Compare commits

..
54 Commits
Author SHA1 Message Date
thuttu 526ca767b1 Android security implementation Phase 2 finalization part 1 2026-11-03 23:16:16 +02:00
thuttu 3ada3c2ce8 Android security implementation Phase 1 finalization part 1 2026-11-03 22:39:32 +02:00
thuttu 9b0009faef Android security implementation Phase 3.4 2026-11-03 19:41:09 +02:00
thuttu 57e194562b Android security implementation Phase 3.3 2026-11-03 18:21:29 +02:00
thuttu 28d63156fb Android security implementation Phase 3.2 update Android_Security_Plan.md for more progress tracking 2026-11-03 18:06:01 +02:00
thuttu e3b3a9bb52 Android security implementation Phase 3.1 2026-11-03 18:05:14 +02:00
thuttu d165fdc4b4 Build increase Phase 02 OpenPGP implementation 2026-11-03 17:05:20 +02:00
thuttu a42774dcf1 Phase 02 OpenPGP implementation 2026-11-03 15:28:43 +02:00
thuttu 0250743250 Start phase 02 on Android security implementation 2026-11-03 11:22:00 +02:00
thuttu 3d5eb5517f Tune Android UI scaling 2026-11-03 10:19:34 +02:00
thuttu b9d46fde1e Fix Android ui scaling and account creation issue 2026-11-03 09:30:14 +02:00
thuttu 1f550dc5c3 Bump version to 0.5.3 2026-11-03 07:56:05 +02:00
thuttu 3963778da1 Implemented the Android notification-privacy part of Phase 1: 2026-11-03 07:49:07 +02:00
thuttu 790051f440 Add Android security Phase 0 2026-11-03 07:32:34 +02:00
thuttu af224beda4 Add ANDROID_SECURITY_PLAN.md to project 2026-11-03 07:16:33 +02:00
thuttu 640fca8a70 Startup Performance tuning 2026-10-18 20:17:28 +03:00
thuttu e63b1c5c8e Third security review is done and added to SECURITY_REVIEW.md 2026-10-17 16:07:06 +03:00
thuttuandCopilot 36ccd2eaf0 Release 0.4.39: copy APK to release dir after build
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-17 15:15:26 +03:00
thuttu ea825adcc1 Implemented desktop OAuth2 account setup for Google and Microsoft. The flow uses the system browser and PKCE; access and refresh tokens stay in the main process and encrypted account store. OAuth connections use fixed provider endpoints, and existing password-based accounts remain supported. Android remains password-based in this phase. 2026-10-17 00:51:23 +03:00
thuttu 1ef934045f Update REFACTOR_PLAN.md tree view and few features to TODO.md 2026-10-17 00:05:37 +03:00
thuttu 82d2f677aa Updated the documentation set to reflect the current architecture and status: 2026-10-16 23:35:32 +03:00
thuttu 60d692f8b4 Refractoring Stage 7.2 Added IPC regression tests verifying native confirmation protects OpenPGP key replacement and trust elevation: cancellation leaves stored key state unchanged, while confirmation permits the change. Bumped to 0.4.38 (Android version code 438) and updated REFACTOR_PLAN.md. 2026-10-16 23:28:34 +03:00
thuttu cdf1b2dd62 Refractoring Stage 7.1 Added sanitizer regression coverage for dangerous nodes and attributes, remote-image URL approval, and keeping remote images inert until explicit loading. Bumped to 0.4.37 (Android version code 437) and updated REFACTOR_PLAN.md. 2026-10-16 23:22:46 +03:00
thuttu cfb6ddc2bb Refractoring Stage 6.24 Moved the HTML sanitizer and remote-image policy API into window.epMailFeatures.contentSecurity, removing the separate window.epMailMailContentSecurity global. Bumped to 0.4.36 (Android version code 436) and updated REFACTOR_PLAN.md. 2026-10-16 23:14:31 +03:00
thuttu bc550cc929 Refractoring Stage 6.23 Moved the mail API factory from the standalone window.epMailUiModules global into window.epMailFeatures.modules; mail-ui.js now uses the shared feature namespace. Bumped to 0.4.35 (Android version code 435) and updated REFACTOR_PLAN.md. 2026-10-16 23:10:21 +03:00
thuttu 7cd3e4a392 Refractoring Stage 6.22 Removed the transitional global aliases from renderer-state.js; renderer state is now exposed only through window.epMailState. Updated the state regression test and bumped to 0.4.34 (Android version code 434). 2026-10-16 23:06:27 +03:00
thuttu ef764183ec Refractoring Stage 6.21 Scoped keyboard shortcut settings and handlers locally; they continue to use the mail and productivity feature APIs. Bumped to 0.4.33 (Android version code 433) and updated REFACTOR_PLAN.md. 2026-10-16 23:00:30 +03:00
thuttu 4fd962cdfd Refractoring Stage 6.20 Scoped the snooze UI helpers locally while preserving its mail and productivity feature API integrations. Bumped to 0.4.32 (Android version code 432) and updated REFACTOR_PLAN.md. 2026-10-16 22:56:54 +03:00
thuttu 590ecc52aa Refractoring Stage 6.19 Scoped attachment preview and search helpers locally; the module continues to use the mail feature API and its existing event-driven integrations. Bumped to 0.4.31 (Android version code 431) and updated REFACTOR_PLAN.md. 2026-10-16 22:51:35 +03:00
thuttu cbb4720353 Refractoring Stage 6.18 Scoped pgp-mail-ui.js behind its existing window.epMailFeatures.pgp API and replaced its leftover global esc dependency with the mail API’s escapeHtml. Bumped to 0.4.30 (Android version code 430) and updated REFACTOR_PLAN.md. 2026-10-16 22:48:59 +03:00
thuttu b9b2a6d031 Refractoring Stage 6.17 Scoped the OpenPGP key-management UI helpers locally; its Preferences integration remains through the productivity API. Bumped the version to 0.4.29 (Android version code 429) and updated REFACTOR_PLAN.md. 2026-10-16 22:41:16 +03:00
thuttu 4b252c774c Refractoring Stage 6.16 Scoped mail-ui.js behind its existing window.epMailFeatures.mail API, removing its implementation functions and state from the shared global scope. Bumped the version to 0.4.28 (Android version code 428) and updated REFACTOR_PLAN.md. 2026-10-16 22:37:25 +03:00
thuttu 0f2014213e Refractoring Stage 6.15 Scoped the core app.js implementation locally; other renderer scripts continue to access it through window.epMailShell. Bumped the version to 0.4.27 (Android version code 427) and updated REFACTOR_PLAN.md. 2026-10-16 22:32:57 +03:00
thuttu 9759c3579a Refractoring Stage 6.14 Encapsulated dav-ui.js’s helpers in a local scope while keeping its public DAV feature API intact. Bumped the version to 0.4.26 (Android version code 426) and updated REFACTOR_PLAN.md. 2026-10-16 22:28:00 +03:00
thuttu 928410b10e Refractoring Stage 6.13 Encapsulated productivity.js in a local scope; its consumers continue to use the existing productivity feature API. Bumped the version to 0.4.25 (Android version code 425) and updated REFACTOR_PLAN.md. 2026-10-16 22:22:14 +03:00
thuttu 26d79fd836 Refractoring Stage 6.12 Bumped the version to 0.4.24 (Android version code 424) and removed the snooze UI’s implicit global call to the productivity label action; it now uses the productivity feature API. 2026-10-16 22:14:37 +03:00
thuttu e80f285e8c Refractoring Stage 6.11 The account manager now uses explicit mail and DAV feature APIs, is scoped locally instead of exposing a global helper, and loads after the DAV feature registers its API. Root and www/ assets are synchronized. 2026-10-16 22:11:52 +03:00
thuttu 3013e489ed Refractoring Stage 6.10 Completed the next renderer modularization slice. mail-ui.js now uses an explicit epMailShell API for core UI helpers and renderer hooks, and the OpenPGP key UI uses feature APIs instead of legacy globals. 2026-10-16 22:05:31 +03:00
thuttu 718ceb6efe Refractoring Stage 6.9 Moved the OpenPGP key UI’s active-account lookup to the mail feature API. The renderer now uses explicit APIs for account, snooze, attachment, OpenPGP mail/key, shortcuts, and DAV integrations; remaining transitional globals are mainly in the core shell and cross-feature hooks. 2026-10-16 21:48:40 +03:00
thuttu 1445d42563 Refractoring Stage 6.8 The core app shell now reads and updates shared UI state through window.epMailState; Calendar and Contacts navigation also uses the productivity feature API. 2026-10-16 21:31:47 +03:00
thuttu f4683b6508 Refractoring Stage 6.7 Migrated DAV calendar/contact state and rendering calls to the productivity feature API, and made the app shell navigate through that API rather than directly calling legacy renderer globals. 2026-10-16 21:14:57 +03:00
thuttu 38340442f0 Refractoring Stage 6.6 Migrated productivity.js and shortcuts.js mail-state access and render/preferences hooks to the mail feature API. 2026-10-16 21:03:40 +03:00
thuttu 84a63441ef Refractoring Stage 6.5 Migrated the snooze, attachment, and OpenPGP mail UI to the explicit mail feature API. 2026-10-16 20:31:59 +03:00
thuttu f19573a337 Refractoring Stage 6.4 Migrate remaining mail-related consumers and remove transitional global dependencies. 2026-10-16 20:17:22 +03:00
thuttu d14c1cfb07 Refractoring Stage 6.3 Convert mail UI to explicit feature APIs and remove legacy global dependencies. 2026-10-16 18:39:09 +03:00
thuttu c1961a4059 Refractoring Stage 6.2 Completed the first renderer modularization slice: 2026-10-16 18:30:22 +03:00
thuttu 297fe77fc1 Refractoring Stage 6.1 Started renderer modularization with shared state. 2026-10-16 18:17:48 +03:00
thuttu 0737892766 Refractoring Stage 5 Completed the IPC feature-grouping step. 2026-10-16 18:07:16 +03:00
thuttu 52f7001b34 Refractoring Stage 5 Moved the OpenPGP and DAV IPC handlers into desktop/ipc/pgp.cjs and desktop/ipc/dav.cjs. 2026-10-16 17:38:48 +03:00
thuttu 928e6dd62a Refractoring Stage 5 Completed channel-specific IPC validation 2026-10-16 17:26:51 +03:00
thuttu 88a8729f4f Refractoring Stage 5 DAV functions EDIT/DEL tied to creators account 2026-10-16 17:15:20 +03:00
thuttu 0b52949f23 Refractoring Stage 4 Completed IPC hardening 2026-10-16 17:08:02 +03:00
thuttu da543d5059 Refractoring Stage 3 Completed the mail-service refactoring stage and started IPC hardening 2026-10-16 16:57:07 +03:00
thuttu e398bc4e1a Refractoring Stage 2 Add Refractor plan.md 2026-10-16 16:27:09 +03:00
179 changed files with 46023 additions and 17795 deletions
+102
View File
@@ -0,0 +1,102 @@
# Android security plan for ep-mail
Status: **Experimental Android OpenPGP implementation for local testing; security review and release gate remain open.** This document tracks Android protections and the remaining work. Neither the test implementation nor this plan is a security certification or a substitute for an independent review.
Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECURITY_REVIEW.md), and [TODO.md](./TODO.md).
## Implementation progress (2026-11-03)
- **Phase 0 — Baseline:** The merged release manifest and core WebView/network settings have now been reviewed and hardened. TLS certificate integration tests, the complete plugin audit, and a production-signed APK review remain open, so the Phase 0 release gate is not closed.
- **Phase 1 — Local data/privacy:** Notification privacy, immediate background app locking, `FLAG_SECURE` while locked, account-removal disclosure, and a fail-closed missing-key recovery screen are implemented. Vault lifecycle, complete deletion semantics, and app-lock lifecycle/biometric follow-up remain open.
- **Phase 2 — Android OpenPGP:** Experimental test implementation is present. It is not security-reviewed or release-complete.
- **Phase 3 — WebView/bridge:** Important protections are implemented; complete bridge review and device/content testing remain open.
- **Phase 4 — Assurance:** Open; independent review, release assurance, and vulnerability/maintenance work remain.
Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed.
OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, on-demand PGP/MIME or inline-encrypted-message decryption, and verification of signed-only PGP/MIME and clear-signed messages. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**.
**Validation evidence:** DAV URL, attachment-name, notification privacy, Android OpenPGP policy decisions, one-shot confirmation callbacks, and the missing-vault-key policy have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock/unlock; with the lock active, emulator screenshots were fully obscured, and unlocking/turning the setting off restored the app. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. The Android OpenPGP module also has automated GnuPG interoperability tests in a Node harness, but those are not device-level mail tests. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Current validation: 157 Node tests and 21 Android unit tests pass; the Android debug build and release-manifest task succeed. Device testing of vault-corruption/key-loss recovery, invalid-certificate integration tests, production-signed APK review, and automated instrumentation of the actual confirmation dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android.
**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric design; invalid-certificate integration tests; production-signed APK/manifest review; app-lock recovery polish; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain.
## 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)
- [x] Generate and review the V0.5.11 worktree release-variant merged manifest. It uses package `studio.daybreak.mail`, versionCode 511/versionName 0.5.11, minSdk 24/targetSdk 36; `allowBackup=false`, `usesCleartextTraffic=false`, and data-extraction exclusions for root/files/databases/shared preferences/external storage. The release manifest has no `debuggable=true` attribute. `MainActivity` is exported only for the launcher; WorkManager's exported job service is protected by `BIND_JOB_SERVICE`; diagnostics/profile receivers require `DUMP`; other merged components are non-exported. The only declared permissions are network, foreground data sync, notifications, wake lock, network-state/boot support, and a signature-protected dynamic-receiver permission. The unused broad `FileProvider` and wildcard origin are absent. The V0.5.10 published APK itself remains debug-signed; no production-signed artifact has been reviewed.
- [~] Review release WebView settings. Web contents debugging now follows `BuildConfig.DEBUG`; file/content access, file-URL cross-access, automatic JavaScript windows, and geolocation are disabled; mixed content is explicitly `NEVER_ALLOW`. The packaged app uses the HTTPS localhost origin. The hardened build compiles and loads the app/Capacitor bridge in the emulator; a full supported-device review remains open.
- [~] Require TLS and hostname validation on IMAP/SMTP and DAV. DAV is restricted to HTTPS and the configured origin; transport requires STARTTLS or implicit TLS and verifies host identity. Unit tests check those settings and absence of permissive trust/socket-factory overrides. Invalid, expired, and mismatched certificate integration tests and a full native-client review remain open.
- [~] Review `EpMailPlugin` as an untrusted-input boundary. DAV URLs and attachment names have specific native validation; PGP MIME structure and send confirmations have added native checks. A complete method-by-method bridge review and comprehensive size/state tests remain open.
- [~] Keep signing keys outside the repository, label debug APKs, and require environment-provided credentials for signed builds. No Android release-signing variables are configured here; published Android APKs are clearly labeled debug/test-only, and no production-signed APK has been reviewed.
- [x] Remove/sanitize sensitive native logging; the current mail sync log omits mailbox content and credentials.
**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)
- [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. If the key alias is missing while encrypted data remains, the app now refuses to generate a replacement key and shows a recovery screen; it does not reset or expose the data. Add device tests for missing/invalidated keys, corrupted ciphertext, reinstall/migration handling, and the recovery instructions; verify no plaintext fallback for all stored data.
- [~] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation now says downloaded attachment files and global OpenPGP keys are retained. Decide/test whether a separate app-data wipe should remove app-created Downloads and PGP keys; account removal intentionally leaves those user data intact.
- [x] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting.
- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` while locked to hide task-switcher content and block screenshots; emulator smoke testing confirmed screenshots are obscured. Background sync continues and the setting is off unless enabled. Delayed lock, automated lifecycle/process-recreation tests, biometric UX, and recovery polish remain open.
- [x] Background sync is separate from the UI lock. Further verification of which credentials/key material are available to background workers remains part of the vault lifecycle review.
**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)
- [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Automated Node-harness tests exercise the Android module against GnuPG; independent review and on-device GnuPG/Thunderbird interoperability remain release blockers.
- [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized. Biometric wrapping-key release, lifecycle/recovery handling, and automated checks against unprotected-key persistence remain open.
- [ ] Add optional biometric/device-credential release of PGP key access and test Keystore invalidation/recovery. Background sync does not use PGP private keys.
- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, trust, and public keys offered as message attachments (never imported silently). Native prompts guard trust elevation and replacement; automated cancel/confirm regression tests remain open.
- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open.
- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open.
- [x] Key-server lookup and publication are disabled in the initial Android test implementation.
**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)
- [~] Mail HTML is sanitized, remote images are blocked until per-message approval, and CSP restrictions are in place. Verify the generated release assets/CSP against the reviewed source on supported devices.
- [x] External URLs are constrained and require user confirmation before opening outside the WebView; unsafe schemes are rejected.
- [~] Broad unused filesystem/navigation capabilities have been removed, but a complete review of every Capacitor plugin/method and permission remains open.
- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open.
**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)
- [ ] Add/maintain Android dependency scanning and an update policy; review licenses and security-critical versions. Three moderate production dependency advisories are still open for compatibility review.
- [ ] Run static analysis, merged-manifest review, and Android/MASVS-aligned checks against a production release; bind evidence to that APK's version and hash.
- [ ] Obtain independent human review of the Keystore/vault, bridge, TLS, and OpenPGP implementation before making security-reviewed claims.
- [ ] Publish user-facing Android security, key-backup, and recovery guidance.
- [ ] Define a vulnerability-reporting contact, triage process, supported Android versions, 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.
+8 -6
View File
@@ -9,14 +9,15 @@ This project has a layered architecture: a desktop Electron shell, a browser-ren
- `desktop/main.cjs` is the privileged process. - `desktop/main.cjs` is the privileged process.
- It owns account storage, mail sync, IMAP/SMTP connectivity, DAV sync, and OpenPGP key handling. - It owns account storage, mail sync, IMAP/SMTP connectivity, DAV sync, and OpenPGP key handling.
- It can show native dialogs, notifications, and system prompts. On Windows, its notification-area tray icon uses the packaged multi-resolution application icon and provides Open and Quit actions. Packaged startup repairs an existing per-user Start Menu shortcut to target the launched app and use its icon, keeping taskbar pins associated with the matching AppUserModelID. - It can show native dialogs, notifications, and system prompts. On Windows, its notification-area tray icon uses the packaged multi-resolution application icon and provides Open and Quit actions. Packaged startup repairs an existing per-user Start Menu shortcut to target the launched app and use its icon, keeping taskbar pins associated with the matching AppUserModelID.
- `desktop/preload.cjs` exposes a minimal API to the renderer through `window.daybreakMail` and `window.pgpPrepareSend`. - `desktop/preload.cjs` exposes the narrow platform API through `window.daybreakMail`. Renderer-to-renderer contracts are grouped under `window.epMailState`, `window.epMailShell`, and `window.epMailFeatures`.
### Renderer UI ### Renderer UI
The browser UI is rendered from the web assets in the root and `www/` folders: The browser UI is rendered from canonical web assets in the repository root; `www/` is generated for Capacitor:
- `index.html` and the shared shell files define the layout and global state. - `index.html` defines the classic-script bootstrap order. `renderer-state.js` exposes shared state as `window.epMailState` without legacy unnamespaced aliases.
- `app.js`, `mail-ui.js`, `account-ui.js`, `dav-ui.js`, `pgp-ui.js`, and `pgp-mail-ui.js` handle page flow, compose/read views, account setup, and encryption UX. - `app.js` publishes `window.epMailShell`; the mail, productivity, DAV, and PGP mail modules publish explicit APIs under `window.epMailFeatures`. PGP key management extends the productivity Preferences UI through that API.
- Renderer feature implementations are locally scoped. The ordered classic-script bootstrap remains a compatibility constraint for desktop and Capacitor, and is covered by bootstrap and combined-script tests.
- The renderer is intentionally thin: it requests actions and displays data, while mail-protocol and cryptographic network work stays in the main process. The reader makes direct HTTPS image requests only after explicit per-message approval. - The renderer is intentionally thin: it requests actions and displays data, while mail-protocol and cryptographic network work stays in the main process. The reader makes direct HTTPS image requests only after explicit per-message approval.
### Android client ### Android client
@@ -33,7 +34,7 @@ The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.c
The main process owns the canonical account model and persists it in an encrypted store: The main process owns the canonical account model and persists it in an encrypted store:
- `mail-account.enc` stores connected IMAP/SMTP accounts and their settings. - `mail-account.enc` stores connected IMAP/SMTP accounts, settings, and desktop OAuth tokens; OAuth refresh tokens never enter the renderer API.
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config. - `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
- `pgp-keys.enc` stores OpenPGP keys and trust data. - `pgp-keys.enc` stores OpenPGP keys and trust data.
@@ -70,6 +71,7 @@ The current architecture takes a strict trust split:
This boundary is important for encryption and safety checks: This boundary is important for encryption and safety checks:
- OpenPGP key selection and trust updates are confirmed in the main process. - OpenPGP key selection and trust updates are confirmed in the main process.
- Replacement-key operations are also confirmed in the main process; tests assert cancellation does not update the contact key.
- Key-server lookup results never elevate trust; only the public key is sent during a separately confirmed publication. - Key-server lookup results never elevate trust; only the public key is sent during a separately confirmed publication.
- Send-time downgrade checks happen in the main process rather than only in UI logic. - Send-time downgrade checks happen in the main process rather than only in UI logic.
- External links open only after a native confirmation dialog. - External links open only after a native confirmation dialog.
@@ -83,7 +85,7 @@ The OpenPGP implementation is split into focused modules:
- `desktop/pgp-keystore.cjs` stores contacts, trust, key material, and settings. - `desktop/pgp-keystore.cjs` stores contacts, trust, key material, and settings.
- `desktop/pgp-mail.cjs` handles message detection, decryption, verification, encryption, and signature checks. - `desktop/pgp-mail.cjs` handles message detection, decryption, verification, encryption, and signature checks.
- `desktop/pgp-keyservers.cjs` implements bounded HTTPS lookup and publication for VKS and HKP-compatible servers. - `desktop/pgp-keyservers.cjs` implements bounded HTTPS lookup and publication for VKS and HKP-compatible servers.
- `desktop/main.cjs` bridges those services into the Electron IPC API. - `desktop/ipc/pgp.cjs` bridges those services into the Electron IPC API; `desktop/main.cjs` wires the services and registrars together.
This keeps the cryptographic logic separate from the UI and gives the app a single place to enforce trust rules, passphrase checks, and recipient validation. This keeps the cryptographic logic separate from the UI and gives the app a single place to enforce trust rules, passphrase checks, and recipient validation.
+3 -3
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 support and an independent security review are still open; see [TODO.md](./TODO.md). 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.
## 1. Format: OpenPGP with PGP/MIME (RFC 3156) ## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
@@ -63,7 +63,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend. - [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend.
- [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs. - [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs.
- [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`. - [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`.
- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Hidden on platforms without a key store (Android until Phase 4). - [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Desktop key management is production functionality; Android exposes an experimental test UI.
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)). - Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
## 7. Phases 2–5 implementation notes ## 7. Phases 2–5 implementation notes
@@ -72,7 +72,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting. - [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting.
- Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload. - Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload.
- Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key. - Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key.
- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android does not yet implement OpenPGP. - Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android's test path supports this format up to 25 MiB, but it has not completed desktop parity, independent review, or release assurance.
- Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply. - Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply.
- A signature from a key that differs from the one on file for the sender is flagged as a changed key. - A signature from a key that differs from the one on file for the sender is flagged as a changed key.
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed). - Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
+7 -3
View File
@@ -8,20 +8,24 @@ The Electron app runs in its own window. On Windows, ep-mail also shows its icon
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. 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.
### Google and Microsoft OAuth2
Desktop account setup supports Google and Microsoft OAuth2 when provider client configuration is supplied to the Electron process. Set `EP_MAIL_GOOGLE_OAUTH_CLIENT_ID` (and `EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET` if issued for the desktop client) and/or `EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID`; `EP_MAIL_MICROSOFT_OAUTH_TENANT_ID` is optional and defaults to `common`. Register the corresponding native/desktop public client with a loopback redirect URI. Microsoft app registrations must allow public-client authorization and delegated IMAP/SMTP permissions. Google's full Gmail mail scope is restricted; production use may require app verification, and unverified projects may need the account added as a test user. OAuth sign-in opens the system browser, uses PKCE, and stores refresh/access tokens only in the encrypted account store. Android continues to use its existing password-based account setup.
On packaged Windows builds, startup repairs an existing per-user Start Menu shortcut to point to the launched installed or portable executable and use its icon and AppUserModelID. Windows may keep a cached icon for an existing taskbar pin; if so, unpin and pin ep-mail again after launching the updated build. On packaged Windows builds, startup repairs an existing per-user Start Menu shortcut to point to the launched installed or portable executable and use its icon and AppUserModelID. Windows may keep a cached icon for an existing taskbar pin; if so, unpin and pin ep-mail again after launching the updated build.
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md). See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
## Android app ## Android app
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run: The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, encrypted account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Android Settings can enable an app lock that covers the WebView and disables its JavaScript bridge when the app leaves the foreground; it also hides the locked screen from screenshots and recent-app previews. Unlock requires the device PIN, pattern, or password, while background mail sync continues. Configure a secure Android screen lock before enabling it. This is a local privacy control, not protection against a compromised or rooted device. Android OpenPGP is now present as an **experimental test-only feature** for key and message testing. It has not had an independent cryptography/security review and is not approved for sensitive or production mail; do not rely on it to protect important messages. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
```sh ```sh
npm install npm install
npm run android:apk npm run android:apk
``` ```
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk`. Install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`, or open the project in Android Studio with `npm run android:open`. 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. 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.
## Run on Windows or Linux ## Run on Windows or Linux
@@ -35,4 +39,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
## Current scope ## Current scope
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`. Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop supports encrypted and signed OpenPGP mail. Android has an experimental test implementation for key management and PGP/MIME send/read; it is not independently reviewed and is not suitable for sensitive mail (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)). Run the tests with `npm test`.
+219
View File
@@ -0,0 +1,219 @@
# Modularity and security refactoring plan
## Goal
Improve the maintainability and auditability of ep-mail without changing its product behavior or weakening the existing Electron/renderer security boundary. Refactor incrementally, keeping each step testable and reversible.
## Current assessment
- `desktop/main.cjs` combines Electron lifecycle, IPC registration, account persistence, IMAP/SMTP work, background sync, outbox processing, DAV, and attachment workflows.
- Renderer code is loaded as classic scripts with shared global state and implicit load-order dependencies.
- Root web assets are copied into `www/` for Capacitor. Treat root assets as source and `www/` as generated output; do not hand-edit generated copies.
- Electron currently enables context isolation and sandboxing, and disables Node integration. Keep these controls in place.
- Existing tests focus mainly on OpenPGP and attachments; IPC, storage, and mail workflow boundaries need more coverage.
- The web content is sanitized and remote images are approval-gated. Preserve and add regression coverage for these protections.
## Current boundaries and target direction
```text
desktop/
main.cjs, preload.cjs # Electron startup, lifecycle, narrow bridge
ipc/ # Mail, DAV, and OpenPGP handler registrars
mail/ # IMAP/SMTP, sync, outbox, snooze, attachments
dav/ # DAV remote-reference validation
security/ # IPC sender and request validation
pgp-*.cjs # OpenPGP key, mail, and key-server services
account-store.cjs # Account-record migration
secure-json-store.cjs # Encrypted JSON persistence
mail-*.cjs, dav-codecs.cjs # Mail models, content projection, DAV codecs
index.html # Shared desktop/browser/Capacitor entry point
app.js, *-ui.js, *.css # Shared renderer sources (canonical)
renderer-state.js # Shared namespaced renderer state
renderer-mail-api.js # Shared renderer feature API factory
mail-content-security.js # HTML sanitizer and remote-image policy
platform-bridge.js # Generated platform bridge
www/ # Generated Capacitor web assets; do not edit
scripts/prepare-android-web.cjs # Copies root web assets into www/
```
Keep the shared renderer outside `desktop/`: Electron, the browser build, and Android all use these web sources. The root files are canonical and `www/` is generated. Desktop service boundaries are reflected by the existing `desktop/ipc/`, `desktop/mail/`, `desktop/dav/`, and `desktop/security/` directories.
IPC modules should validate and translate renderer requests, then call services. Services should not depend on Electron IPC or window objects. Pass dependencies such as storage, network clients, clocks, and notification callbacks explicitly where practical. A future move of shared UI sources into a dedicated `renderer/` directory is optional, not required for this plan; it would need coordinated updates to `index.html` script/style URLs, Electron Builder file inclusion, Android copying, service-worker precache paths, and asset-parity tests.
## Steps and acceptance criteria
### 1. Baseline and guardrails — complete
- [x] Record the current test baseline.
- [x] Confirm the current root/`www/` web assets match.
- [x] Document source-versus-generated asset ownership and add a regression check for drift.
- [x] Preserve unrelated working-tree changes.
**Acceptance:** `npm test` passes, the asset check passes, and no runtime behavior changes in this step.
**Result:** all acceptance checks passed; the suite now contains 38 passing tests.
### 2. Extract pure helpers — complete
- [x] Extract account/input normalization and public account mapping (`desktop/mail-model.cjs`).
- [x] Extract folder validation and message filtering (`desktop/mail-model.cjs`).
- [x] Extract parsed-message display projection (`desktop/mail-content.cjs`).
- [x] Extract DAV iCalendar/vCard serialization (`desktop/dav-codecs.cjs`).
- [x] Add isolated unit tests for these helpers.
**Acceptance:** helper tests do not need Electron or live mail/DAV servers; existing tests remain green.
**Result:** helper modules are tested independently; `npm test` passes 47 tests. Runtime-facing call sites in `desktop/main.cjs` now import the extracted functions.
### 3. Isolate secure persistence — complete
- [x] Move account, DAV, and OpenPGP encrypted JSON file I/O behind `desktop/secure-json-store.cjs`.
- [x] Move legacy account-record migration behind `desktop/account-store.cjs`.
- [x] Keep OS-backed encryption checks, migration behavior, atomic writes, and Linux `basic_text` rejection intact.
- [x] Add tests using injected storage/encryption adapters.
**Acceptance:** services no longer manage secure-store paths directly, and persistence behavior is covered by tests.
**Result:** persistence adapters and legacy migration are covered independently; `npm test` passes 54 tests.
### 4. Split mail services — complete
- [x] Extract SMTP submission and Sent-copy handling (`desktop/mail/send-service.cjs`).
- [x] Extract IMAP special-folder discovery and folder-path resolution (`desktop/mail/folders.cjs`).
- [x] Extract mailbox page/search reads (`desktop/mail/read-service.cjs`).
- [x] Extract message actions (`desktop/mail/action-service.cjs`).
- [x] Extract mailbox reconciliation and rule application (`desktop/mail/sync-service.cjs`).
- [x] Extract background scheduling, per-account backoff, and request coalescing (`desktop/mail/sync-coordinator.cjs`).
- [x] Extract IMAP IDLE watcher lifecycle (`desktop/mail/idle-watcher-manager.cjs`).
- [x] Extract snooze reminder processing (`desktop/mail/snooze-reminder-service.cjs`).
- [x] Extract offline outbox processing and optimistic cache updates (`desktop/mail/outbox-service.cjs`).
- [x] Extract attachment saving and preview workflows (`desktop/mail/attachment-service.cjs`).
**Acceptance:** mail services can be tested with fake clients/stores; generation invalidation, connection cleanup, and no-plaintext PGP queueing remain covered.
**Result:** mail protocol, outbox, attachment, scheduling, IDLE, and snooze workflows are isolated behind injected dependencies; `npm test` passes 92 tests.
### 5. Harden and modularize IPC — complete
- [x] Verify the IPC sender is the expected top-level application document (`desktop/security/ipc-sender.cjs`).
- [x] Restrict navigation to the exact app document URL; reject arbitrary `file:` navigation.
- [x] Validate channel names, argument counts/types, and nested payload complexity (`desktop/security/ipc-arguments.cjs`).
- [x] Bind DAV object updates/deletes to the selected account, server collection, server-returned resource, and current ETag (`desktop/dav/remote-reference.cjs`).
- [x] Validate channel-specific fields and limits; reject renderer-supplied raw SMTP payload fields.
- [x] Group OpenPGP handlers and source fetching in `desktop/ipc/pgp.cjs`, retaining the shared IPC boundary.
- [x] Group mail/account handlers in `desktop/ipc/mail.cjs`.
- [x] Group DAV handlers in `desktop/ipc/dav.cjs`; keep `preload.cjs` as the narrow renderer API.
- [x] Retain public account and DAV config projections rather than exposing secret-bearing store records.
**Acceptance:** IPC tests cover malformed inputs and rejected senders; privileged behavior remains in trusted code.
**Result:** OpenPGP, mail/account, and DAV handler groups now register through the same sender and payload validation wrapper. Registration/schema tests cover all feature modules.
### 6. Modularize renderer incrementally — complete
- [x] Introduce a namespaced shared renderer-state module with transitional classic-script accessors (`renderer-state.js`).
- [x] Extract mail HTML sanitization and remote-image approval checks into a dedicated renderer API (`mail-content-security.js`).
- [x] Add an explicit mail feature API and migrate the account manager to it (`renderer-mail-api.js`, `account-ui.js`).
- [x] Migrate snooze UI state/sync access to the mail feature API (`snooze-ui.js`).
- [x] Migrate attachment UI state, selectors, and message hooks to the mail feature API (`attachments.js`).
- [x] Migrate OpenPGP mail UI reader/compose hooks to the mail feature API (`pgp-mail-ui.js`).
- [x] Migrate shortcut mail-state access and preferences extension to feature APIs (`shortcuts.js`, `productivity.js`).
- [x] Migrate Calendar/Contacts navigation and DAV UI to the productivity feature API (`app.js`, `dav-ui.js`).
- [x] Migrate OpenPGP key UI to the mail feature API for active-account access (`pgp-ui.js`).
- [x] Make the core app shell consume the namespaced renderer state instead of compatibility aliases.
- [x] Expose core shell behavior through an explicit renderer API and migrate mail UI selectors, notifications, rendering, and compose hooks to that API (`app.js`, `mail-ui.js`).
- [x] Hide the account-manager script in a local module scope and route selectors, escaping, notifications, and DAV navigation through explicit feature APIs (`account-ui.js`, `dav-ui.js`).
- [x] Route the snooze action's message-label hook through the productivity feature API (`snooze-ui.js`, `productivity.js`).
- [x] Encapsulate productivity implementation state and helpers in a local module scope, preserving the explicit productivity feature API (`productivity.js`).
- [x] Encapsulate DAV helpers in a local module scope while preserving `window.epMailFeatures.dav` (`dav-ui.js`).
- [x] Encapsulate core renderer implementation behind `window.epMailShell` (`app.js`).
- [x] Encapsulate mail UI implementation behind `window.epMailFeatures.mail` (`mail-ui.js`).
- [x] Encapsulate OpenPGP key-management UI helpers locally; it contributes to Preferences through the productivity API (`pgp-ui.js`).
- [x] Encapsulate OpenPGP mail helpers behind `window.epMailFeatures.pgp` and use the mail API's HTML escaping helper (`pgp-mail-ui.js`).
- [x] Encapsulate attachment UI helpers locally; its navigation and renderer hooks continue through the mail API (`attachments.js`).
- [x] Encapsulate snooze UI helpers locally while preserving explicit mail/productivity API usage (`snooze-ui.js`).
- [x] Encapsulate keyboard shortcut settings and handlers locally; integrations remain through the mail/productivity feature APIs (`shortcuts.js`).
- [x] Remove transitional renderer-state globals after all consumers migrated to the namespaced state API (`renderer-state.js`).
- [x] Register the mail API factory under the shared feature namespace instead of a standalone renderer global (`renderer-mail-api.js`, `mail-ui.js`).
- [x] Register content security helpers under the shared feature namespace instead of a standalone global (`mail-content-security.js`, `app.js`).
- [x] Migrate additional mail-related consumers to unique local aliases to avoid classic-script lexical redeclarations.
- [x] Add a combined-script parse test to prevent duplicate top-level lexical declarations from stopping later UI scripts.
- [x] Migrate remaining mail-related consumers and remove legacy/transitional global dependencies.
- [x] Make cross-feature dependencies explicit through namespaced APIs and test the required classic-script load order.
- [x] Keep root web assets canonical and verify generated `www/` parity.
- [x] Preserve CSP, HTML sanitization, and per-message remote-image approval behavior with regression coverage.
**Acceptance:** both desktop and Android builds include the intended modules and existing user-visible flows still work.
**Result:** renderer features are locally scoped behind `epMailState`, `epMailShell`, and `epMailFeatures` APIs. The classic-script bootstrap remains intentionally ordered for desktop/Capacitor compatibility, with that order covered by tests. The user has confirmed successive built artifacts work.
**Deferred follow-up:** migrate the renderer from classic scripts to native ES modules; this is not required to complete the incremental modularization step above.
### 7. Security regression coverage and review — in progress
- [x] Cover HTML sanitization and remote-image validation/approval gating.
- [x] Cover DAV URL/object validation and current ETag binding.
- [ ] Add direct IPC-handler coverage for main-process plaintext-send downgrade confirmation (the confirmation behavior exists; its critical accept/cancel branch is not directly tested yet).
- [x] Cover native OpenPGP trust elevation and replacement-key confirmation, including cancellation behavior.
- [ ] Complete the human review and remaining items in `SECURITY_REVIEW.md` (dependency audit/version pinning and Android encryption limitations included).
**Acceptance:** security-sensitive behaviors have regression tests, and unresolved risks are documented rather than silently treated as fixed.
## Execution notes
- Do not combine architectural refactoring with feature work or broad dependency upgrades.
- Run `npm test` after each extraction; run desktop/Android build checks at relevant integration points.
- Keep changes small and inspect generated output before replacing it. The Android preparation script recreates `www/`, so edits there are not authoritative.
## Build version coordination
- `package.json` is the canonical application version; keep both `package-lock.json` version fields synchronized with it.
- Electron Builder and the desktop Actions artifact name derive from `package.json`.
- Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions.
- `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump.
- Latest version check: `package.json` and both lockfile version fields are `0.5.0`; Android derives `versionName 0.5.0` and `versionCode 500`. OAuth2 desktop support is in this source version; the artifact still needs to be built and verified.
## Progress log
- Initial baseline: `npm test` passed 37 tests on 2026-10-16.
- Initial inspection found matching root/`www/` web assets.
- `package.json` has a pre-existing user change allowing the `esbuild@0.28.2` install script; it is being preserved.
- Step 1 added a generated-web-asset parity test; the full suite passed 38 tests.
- Step 2 extracted pure account, folder, mail-content, filtering, and DAV codec helpers; the full suite passed 47 tests.
- Step 3 extracted encrypted JSON persistence and account migration; the full suite passed 54 tests.
- Step 4 extracted injected SMTP, IMAP folder/read/action, outbox, attachment, mailbox-sync, and scheduling services; the full suite passed 86 tests.
- Step 4 completed with extracted IDLE and snooze services; the full suite passed 92 tests.
- Step 5 added a trusted top-level sender check to all 54 registered IPC handlers; sender boundary tests pass.
- Step 5 also aligned `will-navigate` with the same exact-document policy; `npm test` passes 96 tests.
- Step 5 added request schemas for all 54 registered channels, plus depth/collection/string bounds. Base64 attachment payloads remain uncapped to preserve the existing no-total-size-cap behavior.
- Step 5 also binds DAV updates/deletes to the configured account, same-origin collection, a server-listed resource, and a current ETag; DAV IDs are constrained against line injection and path traversal.
- Step 5 moved OpenPGP handler registration and message-source fetching into a feature module and added registration/schema coverage.
- Step 5 moved DAV handler registration into a feature module and added registration/schema coverage; the full suite passes 110 tests.
- Step 5 grouped mail/account handlers in `desktop/ipc/mail.cjs`; all 114 tests pass and the remaining app-version handler stays in the Electron shell.
- Added a build-version consistency check; the initial verification was at package version `0.4.21` / Android build number `421`.
- Step 5 grouped mail/account handlers and added a release-version consistency test; current package/lockfile/Android version alignment was checked and documented.
- Step 6 added `renderer-state.js`, extracted the mail HTML security API, and introduced `renderer-mail-api.js`; `account-ui.js` now uses that explicit API instead of several mail globals. Transitional aliases remain for other classic scripts.
- Step 6 migrated snooze, attachment, OpenPGP mail/key, shortcut, productivity state/render, and DAV UI integrations to feature APIs; compatibility globals remain in the core shell and some cross-feature hooks. The core app now reads shared state through `renderer-state.js`; the suite passes 123 tests.
- Step 6 added an explicit `epMailShell` interface for mail UI selectors, notifications, views, and renderer wrappers. `mail-ui.js` now uses it rather than directly replacing core renderer functions; search resets use namespaced state, and preferences remain owned by the productivity feature.
- Step 6 verification at version `0.4.22` / Android build number `422`: all 123 tests pass, including generated `www/` parity and combined classic-script parsing.
- Step 6 at version `0.4.23` moves account-manager dependencies onto feature APIs and publishes the DAV manager through `window.epMailFeatures.dav` instead of a free global function.
- Step 6 at version `0.4.24` removes the snooze-to-productivity label action's implicit global call; account and snooze feature API checks are covered by the renderer tests.
- Step 6 at version `0.4.25` wraps productivity internals in a local scope; Calendar, Contacts, labels, and profile behavior remain published through the productivity feature API.
- Step 6 at version `0.4.26` wraps DAV UI internals in a local scope while preserving the public DAV feature API.
- Step 6 at version `0.4.27` scopes core renderer functions and state in `app.js`; other scripts continue through the explicit `epMailShell` interface.
- Step 6 at version `0.4.28` scopes mail UI implementation details while retaining its explicit mail feature API.
- Step 6 at version `0.4.29` scopes OpenPGP key UI implementation helpers without changing its Preferences integration.
- Step 6 at version `0.4.30` scopes PGP mail helpers, preserving the `prepareSend` API and removing its dependency on the core shell's former global HTML escape helper.
- Step 6 at version `0.4.31` scopes attachment preview and search helpers while retaining their event-driven integrations.
- Step 6 at version `0.4.32` scopes snooze UI helpers; message labeling and mail-state access remain routed through feature APIs.
- Step 6 at version `0.4.33` scopes keyboard shortcut helpers and event handlers without changing their Preferences integration.
- Step 6 at version `0.4.34` removes legacy global renderer-state accessors; the state module now exposes only `window.epMailState` to the renderer.
- Step 6 at version `0.4.35` consolidates the mail API factory under `window.epMailFeatures.modules`, removing the separate `window.epMailUiModules` global.
- Step 6 at version `0.4.36` consolidates the HTML sanitization and remote-image policy API under `window.epMailFeatures.contentSecurity`.
- Step 7 at version `0.4.37` adds focused sanitizer coverage for dangerous DOM nodes/attributes and verifies that remote images remain data-only pending explicit loading.
- Step 7 at version `0.4.38` tests main-process native confirmation for OpenPGP key replacement and trust elevation; cancellation must not mutate stored key state.
- Desktop OAuth2 support for Google and Microsoft was added after the `0.4.38` artifact; `0.5.0` uses configurable OAuth client IDs, PKCE, encrypted token persistence, and provider-fixed mail endpoints.
- Step 7 coverage status: sanitizer/remote-image, DAV reference/ETag, and OpenPGP trust/replacement paths have regression coverage. A direct plaintext-send IPC confirmation test and the documented human/security review remain open.
- Renderer modularization step 6 is complete: feature modules are scoped, legacy renderer-state aliases are removed, public cross-feature interfaces are namespaced, and root/`www/` parity plus classic-script ordering are tested. Native ES module conversion remains a deferred follow-up.
- The current IPC/DAV validation changes pass the full suite: 108 tests.
- While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved.
+25 -6
View File
@@ -4,12 +4,14 @@ Date: 2026-10-08
Version reviewed: 0.3.2 (working tree, uncommitted changes included) Version reviewed: 0.3.2 (working tree, uncommitted changes included)
Type: automated review by an AI security-review agent. It is not a substitute for a human review. Type: automated review by an AI security-review agent. It is not a substitute for a human review.
> **Current status (2026-10-16, ep-mail 0.4.38):** The entries below are a historical review record. The replacement-key and trust-elevation confirmations are implemented in the main process and now have IPC regression tests for cancel/confirm behavior. The send-time plaintext downgrade check is enforced in the main process. The user confirms the current built artifact works. A direct IPC test for the plaintext-send confirmation branch and an independent human review remain open; Android OpenPGP support is not implemented.
## Scope ## Scope
- `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust - `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust
- `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache - `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache
- `pgp:*` IPC handlers in `desktop/main.cjs` and `desktop/preload.cjs` - `pgp:*` IPC handlers, now registered in `desktop/ipc/pgp.cjs`, plus the plaintext-send check in `desktop/ipc/mail.cjs`; the original review predates this IPC extraction.
- Renderer: `pgp-mail-ui.js`, `pgp-ui.js`, the `pgpPrepareSend` hook in `mail-ui.js` - Renderer: `pgp-mail-ui.js`, `pgp-ui.js`, and the `window.epMailFeatures.pgp.prepareSend` feature hook used by `mail-ui.js`.
- Design reference: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md) - Design reference: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)
Focus areas: secret leaks (disk, logs, outbox, renderer), IPC abuse by a compromised renderer, HTML injection from key user IDs and decrypted content, signature status spoofing, key matching by fingerprint, silent downgrade to plaintext, malformed or oversized input, passphrase cache lifetime. Focus areas: secret leaks (disk, logs, outbox, renderer), IPC abuse by a compromised renderer, HTML injection from key user IDs and decrypted content, signature status spoofing, key matching by fingerprint, silent downgrade to plaintext, malformed or oversized input, passphrase cache lifetime.
@@ -25,19 +27,19 @@ No critical or high severity issues were reported.
## Fixes applied ## Fixes applied
1. **Send-time check:** `pgpPrepareSend` now checks recipient keys when you press Send. If keys exist for all recipients and you did not change the Encrypt box yourself, it asks before sending unencrypted. Unticking Encrypt on purpose still sends without a prompt. 1. **Send-time check:** the renderer checks recipient keys when you press Send. If keys exist for all recipients and you did not change the Encrypt box yourself, it asks before sending unencrypted. Unticking Encrypt on purpose still sends without a prompt. This renderer hook is now exposed as `window.epMailFeatures.pgp.prepareSend`.
2. **Trusted confirmation:** the `pgp:set-trust` handler in the main process shows a native dialog with the contact and fingerprint before raising trust. A cancelled dialog aborts the change. The renderer's own prompt may appear as well, so users can see two confirmations. 2. **Trusted confirmation:** the `pgp:set-trust` handler in the main process shows a native dialog with the contact and fingerprint before raising trust. A cancelled dialog aborts the change. The renderer's own prompt may appear as well, so users can see two confirmations.
## Verification ## Verification at the original review time
- `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests). - `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests).
- `node --check` on the edited files. - `node --check` on the edited files.
- The fixes were not exercised in the running app. - The fixes were not exercised in the running app.
## Remaining work ## Remaining work recorded after the first review (2026-10-08)
- Human review of the key store, the IPC boundary and the signature UI. - Human review of the key store, the IPC boundary and the signature UI.
- Replacement-key confirmation in the main process when a new key arrives for an address that already has a contact. The review suggested it, and only the trust confirmation was added. - Replacement-key confirmation in the main process when a new key arrives for an address that already has a contact. This was still open at the time; see the later review pass below.
- Run `npm audit` and pin the OpenPGP.js version. - Run `npm audit` and pin the OpenPGP.js version.
- Re-run the GnuPG interoperability tests after dependency updates. - Re-run the GnuPG interoperability tests after dependency updates.
- Android has no encryption support yet, so it was not reviewed. - Android has no encryption support yet, so it was not reviewed.
@@ -56,3 +58,20 @@ Applied fixes:
- #3: native confirmation showing both fingerprints when a key overlaps existing contacts, and the add-contact flow aborts if the replacement is not confirmed. - #3: native confirmation showing both fingerprints when a key overlaps existing contacts, and the add-contact flow aborts if the replacement is not confirmed.
- #4: the main process checks recipient keys before allowing a plaintext send and shows a trusted confirmation dialog. - #4: the main process checks recipient keys before allowing a plaintext send and shows a trusted confirmation dialog.
- #5: Linux now rejects the insecure `basic_text` safeStorage backend and asks the user to switch to a secure system keyring before storing mail or PGP secrets. - #5: Linux now rejects the insecure `basic_text` safeStorage backend and asks the user to switch to a secure system keyring before storing mail or PGP secrets.
## Current follow-up
- Replacement-key and trust-elevation confirmation are enforced in `desktop/ipc/pgp.cjs`. `tests/pgp-ipc-registration.test.cjs` verifies both cancellation and confirmation paths for those changes.
- Main-process plaintext-send confirmation is implemented in `desktop/ipc/mail.cjs`; direct regression coverage for that dialog's accept/cancel branches remains open.
- Human cryptography/security review and dependency remediation remain outstanding. OpenPGP.js is pinned to 6.3.2; `npm audit --omit=dev` currently reports three moderate advisories in `ip-address` and the Nodemailer/mailparser dependency chain. GnuPG interoperability tests are in the current test suite and should be rerun after dependency changes.
- Android's experimental OpenPGP implementation was added after the desktop review and is outside the reviewed scope. It must not be relied on for sensitive mail until independently reviewed. Native prompts for trust elevation, key replacement, and plaintext sending are implemented; emulator smoke tests exercised trust accept/cancel and plaintext cancel. Automated regression coverage and resistance to renderer-policy bypasses remain open.
## Third review pass (2026-10-17)
Fresh automated review of the whole repository (ep-mail 0.4.39), covering the Electron main process, IPC, preload and renderer boundary, mail content handling, storage and crypto, and network and file operations. No code was changed in this pass.
| # | Severity | File | Lines | Vulnerability | Confidence |
|---|----------|------|-------|---------------|------------|
| - | - | - | - | No actionable vulnerabilities found. | - |
The open items under "Current follow-up" still apply: human review, dependency audit, OpenPGP.js version pinning and Android OpenPGP support.
+26 -6
View File
@@ -12,7 +12,7 @@
## Mail workflow ## Mail workflow
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return. - [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
- [ ] Add Undo Send and scheduled sending. - [ ] Add a configurable Undo Send delay and scheduled sending.
- [x] Improve mail search with sender, subject, date, folder, and attachment filters. - [x] Improve mail search with sender, subject, date, folder, and attachment filters.
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns. - [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
- [ ] Group related messages into conversations, with controls to expand or collapse threads. - [ ] Group related messages into conversations, with controls to expand or collapse threads.
@@ -26,17 +26,36 @@
## Mail security ## Mail security
- [ ] Add support for encrypting and decrypting mail with OpenPGP (PGP/MIME). See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md). - [x] Add desktop support for encrypting and decrypting mail with OpenPGP (PGP/MIME); Android has a separate experimental implementation for local testing only. See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md).
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI. - [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases. - [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading. - [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout. - [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
- [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then). - [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption.
- [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-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness.
- [ ] 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.
- [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.
- [x] Manual interoperability check with Thunderbird. - [x] Manual interoperability check with Thunderbird.
- [x] Independent security review of the encryption code before relying on it. - [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)).
- [ ] Complete an independent human security review of desktop and Android encryption code before any production reliance or release.
- [x] Pin OpenPGP.js to the exact lockfile version while security review is pending.
- [ ] Resolve the current moderate dependency advisories reported by `npm audit --omit=dev` with compatibility tests.
- [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation.
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
- [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews.
- [x] Add an optional native Android app lock using the device credential while leaving background mail sync available.
- [x] Set `FLAG_SECURE` while the optional app lock is engaged to hide the screen from screenshots and recents previews.
- [x] Exercise background lock, credential unlock, and screenshot obscuring on an Android emulator.
- [x] Disclose in account-removal confirmation that downloaded files and global OpenPGP keys are retained.
- [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.
- [ ] 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.
## Appearance and settings ## Appearance and settings
@@ -47,6 +66,7 @@
## Account settings ## Account settings
- [x] Add desktop OAuth2 account setup for Google and Microsoft. Configure provider client IDs with the environment variables documented in `README.md`; Android remains password-based.
- [ ] Fix the mailbox space indicator; it is not working. - [ ] Fix the mailbox space indicator; it is not working.
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives. - [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background. - [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
@@ -63,8 +83,8 @@
- [x] Remove the display name initials from the bottom-left corner. - [x] Remove the display name initials from the bottom-left corner.
- [x] Add the ability to delete draft mails. - [x] Add the ability to delete draft mails.
- [x] Fix IMAP folder creation, which does not work. - [x] Fix IMAP folder creation, which does not work.
- [ ] Give the sidebar (Inbox, Folders, etc.) more room so every item fits on screen: make the box scrollable with a slider, or remove or collapse less-used items. - [ ] Improve sidebar usability so all folders fit or can be reached by scrolling; consider collapsing less-used sections.
- [ ] Make labels work and add the ability to create more labels. - [ ] Make labels work reliably and support creating and managing additional labels.
- [x] Fix created IMAP folders not showing in the mail rules folder list; only Inbox, Archive and Trash are shown. - [x] Fix created IMAP folders not showing in the mail rules folder list; only Inbox, Archive and Trash are shown.
- [x] Fix draft mail deletion to work like the Inbox: select multiple drafts and delete the selected drafts at once. - [x] Fix draft mail deletion to work like the Inbox: select multiple drafts and delete the selected drafts at once.
- [x] Show created IMAP folders in the same list as Inbox and the other folders, and move the folder list and the add-folder button to the top row above Inbox. Add scrolling to the IMAP folders area. - [x] Show created IMAP folders in the same list as Inbox and the other folders, and move the folder list and the add-folder button to the top row above Inbox. Add scrolling to the IMAP folders area.
+13 -8
View File
@@ -1,26 +1,31 @@
(() => {
const accountMailUi = window.epMailFeatures.mail;
const accountDavUi = window.epMailFeatures.dav;
async function openAccountManager(){ async function openAccountManager(){
const root=$('#modal-root'); const root=accountMailUi.select('#modal-root');
try{ try{
const data=await window.daybreakMail.listAccounts(); const data=await window.daybreakMail.listAccounts();
const accounts=data.accounts||[]; const accounts=data.accounts||[];
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.displayName||account.email)}</strong><small>${esc(account.email)} · ${esc(account.imapHost)} · ${esc(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${esc(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${esc(account.id)}">Edit</button><button class="discard" data-remove-account="${esc(account.id)}">Remove</button></div></div>`).join(''); const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${accountMailUi.escapeHtml(account.displayName||account.email)}</strong><small>${accountMailUi.escapeHtml(account.email)} · ${accountMailUi.escapeHtml(account.imapHost)} · ${accountMailUi.escapeHtml(account.smtpHost)}</small></div><div class="account-row-actions">${account.id===data.activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-switch-account="${accountMailUi.escapeHtml(account.id)}">Switch</button>`}<button class="outline-button" data-edit-account="${accountMailUi.escapeHtml(account.id)}">Edit</button><button class="discard" data-remove-account="${accountMailUi.escapeHtml(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`; root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||'<p class="account-note">No mailboxes connected yet.</p>'}<div class="account-row"><div class="account-row-info"><strong>Calendar and contacts</strong><small>Configure CalDAV calendar and CardDAV address book servers.</small></div><div class="account-row-actions"><button class="outline-button" data-open-dav="caldav">Calendar servers</button><button class="outline-button" data-open-dav="carddav">Contact servers</button></div></div></div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-mail-account">+ Add account</button></div></div></div>`;
const close=()=>root.innerHTML=''; const close=()=>root.innerHTML='';
root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close); root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);
root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
root.querySelector('#add-mail-account').onclick=()=>{close();openMailAccount()}; root.querySelector('#add-mail-account').onclick=()=>{close();accountMailUi.openMailAccount()};
root.onclick=async event=>{ root.onclick=async event=>{
const switchButton=event.target.closest('[data-switch-account]'); const switchButton=event.target.closest('[data-switch-account]');
if(switchButton){switchButton.disabled=true;try{connectedMailAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);activeFolder='Inbox';mailPageOffset=0;document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));$('#sidebar-title').textContent='Inbox';$('#crumb-current').textContent='Inbox';updateAccountCard(connectedMailAccount);close();await syncMailbox(true,{offset:0})}catch(error){toast(error.message||'Could not switch accounts');switchButton.disabled=false}return} if(switchButton){switchButton.disabled=true;try{accountMailUi.connectedAccount=await window.daybreakMail.selectAccount(switchButton.dataset.switchAccount);accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);document.querySelectorAll('.folder').forEach(button=>button.classList.toggle('active',button.dataset.folder==='Inbox'));accountMailUi.select('#sidebar-title').textContent='Inbox';accountMailUi.select('#crumb-current').textContent='Inbox';accountMailUi.updateAccountCard(accountMailUi.connectedAccount);close();await accountMailUi.syncMailbox(true,{offset:0})}catch(error){accountMailUi.toast(error.message||'Could not switch accounts');switchButton.disabled=false}return}
const davButton=event.target.closest('[data-open-dav]'); const davButton=event.target.closest('[data-open-dav]');
if(davButton){close();openDavManager(davButton.dataset.openDav);return} if(davButton){close();accountDavUi.openManager(davButton.dataset.openDav);return}
const editButton=event.target.closest('[data-edit-account]'); const editButton=event.target.closest('[data-edit-account]');
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)openMailAccount(account);return} if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
const removeButton=event.target.closest('[data-remove-account]'); const removeButton=event.target.closest('[data-remove-account]');
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;connectedMailAccount=active;if(active){updateAccountCard(active);close();activeFolder='Inbox';mailPageOffset=0;await syncMailbox(false,{offset:0})}else{updateAccountCard({email:'Connect a mailbox',imapHost:''});messages.splice(0,messages.length);renderList();$('#reader-pane').innerHTML=emptyReader();toast('Mail account removed');openAccountManager()}}catch(error){toast(error.message||'Could not remove the account');removeButton.disabled=false}return} if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?\n\nIts cached mail, drafts and pending sends will be removed. Downloaded attachment files and OpenPGP keys are kept; delete those separately if you want to remove them too.`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
}; };
}catch(error){toast(error.message||'Could not load mail accounts')} }catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
} }
document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true); document.addEventListener('click',event=>{const card=event.target.closest('#account-settings');if(!card)return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true); document.addEventListener('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
})();
+25
View File
@@ -3,6 +3,20 @@ apply plugin: 'org.jetbrains.kotlin.android'
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() } def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
def releaseStoreFile = System.getenv('EP_MAIL_ANDROID_STORE_FILE')
def releaseStorePassword = System.getenv('EP_MAIL_ANDROID_STORE_PASSWORD')
def releaseKeyAlias = System.getenv('EP_MAIL_ANDROID_KEY_ALIAS')
def releaseKeyPassword = System.getenv('EP_MAIL_ANDROID_KEY_PASSWORD')
def releaseSigningValues = [releaseStoreFile, releaseStorePassword, releaseKeyAlias, releaseKeyPassword]
def hasAnyReleaseSigningValue = releaseSigningValues.any { it != null && !it.isBlank() }
def hasCompleteReleaseSigning = releaseSigningValues.every { it != null && !it.isBlank() }
if (hasAnyReleaseSigningValue && !hasCompleteReleaseSigning) {
throw new GradleException('Android release signing requires EP_MAIL_ANDROID_STORE_FILE, EP_MAIL_ANDROID_STORE_PASSWORD, EP_MAIL_ANDROID_KEY_ALIAS, and EP_MAIL_ANDROID_KEY_PASSWORD.')
}
if (hasCompleteReleaseSigning && !new File(releaseStoreFile).isAbsolute()) {
throw new GradleException('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.')
}
android { android {
namespace = "studio.daybreak.mail" namespace = "studio.daybreak.mail"
@@ -10,6 +24,16 @@ android {
buildFeatures { buildFeatures {
buildConfig true buildConfig true
} }
if (hasCompleteReleaseSigning) {
signingConfigs {
release {
storeFile file(releaseStoreFile)
storePassword releaseStorePassword
keyAlias releaseKeyAlias
keyPassword releaseKeyPassword
}
}
}
packaging { packaging {
resources { resources {
pickFirsts += "META-INF/NOTICE.md" pickFirsts += "META-INF/NOTICE.md"
@@ -33,6 +57,7 @@ android {
release { release {
minifyEnabled false minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
if (hasCompleteReleaseSigning) signingConfig signingConfigs.release
} }
} }
compileOptions { compileOptions {
+2 -9
View File
@@ -8,6 +8,8 @@
<application <application
android:allowBackup="false" android:allowBackup="false"
android:dataExtractionRules="@xml/data_extraction_rules"
android:usesCleartextTraffic="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round" android:roundIcon="@mipmap/ic_launcher_round"
@@ -34,15 +36,6 @@
android:exported="false" android:exported="false"
android:foregroundServiceType="dataSync" /> android:foregroundServiceType="dataSync" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"></meta-data>
</provider>
</application> </application>
</manifest> </manifest>
@@ -25,7 +25,6 @@ internal object AndroidAccountVault {
fun initialize(context: Context) { fun initialize(context: Context) {
appContext = context.applicationContext appContext = context.applicationContext
secretKey()
} }
@Synchronized @Synchronized
@@ -57,6 +56,80 @@ internal object AndroidAccountVault {
fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray() fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray()
fun notificationDetailsEnabled(): Boolean =
read().optBoolean("showNotificationDetails", NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS)
@Synchronized
fun setNotificationDetailsEnabled(enabled: Boolean): Boolean {
val store = read().put("showNotificationDetails", enabled)
write(store)
return enabled
}
fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false)
@Synchronized
fun setAppLockEnabled(enabled: Boolean): Boolean {
val store = read().put("appLockEnabled", enabled)
write(store)
return enabled
}
fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) }
?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject())
@Synchronized
fun savePgpStore(candidate: JSONObject) {
validatePgpStore(candidate)
val store = read().put("pgpStore", JSONObject(candidate.toString()))
write(store)
}
private fun validatePgpStore(candidate: JSONObject) {
require(candidate.toString().length <= 3_000_000) { "The OpenPGP key store is too large." }
require(!hasPassphraseField(candidate)) { "Passphrases must never be stored." }
val keys = candidate.optJSONArray("keys") ?: JSONArray()
val contacts = candidate.optJSONArray("contacts") ?: JSONArray()
require(keys.length() <= 20 && contacts.length() <= 500) { "The OpenPGP key store has too many entries." }
val fingerprint = Regex("^[0-9A-Fa-f]{40,64}$")
for (index in 0 until keys.length()) {
val entry = keys.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP key entry is invalid.")
val privateKey = entry.optString("privateKey")
val publicKey = entry.optString("publicKey")
require(fingerprint.matches(entry.optString("fingerprint")) &&
privateKey.length in 1..200_000 && privateKey.contains("BEGIN PGP PRIVATE KEY BLOCK") &&
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK")) {
"An OpenPGP key entry is invalid."
}
}
for (index in 0 until contacts.length()) {
val entry = contacts.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP contact entry is invalid.")
val publicKey = entry.optString("publicKey")
require(fingerprint.matches(entry.optString("fingerprint")) &&
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK") &&
!publicKey.contains("BEGIN PGP PRIVATE KEY BLOCK")) {
"An OpenPGP contact entry is invalid."
}
require(entry.optString("trust") in setOf("unknown", "trusted", "verified")) {
"An OpenPGP contact trust value is invalid."
}
}
}
private fun hasPassphraseField(value: Any?): Boolean = when (value) {
is JSONObject -> {
val keys = value.keys()
var found = false
while (keys.hasNext() && !found) {
val key = keys.next()
found = key.contains("passphrase", ignoreCase = true) || hasPassphraseField(value.opt(key))
}
found
}
is JSONArray -> (0 until value.length()).any { hasPassphraseField(value.opt(it)) }
else -> false
}
fun account(id: String? = null): JSONObject? { fun account(id: String? = null): JSONObject? {
val store = read() val store = read()
val accounts = store.optJSONArray("accounts") ?: return null val accounts = store.optJSONArray("accounts") ?: return null
@@ -432,6 +505,10 @@ internal object AndroidAccountVault {
.put("displayName", account.optString("displayName")) .put("displayName", account.optString("displayName"))
.put("imapHost", account.optString("imapHost")) .put("imapHost", account.optString("imapHost"))
.put("smtpHost", account.optString("smtpHost")) .put("smtpHost", account.optString("smtpHost"))
.put("imapPort", account.optInt("imapPort", 143))
.put("smtpPort", account.optInt("smtpPort", 587))
.put("imapSecure", account.optBoolean("imapSecure", false))
.put("smtpSecure", account.optBoolean("smtpSecure", false))
.put("signature", account.optString("signature")) .put("signature", account.optString("signature"))
.put("notificationsEnabled", account.optBoolean("notificationsEnabled", true)) .put("notificationsEnabled", account.optBoolean("notificationsEnabled", true))
.put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2)) .put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2))
@@ -523,6 +600,11 @@ internal object AndroidAccountVault {
private fun secretKey(): SecretKey { private fun secretKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it } (keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val hasEncryptedData = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.contains(ENCRYPTED_VALUE)
check(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData)) {
AndroidVaultKeyPolicy.MISSING_KEY_MESSAGE
}
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init( generator.init(
KeyGenParameterSpec.Builder( KeyGenParameterSpec.Builder(
@@ -20,6 +20,8 @@ internal object AndroidDavService {
private val httpClient = OkHttpClient.Builder() private val httpClient = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS) .connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS)
.followRedirects(false)
.followSslRedirects(false)
.build() .build()
fun list(): JSONObject { fun list(): JSONObject {
@@ -36,12 +38,7 @@ internal object AndroidDavService {
val serverUrl = input.optString("serverUrl").trim() val serverUrl = input.optString("serverUrl").trim()
val username = input.optString("username").trim() val username = input.optString("username").trim()
val password = input.optString("password") val password = input.optString("password")
val url = try { URL(serverUrl) } catch (_: Exception) { val url = DavUrlPolicy.parseServerUrl(serverUrl)
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
}
require(url.protocol == "https" || (url.protocol == "http" && url.host in setOf("localhost", "127.0.0.1", "::1"))) {
"DAV server URLs must use HTTPS."
}
require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." } require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." }
val collections = discoverCollections(url.toString(), username, password, type) val collections = discoverCollections(url.toString(), username, password, type)
require(collections.length() > 0) { require(collections.length() > 0) {
@@ -165,13 +162,7 @@ internal object AndroidDavService {
body: String?, body: String?,
headers: Map<String, String> = emptyMap() headers: Map<String, String> = emptyMap()
): HttpResult { ): HttpResult {
val target = URL(address) DavUrlPolicy.requireSameOrigin(account.optString("serverUrl"), address)
val base = URL(account.optString("serverUrl"))
val targetPort = if (target.port >= 0) target.port else target.defaultPort
val basePort = if (base.port >= 0) base.port else base.defaultPort
require(target.protocol == base.protocol && target.host.equals(base.host, true) && targetPort == basePort) {
"The DAV server returned a collection URL on an unexpected host."
}
val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull()) val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull())
val builder = Request.Builder() val builder = Request.Builder()
.url(address) .url(address)
@@ -394,7 +385,10 @@ internal object AndroidDavService {
.put("username", account.optString("username")) .put("username", account.optString("username"))
.put("collections", account.optJSONArray("collections") ?: JSONArray()) .put("collections", account.optJSONArray("collections") ?: JSONArray())
private fun type(value: String) = if (value == "carddav") "carddav" else "caldav" private fun type(value: String) = when (value) {
"caldav", "carddav" -> value
else -> throw IllegalArgumentException("Choose a supported CalDAV or CardDAV account.")
}
private fun findCollection(collections: JSONArray, url: String): JSONObject? { private fun findCollection(collections: JSONArray, url: String): JSONObject? {
for (index in 0 until collections.length()) { for (index in 0 until collections.length()) {
@@ -11,6 +11,8 @@ import com.sun.mail.imap.IMAPFolder
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.text.DateFormat import java.text.DateFormat
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Calendar import java.util.Calendar
@@ -263,11 +265,24 @@ internal object AndroidMailService {
} }
fun send(account: JSONObject, input: JSONObject): JSONObject { fun send(account: JSONObject, input: JSONObject): JSONObject {
val rawBase64 = input.optString("rawBase64")
val session = Session.getInstance(smtpProperties(account), credentials(account))
val message: MimeMessage
if (rawBase64.isNotBlank()) {
require(rawBase64.length <= 36_000_000 && rawBase64.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
"The encrypted message is too large or invalid."
}
val bytes = Base64.decode(rawBase64, Base64.DEFAULT)
require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." }
message = MimeMessage(session, ByteArrayInputStream(bytes))
validateOpenPgpMime(message)
require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) {
"The encrypted message needs a sender and at least one recipient."
}
} else {
val recipient = input.optString("to").trim() val recipient = input.optString("to").trim()
require(recipient.isNotEmpty()) { "Add at least one recipient." } require(recipient.isNotEmpty()) { "Add at least one recipient." }
val properties = smtpProperties(account) message = MimeMessage(session)
val session = Session.getInstance(properties, credentials(account))
val message = MimeMessage(session)
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8")) message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true)) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
val cc = input.optString("cc").trim() val cc = input.optString("cc").trim()
@@ -309,6 +324,7 @@ internal object AndroidMailService {
message.sentDate = Date() message.sentDate = Date()
message.saveChanges() message.saveChanges()
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
}
val transport = session.getTransport("smtp") val transport = session.getTransport("smtp")
try { try {
@@ -337,6 +353,61 @@ internal object AndroidMailService {
return JSONObject().put("ok", true).put("savedToSent", savedToSent) return JSONObject().put("ok", true).put("savedToSent", savedToSent)
} }
fun pgpMessageSource(account: JSONObject, folderName: String, uid: Long): JSONObject = withStore(account) { _, store ->
require(uid > 0) { "That message could not be identified." }
val folder = resolveFolder(store, folderName) ?: throw IllegalStateException("That mail folder could not be found.")
folder.open(Folder.READ_ONLY)
try {
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
?: throw IllegalStateException("The message is no longer available.")
val output = ByteArrayOutputStream()
message.writeTo(output)
val bytes = output.toByteArray()
require(bytes.size <= 25 * 1024 * 1024) { "This encrypted message is too large to open on Android testing builds." }
JSONObject().put("rawBase64", Base64.encodeToString(bytes, Base64.NO_WRAP))
} finally {
folder.close(false)
}
}
private fun validateOpenPgpMime(message: MimeMessage) {
val contentType = message.contentType.lowercase(Locale.ROOT)
val multipart = message.content as? Multipart
?: throw IllegalArgumentException("The OpenPGP MIME message is malformed.")
require(multipart.count == 2) { "The OpenPGP MIME message has an unexpected structure." }
if (contentType.startsWith("multipart/encrypted")) {
val versionPart = multipart.getBodyPart(0)
val encryptedPart = multipart.getBodyPart(1)
val version = runCatching { versionPart.content.toString().trim() }.getOrDefault("")
val armor = runCatching { String(encryptedPart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" &&
encryptedPart.isMimeType("application/octet-stream") &&
armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) {
"The encrypted OpenPGP payload is missing or malformed."
}
} else if (contentType.startsWith("multipart/signed")) {
val signaturePart = multipart.getBodyPart(1)
val armor = runCatching { String(signaturePart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
require(signaturePart.isMimeType("application/pgp-signature") &&
armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) {
"The OpenPGP signature is missing or malformed."
}
} else {
throw IllegalArgumentException("Only an OpenPGP MIME message can use the protected send path.")
}
}
fun savePgpAttachment(context: Context, input: JSONObject): JSONObject {
val filename = input.optString("filename").replace(Regex("[\\\\/\\r\\n\\u0000]"), "").take(255).ifBlank { "attachment" }
val contentType = input.optString("contentType", "application/octet-stream").lowercase(Locale.ROOT)
require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) { "The attachment content type is invalid." }
val encoded = input.optString("contentBase64")
require(encoded.length <= 36_000_000 && encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
"The attachment is too large or invalid."
}
return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT))
}
fun flushOutbox(account: JSONObject) { fun flushOutbox(account: JSONObject) {
val accountId = account.optString("id") val accountId = account.optString("id")
val queued = AndroidAccountVault.pendingMailOperations(accountId) val queued = AndroidAccountVault.pendingMailOperations(accountId)
@@ -351,7 +422,7 @@ internal object AndroidMailService {
} }
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id")) AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
} catch (error: Exception) { } catch (error: Exception) {
android.util.Log.w("EpMailOutbox", "Mail operation remains queued for a later retry.", error) android.util.Log.w("EpMailOutbox", "Mail operation remains queued (${error.javaClass.simpleName})")
break break
} }
} }
@@ -479,7 +550,7 @@ internal object AndroidMailService {
inbox.close(true) inbox.close(true)
} }
} catch (error: Exception) { } catch (error: Exception) {
android.util.Log.e("EpMailRules", "Could not apply a mail rule to message $uid", error) android.util.Log.e("EpMailRules", "Could not apply a mail rule (${error.javaClass.simpleName})")
} }
} }
} }
@@ -491,14 +562,15 @@ internal object AndroidMailService {
shouldStop: () -> Boolean, shouldStop: () -> Boolean,
onConnection: (Store?, Folder?) -> Unit onConnection: (Store?, Folder?) -> Unit
) { ) {
val protocol = imapProtocol(account)
val props = imapProperties(account).apply { val props = imapProperties(account).apply {
setProperty("mail.imap.timeout", "0") setProperty("mail.$protocol.timeout", "0")
setProperty("mail.imap.writetimeout", "60000") setProperty("mail.$protocol.writetimeout", "60000")
} }
val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2) val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
.coerceIn(2, 60) * 60_000L .coerceIn(2, 60) * 60_000L
val session = Session.getInstance(props, credentials(account)) val session = Session.getInstance(props, credentials(account))
val store = session.getStore("imap") val store = session.getStore(protocol)
try { try {
store.connect( store.connect(
account.optString("imapHost"), account.optString("imapHost"),
@@ -596,7 +668,10 @@ internal object AndroidMailService {
val links = linkedSetOf<String>() val links = linkedSetOf<String>()
collectParts(message, body, htmlBodies, attachments, links) collectParts(message, body, htmlBodies, attachments, links)
val bodyText = body.joinToString("\n\n").trim().take(8000) val bodyText = body.joinToString("\n\n").trim().take(8000)
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----")
val signed = isSignedMessage(message) || bodyText.contains("-----BEGIN PGP SIGNED MESSAGE-----")
val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText
val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date() val date = message.receivedDate ?: message.sentDate ?: Date()
val tags = JSONArray().put(requestedFolder) val tags = JSONArray().put(requestedFolder)
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid") val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
@@ -619,6 +694,8 @@ internal object AndroidMailService {
.put("email", senderEmail) .put("email", senderEmail)
.put("subject", subject) .put("subject", subject)
.put("snippet", snippet) .put("snippet", snippet)
.put("encrypted", encrypted)
.put("signed", signed)
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date)) .put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date)) .put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
.put("timestamp", date.time) .put("timestamp", date.time)
@@ -631,7 +708,7 @@ internal object AndroidMailService {
.put("sourceFolder", labelFolder) .put("sourceFolder", labelFolder)
.put("html", htmlBodies.firstOrNull()?.take(100000) ?: "") .put("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
.put("body", JSONArray().apply { .put("body", JSONArray().apply {
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40) val paragraphs = visibleBody.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put) if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
}) })
.put("links", JSONArray().apply { links.take(30).forEach(::put) }) .put("links", JSONArray().apply { links.take(30).forEach(::put) })
@@ -640,6 +717,24 @@ internal object AndroidMailService {
.put("size", files.firstOrNull()?.optString("size") ?: "") .put("size", files.firstOrNull()?.optString("size") ?: "")
} }
private fun isEncryptedMessage(part: javax.mail.Part): Boolean {
if (part.isMimeType("multipart/encrypted")) return true
val content = try { part.content } catch (_: Exception) { return false }
if (content is Multipart) {
for (index in 0 until content.count) if (isEncryptedMessage(content.getBodyPart(index))) return true
} else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true
return false
}
private fun isSignedMessage(part: javax.mail.Part): Boolean {
if (part.isMimeType("multipart/signed")) return true
val content = try { part.content } catch (_: Exception) { return false }
if (content is Multipart) {
for (index in 0 until content.count) if (isSignedMessage(content.getBodyPart(index))) return true
} else if (content is String && content.contains("-----BEGIN PGP SIGNED MESSAGE-----")) return true
return false
}
private fun attachmentList(attachments: JSONArray): List<JSONObject> = private fun attachmentList(attachments: JSONArray): List<JSONObject> =
(0 until attachments.length()).map { attachments.getJSONObject(it) } (0 until attachments.length()).map { attachments.getJSONObject(it) }
@@ -650,7 +745,9 @@ internal object AndroidMailService {
attachments: JSONArray, attachments: JSONArray,
links: MutableSet<String> links: MutableSet<String>
) { ) {
if (part.isMimeType("application/pgp-signature") || part.isMimeType("application/pgp-encrypted")) return
val filename = decode(part.fileName) val filename = decode(part.fileName)
if (part.isMimeType("application/octet-stream") && filename.equals("encrypted.asc", true)) return
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) { if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
val name = filename.ifBlank { "attachment" } val name = filename.ifBlank { "attachment" }
val size = part.size.coerceAtLeast(0) val size = part.size.coerceAtLeast(0)
@@ -690,12 +787,13 @@ internal object AndroidMailService {
} }
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject { private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
val safeFilename = AttachmentNamePolicy.sanitize(filename)
val mimeType = contentType.substringBefore(';').ifBlank { val mimeType = contentType.substringBefore(';').ifBlank {
MimeTypeMap.getSingleton().getMimeTypeFromExtension(filename.substringAfterLast('.', "")) ?: "application/octet-stream" MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream"
} }
if (Build.VERSION.SDK_INT >= 29) { if (Build.VERSION.SDK_INT >= 29) {
val values = ContentValues().apply { val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, filename) put(MediaStore.Downloads.DISPLAY_NAME, safeFilename)
put(MediaStore.Downloads.MIME_TYPE, mimeType) put(MediaStore.Downloads.MIME_TYPE, mimeType)
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
} }
@@ -703,13 +801,13 @@ internal object AndroidMailService {
?: throw IllegalStateException("Could not create the attachment in Downloads.") ?: throw IllegalStateException("Could not create the attachment in Downloads.")
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) } context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
?: throw IllegalStateException("Could not write the attachment.") ?: throw IllegalStateException("Could not write the attachment.")
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", filename) return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", safeFilename)
} }
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
?: throw IllegalStateException("Downloads storage is not available.") ?: throw IllegalStateException("Downloads storage is not available.")
val file = File(directory, filename.replace(Regex("[\\\\/:*?\"<>|]"), "_")) val file = File(directory, safeFilename)
file.writeBytes(bytes) file.writeBytes(bytes)
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", filename) return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename)
} }
private const val CUSTOM_FOLDER_PREFIX = "Folder:" private const val CUSTOM_FOLDER_PREFIX = "Folder:"
@@ -783,7 +881,7 @@ internal object AndroidMailService {
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T { private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
val session = Session.getInstance(imapProperties(account), credentials(account)) val session = Session.getInstance(imapProperties(account), credentials(account))
val store = session.getStore("imap") val store = session.getStore(imapProtocol(account))
try { try {
store.connect( store.connect(
account.optString("imapHost"), account.optString("imapHost"),
@@ -805,29 +903,20 @@ internal object AndroidMailService {
} }
private fun imapProperties(account: JSONObject) = Properties().apply { private fun imapProperties(account: JSONObject) = Properties().apply {
setProperty("mail.store.protocol", "imap") putAll(AndroidMailTransport.imapProperties(MailServerConnection(
setProperty("mail.imap.host", account.optString("imapHost")) account.optString("imapHost"),
setProperty("mail.imap.port", account.optInt("imapPort", 143).toString()) account.optInt("imapPort", 143),
setProperty("mail.imap.auth", "true") account.optBoolean("imapSecure", false)
setProperty("mail.imap.starttls.enable", "true") )))
setProperty("mail.imap.starttls.required", "true")
setProperty("mail.imap.ssl.checkserveridentity", "true")
setProperty("mail.imap.connectiontimeout", "20000")
setProperty("mail.imap.timeout", "30000")
setProperty("mail.imap.writetimeout", "30000")
} }
private fun smtpProperties(account: JSONObject) = Properties().apply { private fun imapProtocol(account: JSONObject) = if (account.optBoolean("imapSecure", false)) "imaps" else "imap"
setProperty("mail.smtp.host", account.optString("smtpHost"))
setProperty("mail.smtp.port", account.optInt("smtpPort", 587).toString()) private fun smtpProperties(account: JSONObject) = AndroidMailTransport.smtpProperties(MailServerConnection(
setProperty("mail.smtp.auth", "true") account.optString("smtpHost"),
setProperty("mail.smtp.starttls.enable", "true") account.optInt("smtpPort", 587),
setProperty("mail.smtp.starttls.required", "true") account.optBoolean("smtpSecure", false)
setProperty("mail.smtp.ssl.checkserveridentity", "true") ))
setProperty("mail.smtp.connectiontimeout", "20000")
setProperty("mail.smtp.timeout", "30000")
setProperty("mail.smtp.writetimeout", "30000")
}
private fun displayName(account: JSONObject) = private fun displayName(account: JSONObject) =
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80) account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
@@ -0,0 +1,45 @@
package studio.daybreak.mail
import java.util.Properties
internal data class MailServerConnection(
val host: String,
val port: Int,
val secure: Boolean
)
internal object AndroidMailTransport {
fun imapProperties(server: MailServerConnection): Properties = Properties().apply {
val protocol = if (server.secure) "imaps" else "imap"
setProperty("mail.store.protocol", protocol)
setProperty("mail.$protocol.host", server.host)
setProperty("mail.$protocol.port", server.port.toString())
setProperty("mail.$protocol.auth", "true")
setProperty("mail.$protocol.ssl.checkserveridentity", "true")
if (server.secure) {
setProperty("mail.$protocol.ssl.enable", "true")
} else {
setProperty("mail.$protocol.starttls.enable", "true")
setProperty("mail.$protocol.starttls.required", "true")
}
setProperty("mail.$protocol.connectiontimeout", "20000")
setProperty("mail.$protocol.timeout", "30000")
setProperty("mail.$protocol.writetimeout", "30000")
}
fun smtpProperties(server: MailServerConnection): Properties = Properties().apply {
setProperty("mail.smtp.host", server.host)
setProperty("mail.smtp.port", server.port.toString())
setProperty("mail.smtp.auth", "true")
setProperty("mail.smtp.ssl.checkserveridentity", "true")
if (server.secure) {
setProperty("mail.smtp.ssl.enable", "true")
} else {
setProperty("mail.smtp.starttls.enable", "true")
setProperty("mail.smtp.starttls.required", "true")
}
setProperty("mail.smtp.connectiontimeout", "20000")
setProperty("mail.smtp.timeout", "30000")
setProperty("mail.smtp.writetimeout", "30000")
}
}
@@ -0,0 +1,39 @@
package studio.daybreak.mail
import java.util.concurrent.atomic.AtomicBoolean
/** Makes native confirmations fail closed and guarantees each plugin call gets one decision. */
internal class AndroidPgpConfirmationGate(
private val showPrompt: (Prompt) -> Unit,
private val dispatch: ((() -> Unit) -> Unit)
) {
data class Prompt(
val title: String,
val message: String,
val confirmLabel: String,
val cancelLabel: String,
val confirm: () -> Unit,
val cancel: () -> Unit
)
fun request(
title: String,
message: String,
confirmLabel: String,
cancelLabel: String = "Cancel",
onConfirmed: () -> Unit,
onCancelled: () -> Unit
) {
val decided = AtomicBoolean(false)
showPrompt(
Prompt(
title = title,
message = message,
confirmLabel = confirmLabel,
cancelLabel = cancelLabel,
confirm = { if (decided.compareAndSet(false, true)) dispatch(onConfirmed) },
cancel = { if (decided.compareAndSet(false, true)) dispatch(onCancelled) }
)
)
}
}
@@ -0,0 +1,86 @@
package studio.daybreak.mail
import java.util.Locale
internal object AndroidPgpPolicy {
data class ContactKey(
val fingerprint: String,
val emails: List<String>,
val trust: String
)
data class RecipientKey(
val email: String,
val fingerprint: String
)
private val trustOrder = mapOf("unknown" to 0, "trusted" to 1, "verified" to 2)
fun storeChangeWarning(previous: List<ContactKey>, candidate: List<ContactKey>): String? {
val oldByFingerprint = previous.associateBy { it.fingerprint.uppercase(Locale.ROOT) }
val warnings = ArrayList<String>()
for (current in candidate) {
val fingerprint = current.fingerprint.uppercase(Locale.ROOT)
val old = oldByFingerprint[fingerprint]
if (old != null && (trustOrder[current.trust] ?: 0) > (trustOrder[old.trust] ?: 0)) {
warnings.add(
"Trust change for ${safeLabel(current.emails)}\n" +
"Fingerprint: ${formatFingerprint(fingerprint)}\n" +
"New trust: ${current.trust}"
)
}
if (old == null) {
val newEmails = current.emails.map { it.lowercase(Locale.ROOT) }.toSet()
for (previousKey in previous) {
val oldFingerprint = previousKey.fingerprint.uppercase(Locale.ROOT)
val overlaps = previousKey.emails.any { it.lowercase(Locale.ROOT) in newEmails }
if (overlaps && oldFingerprint != fingerprint) {
warnings.add(
"A different key is already stored for ${safeLabel(current.emails)}.\n" +
"New fingerprint: ${formatFingerprint(fingerprint)}\n" +
"Existing fingerprint: ${formatFingerprint(oldFingerprint)}"
)
}
}
}
}
return warnings.take(MAX_WARNINGS).takeIf { it.isNotEmpty() }?.joinToString("\n\n")?.let {
"$it\n\nOnly confirm trust or a replacement after comparing fingerprints with the key owner through another channel."
}
}
fun plaintextSendWarning(
recipients: List<String>,
availableKeys: List<RecipientKey>,
encryptionWasRequested: Boolean
): String? {
val uniqueRecipients = recipients.map { it.trim().lowercase(Locale.ROOT) }.filter(String::isNotBlank).distinct()
if (uniqueRecipients.isEmpty()) return null
val matchedKeys = availableKeys.filter { key -> key.email.trim().lowercase(Locale.ROOT) in uniqueRecipients }
if (!encryptionWasRequested && matchedKeys.isEmpty()) return null
val recipientLines = uniqueRecipients.take(MAX_RECIPIENTS).map { email ->
val fingerprints = matchedKeys.filter { it.email.trim().equals(email, ignoreCase = true) }
.map { formatFingerprint(it.fingerprint.uppercase()) }.distinct()
if (fingerprints.isEmpty()) "$email — no key stored" else "$email\n${fingerprints.joinToString("\n")}"
}.joinToString("\n\n")
val prefix = if (encryptionWasRequested) {
"OpenPGP was requested, but this message will be sent in plaintext."
} else {
"A stored OpenPGP key is available for at least one recipient."
}
return "$prefix\n\nRecipients and stored key fingerprints:\n$recipientLines\n\n" +
"The message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?"
}
private fun safeLabel(values: List<String>): String =
values.joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" }
private fun formatFingerprint(value: String): String = value.chunked(4).joinToString(" ").take(200)
private const val MAX_WARNINGS = 6
private const val MAX_RECIPIENTS = 10
}
@@ -0,0 +1,8 @@
package studio.daybreak.mail
internal object AndroidVaultKeyPolicy {
fun shouldCreateKey(hasEncryptedData: Boolean): Boolean = !hasEncryptedData
const val MISSING_KEY_MESSAGE =
"The Android Keystore key for saved app data is missing. Existing encrypted data was not reset or replaced."
}
@@ -0,0 +1,11 @@
package studio.daybreak.mail
internal object AttachmentNamePolicy {
fun sanitize(value: String): String {
val name = value
.replace(Regex("[\\\\/:*?\"<>|\\u0000-\\u001f]"), "_")
.trim()
.take(180)
return if (name.isBlank() || name == "." || name == "..") "attachment" else name
}
}
@@ -0,0 +1,31 @@
package studio.daybreak.mail
import java.net.URL
/** Enforces the transport and origin policy for user-configured DAV endpoints. */
internal object DavUrlPolicy {
fun parseServerUrl(raw: String): URL {
val url = try {
URL(raw)
} catch (_: Exception) {
throw IllegalArgumentException("Enter a valid CalDAV or CardDAV server URL.")
}
require(url.protocol.equals("https", ignoreCase = true) && url.host.isNotBlank()) {
"DAV server URLs must use HTTPS."
}
require(url.userInfo == null && url.ref == null) {
"DAV server URLs cannot contain credentials or fragments."
}
return url
}
fun requireSameOrigin(baseAddress: String, targetAddress: String) {
val base = parseServerUrl(baseAddress)
val target = parseServerUrl(targetAddress)
val basePort = if (base.port >= 0) base.port else base.defaultPort
val targetPort = if (target.port >= 0) target.port else target.defaultPort
require(target.host.equals(base.host, ignoreCase = true) && targetPort == basePort) {
"The DAV server returned a collection URL on an unexpected host."
}
}
}
@@ -16,6 +16,7 @@ import java.util.Locale
import java.util.UUID import java.util.UUID
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import javax.mail.internet.InternetAddress
@CapacitorPlugin(name = "EpMail") @CapacitorPlugin(name = "EpMail")
class EpMailPlugin : Plugin() { class EpMailPlugin : Plugin() {
@@ -37,11 +38,20 @@ class EpMailPlugin : Plugin() {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
context.registerReceiver(receiver, filter) context.registerReceiver(receiver, filter)
} }
MailIdleService.start(context) ensureVaultAvailableAndStartSync()
} }
override fun handleOnResume() { override fun handleOnResume() {
ensureVaultAvailableAndStartSync()
}
private fun ensureVaultAvailableAndStartSync() {
try {
AndroidAccountVault.read()
MailIdleService.start(context) MailIdleService.start(context)
} catch (error: Exception) {
android.util.Log.e("EpMailStorage", "Secure local storage is unavailable (${error.javaClass.simpleName})")
}
} }
override fun handleOnDestroy() { override fun handleOnDestroy() {
@@ -56,6 +66,160 @@ class EpMailPlugin : Plugin() {
call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME)) call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME))
} }
@PluginMethod
fun getNotificationPrivacy(call: PluginCall) {
try {
call.resolve(JSObject().put("showDetails", AndroidAccountVault.notificationDetailsEnabled()))
} catch (error: Exception) {
call.reject(error.message ?: "Could not read notification privacy settings.")
}
}
@PluginMethod
fun setNotificationDetails(call: PluginCall) {
try {
val enabled = call.getBoolean("enabled")
?: throw IllegalArgumentException("Choose whether notifications may show details.")
AndroidAccountVault.setNotificationDetailsEnabled(enabled)
call.resolve(JSObject().put("showDetails", enabled))
} catch (error: Exception) {
call.reject(error.message ?: "Could not save notification privacy settings.")
}
}
@PluginMethod
fun getAppLockSettings(call: PluginCall) {
try {
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
call.resolve(JSObject()
.put("enabled", AndroidAccountVault.appLockEnabled())
.put("deviceSecure", keyguard.isDeviceSecure))
} catch (error: Exception) {
call.reject(error.message ?: "Could not read app-lock settings.")
}
}
@PluginMethod
fun setAppLockEnabled(call: PluginCall) {
try {
val enabled = call.getBoolean("enabled")
?: throw IllegalArgumentException("Choose whether to lock ep-mail when you leave it.")
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
require(!enabled || keyguard.isDeviceSecure) {
"Set a screen lock in Android Settings before enabling the app lock."
}
AndroidAccountVault.setAppLockEnabled(enabled)
(activity as? MainActivity)?.onAppLockSettingChanged(enabled)
call.resolve(JSObject().put("enabled", enabled).put("deviceSecure", keyguard.isDeviceSecure))
} catch (error: Exception) {
call.reject(error.message ?: "Could not save app-lock settings.")
}
}
@PluginMethod
fun pgpLoadStore(call: PluginCall) {
try {
call.resolve(AndroidAccountVault.pgpStore().toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not load the Android OpenPGP key store.")
}
}
@PluginMethod
fun pgpSaveStore(call: PluginCall) {
try {
val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.")
val next = JSONObject(candidate.toString())
val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next)
if (warning == null) {
AndroidAccountVault.savePgpStore(next)
call.resolve(JSObject().put("ok", true))
} else {
showPgpConfirmation(
title = "Confirm OpenPGP key changes",
message = warning,
confirmLabel = "Confirm changes",
onConfirmed = {
try {
AndroidAccountVault.savePgpStore(next)
call.resolve(JSObject().put("ok", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
}
},
onCancelled = { call.reject("OpenPGP key change cancelled.") }
)
}
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
}
}
private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? {
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
return AndroidPgpPolicy.storeChangeWarning(pgpContacts(oldContacts), pgpContacts(newContacts))
}
private fun pgpContacts(values: JSONArray): List<AndroidPgpPolicy.ContactKey> =
(0 until values.length()).mapNotNull { values.optJSONObject(it) }.map { contact ->
AndroidPgpPolicy.ContactKey(
fingerprint = contact.optString("fingerprint"),
emails = jsonStrings(contact.optJSONArray("emails")),
trust = contact.optString("trust")
)
}
private fun jsonStrings(values: JSONArray?): List<String> =
values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
private fun showPgpConfirmation(
title: String,
message: String,
confirmLabel: String,
onConfirmed: () -> Unit,
onCancelled: () -> Unit
) {
val gate = AndroidPgpConfirmationGate(
showPrompt = { prompt ->
val host = activity
host.runOnUiThread {
AlertDialog.Builder(host)
.setTitle(prompt.title)
.setMessage(prompt.message)
.setNegativeButton(prompt.cancelLabel) { _, _ -> prompt.cancel() }
.setPositiveButton(prompt.confirmLabel) { _, _ -> prompt.confirm() }
.setOnCancelListener { prompt.cancel() }
.show()
}
},
dispatch = { action -> bridge.execute(action) }
)
gate.request(title, message, confirmLabel, onConfirmed = onConfirmed, onCancelled = onCancelled)
}
@PluginMethod
fun pgpGetMessageSource(call: PluginCall) {
try {
val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before opening messages.")
val folder = call.getString("folder") ?: "Inbox"
val uid = call.getLong("uid") ?: 0L
call.resolve(AndroidMailService.pgpMessageSource(account, folder, uid).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not load the encrypted message.")
}
}
@PluginMethod
fun savePgpAttachment(call: PluginCall) {
try {
call.resolve(AndroidMailService.savePgpAttachment(context, JSONObject(call.data.toString())).toJSObject())
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the decrypted attachment.")
}
}
@PluginMethod @PluginMethod
fun getAccount(call: PluginCall) { fun getAccount(call: PluginCall) {
val account = AndroidAccountVault.account() val account = AndroidAccountVault.account()
@@ -292,6 +456,26 @@ class EpMailPlugin : Plugin() {
val input = JSONObject(call.data.toString()).apply { val input = JSONObject(call.data.toString()).apply {
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>") if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
} }
val warning = try { plaintextSendWarning(input) } catch (error: Exception) {
call.reject(error.message ?: "Could not check the OpenPGP send policy.")
return
}
if (warning == null) {
sendPrepared(call, input)
return
}
showPgpConfirmation(
title = "Send without OpenPGP encryption?",
message = warning,
confirmLabel = "Send plaintext",
onConfirmed = { sendPrepared(call, input) },
onCancelled = {
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
}
)
}
private fun sendPrepared(call: PluginCall, input: JSONObject) {
try { try {
val account = AndroidAccountVault.account() val account = AndroidAccountVault.account()
?: throw IllegalStateException("Add a mail account before sending.") ?: throw IllegalStateException("Add a mail account before sending.")
@@ -308,6 +492,33 @@ class EpMailPlugin : Plugin() {
} }
} }
private fun plaintextSendWarning(input: JSONObject): String? {
if (input.optString("rawBase64").isNotBlank()) return null
val recipients = (listOf(input.optString("to"), input.optString("cc"))
.filter(String::isNotBlank)
.flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } })
.distinct()
val data = AndroidAccountVault.pgpStore()
val contacts = data.optJSONArray("contacts") ?: JSONArray()
val keys = data.optJSONArray("keys") ?: JSONArray()
val available = ArrayList<AndroidPgpPolicy.RecipientKey>()
for (address in recipients) {
for (index in 0 until contacts.length()) {
val contact = contacts.optJSONObject(index) ?: continue
if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) {
available.add(AndroidPgpPolicy.RecipientKey(address, contact.optString("fingerprint")))
}
}
for (index in 0 until keys.length()) {
val key = keys.optJSONObject(index) ?: continue
if (key.optString("email").equals(address, true)) {
available.add(AndroidPgpPolicy.RecipientKey(address, key.optString("fingerprint")))
}
}
}
return AndroidPgpPolicy.plaintextSendWarning(recipients, available, input.optBoolean("pgpRequested"))
}
@PluginMethod @PluginMethod
fun listDrafts(call: PluginCall) { fun listDrafts(call: PluginCall) {
try { try {
@@ -458,9 +669,14 @@ class EpMailPlugin : Plugin() {
val displayName = input.optString("displayName").trim().take(80) val displayName = input.optString("displayName").trim().take(80)
val imapHost = input.optString("imapHost").trim() val imapHost = input.optString("imapHost").trim()
val smtpHost = input.optString("smtpHost").trim() val smtpHost = input.optString("smtpHost").trim()
val imapPort = input.optInt("imapPort", 143)
val smtpPort = input.optInt("smtpPort", 587)
require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) { require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) {
"Enter a valid email, account display name, password, and both mail server names." "Enter a valid email, account display name, password, and both mail server names."
} }
require(imapPort in 1..65535 && smtpPort in 1..65535) {
"Enter valid IMAP and SMTP ports (1–65535)."
}
return JSONObject() return JSONObject()
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() }) .put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
.put("email", email) .put("email", email)
@@ -474,8 +690,10 @@ class EpMailPlugin : Plugin() {
require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." } require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." }
}) })
.put("rules", normalizeRules(input.optJSONArray("rules"))) .put("rules", normalizeRules(input.optJSONArray("rules")))
.put("imapPort", input.optInt("imapPort", 143)) .put("imapPort", imapPort)
.put("smtpPort", input.optInt("smtpPort", 587)) .put("smtpPort", smtpPort)
.put("imapSecure", input.optBoolean("imapSecure", false))
.put("smtpSecure", input.optBoolean("smtpSecure", false))
} }
private fun normalizeRules(input: JSONArray?): JSONArray { private fun normalizeRules(input: JSONArray?): JSONArray {
@@ -25,7 +25,7 @@ class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worke
} }
Result.success() Result.success()
} catch (error: Exception) { } catch (error: Exception) {
android.util.Log.w(TAG, "Periodic mail fallback sync failed", error) android.util.Log.w(TAG, "Periodic mail fallback sync failed (${error.javaClass.simpleName})")
Result.retry() Result.retry()
} }
} }
@@ -49,7 +49,7 @@ class MailIdleService : Service() {
reconcile() reconcile()
if (watchers.isEmpty()) stopSelf(startId) if (watchers.isEmpty()) stopSelf(startId)
} catch (error: Exception) { } catch (error: Exception) {
android.util.Log.e(TAG, "Could not start mailbox watchers", error) android.util.Log.e(TAG, "Could not start mailbox watchers (${error.javaClass.simpleName})")
} }
}.start() }.start()
return START_STICKY return START_STICKY
@@ -102,7 +102,9 @@ class MailIdleService : Service() {
) )
failures = 0 failures = 0
} catch (error: Exception) { } catch (error: Exception) {
if (!watcher.stopped.get()) android.util.Log.w(TAG, "IMAP watcher disconnected for ${account.optString("email")}", error) if (!watcher.stopped.get()) {
android.util.Log.w(TAG, "IMAP watcher disconnected (${error.javaClass.simpleName})")
}
failures += 1 failures += 1
} finally { } finally {
watcher.folder = null watcher.folder = null
@@ -134,6 +136,7 @@ class MailIdleService : Service() {
.setContentIntent(appPendingIntent()) .setContentIntent(appPendingIntent())
.setOngoing(true) .setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW) .setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.build() .build()
private fun appPendingIntent(): PendingIntent { private fun appPendingIntent(): PendingIntent {
@@ -217,19 +220,26 @@ class MailIdleService : Service() {
appContext, 0, launchIntent, appContext, 0, launchIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
) )
val title = if (count == 1) "New mail" else "$count new messages" val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false)
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email) .setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(title) .setContentTitle("New mail")
.setContentText(email) .setContentText(NotificationPrivacyPolicy.newMailText(showDetails, email, count))
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle("ep-mail")
.setContentText("New mail")
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build())
.setContentIntent(pendingIntent) .setContentIntent(pendingIntent)
.build() .build()
try { try {
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification) NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
} catch (error: SecurityException) { } catch (error: SecurityException) {
android.util.Log.w(TAG, "Notification permission is unavailable", error) android.util.Log.w(TAG, "Notification permission is unavailable (${error.javaClass.simpleName})")
} }
} }
val update = JSONObject() val update = JSONObject()
@@ -254,12 +264,20 @@ class MailIdleService : Service() {
NotificationManager.IMPORTANCE_DEFAULT NotificationManager.IMPORTANCE_DEFAULT
)) ))
} }
val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false)
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID) val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email) .setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle("Mail reminder") .setContentTitle("Mail reminder")
.setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" }) .setContentText(NotificationPrivacyPolicy.reminderText(showDetails, reminder.optString("subject")))
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle("ep-mail")
.setContentText("A mail reminder is due")
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.build())
.setContentIntent(appPendingIntentFor(appContext)) .setContentIntent(appPendingIntentFor(appContext))
.build() .build()
try { try {
@@ -268,7 +286,7 @@ class MailIdleService : Service() {
notification notification
) )
} catch (error: SecurityException) { } catch (error: SecurityException) {
android.util.Log.w(TAG, "Reminder notification permission is unavailable", error) android.util.Log.w(TAG, "Reminder notification permission is unavailable (${error.javaClass.simpleName})")
} }
} }
val update = JSONObject() val update = JSONObject()
@@ -1,19 +1,296 @@
package studio.daybreak.mail; package studio.daybreak.mail;
import android.Manifest; import android.Manifest;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.app.ActivityCompat; import androidx.core.app.ActivityCompat;
import com.getcapacitor.BridgeActivity; import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity { public class MainActivity extends BridgeActivity {
private static final int UNLOCK_REQUEST_CODE = 705;
private FrameLayout appLockOverlay;
private TextView appLockMessage;
private Button appLockButton;
private boolean appLocked;
private boolean awaitingUnlockResult;
private boolean activityResumed;
private boolean vaultRecoveryRequired;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(EpMailPlugin.class); registerPlugin(EpMailPlugin.class);
super.onCreate(savedInstanceState);
hardenWebView();
AndroidAccountVault.INSTANCE.initialize(getApplicationContext());
try {
AndroidAccountVault.INSTANCE.read();
} catch (Exception storageError) {
vaultRecoveryRequired = true;
createVaultRecoveryOverlay();
return;
}
createAppLockOverlay();
if (isAppLockEnabled()) lockWebView();
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701); ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
} }
} }
@Override
public void onResume() {
super.onResume();
if (vaultRecoveryRequired) return;
activityResumed = true;
if (isAppLockEnabled() && appLocked) {
lockWebView();
configureUnlockButton();
}
}
@Override
public void onPause() {
activityResumed = false;
if (!vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
super.onPause();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != UNLOCK_REQUEST_CODE) return;
awaitingUnlockResult = false;
if (resultCode == RESULT_OK && isAppLockEnabled()) unlockWebView(true);
else updateAppLockMessage("Unlock with your Android screen lock to view mail.");
}
public void onAppLockSettingChanged(boolean enabled) {
runOnUiThread(() -> {
if (!enabled) {
awaitingUnlockResult = false;
unlockWebView(false);
} else if (activityResumed) {
appLocked = false;
} else {
lockWebView();
}
});
}
private boolean isAppLockEnabled() {
try {
return AndroidAccountVault.INSTANCE.appLockEnabled();
} catch (Exception ignored) {
// If the encrypted setting cannot be read, prefer locking over exposing stale UI.
return true;
}
}
private void hardenWebView() {
if (getBridge() == null || getBridge().getWebView() == null) return;
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
WebView webView = getBridge().getWebView();
android.webkit.WebSettings settings = webView.getSettings();
settings.setAllowFileAccess(false);
settings.setAllowContentAccess(false);
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
settings.setGeolocationEnabled(false);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
private void createVaultRecoveryOverlay() {
View content = findViewById(android.R.id.content);
if (!(content instanceof FrameLayout)) return;
FrameLayout overlay = new FrameLayout(this);
overlay.setBackgroundColor(Color.rgb(25, 21, 18));
overlay.setClickable(true);
overlay.setFocusable(true);
LinearLayout panel = new LinearLayout(this);
panel.setOrientation(LinearLayout.VERTICAL);
panel.setGravity(Gravity.CENTER);
panel.setPadding(dp(28), dp(28), dp(28), dp(28));
TextView title = new TextView(this);
title.setText("Saved data could not be opened");
title.setTextColor(Color.rgb(238, 230, 215));
title.setTextSize(21);
title.setGravity(Gravity.CENTER);
panel.addView(title, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TextView details = new TextView(this);
details.setText("ep-mail could not decrypt its saved local data. It has not been reset or replaced. Try restoring the same device/app state if available. If you cannot recover it, open Android App info and clear ep-mail data to start fresh; this permanently removes saved accounts, cached mail, drafts, queued sends, DAV settings, and OpenPGP keys. Attachments already saved to Downloads remain there.");
details.setTextColor(Color.rgb(210, 199, 181));
details.setTextSize(14);
details.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams detailsParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
detailsParams.topMargin = dp(16);
panel.addView(details, detailsParams);
Button settingsButton = new Button(this);
settingsButton.setText("Open Android App info");
settingsButton.setOnClickListener(view -> {
try {
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName())));
} catch (Exception ignored) {
// Keep the recovery instructions visible if Settings cannot be launched.
}
});
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
buttonParams.gravity = Gravity.CENTER_HORIZONTAL;
buttonParams.topMargin = dp(24);
panel.addView(settingsButton, buttonParams);
overlay.addView(panel, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
((FrameLayout) content).addView(overlay, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (getBridge() != null && getBridge().getWebView() != null) {
getBridge().getWebView().getSettings().setJavaScriptEnabled(false);
}
}
private void createAppLockOverlay() {
View content = findViewById(android.R.id.content);
if (!(content instanceof FrameLayout)) return;
appLockOverlay = new FrameLayout(this);
appLockOverlay.setBackgroundColor(Color.rgb(25, 21, 18));
appLockOverlay.setClickable(true);
appLockOverlay.setFocusable(true);
LinearLayout panel = new LinearLayout(this);
panel.setOrientation(LinearLayout.VERTICAL);
panel.setGravity(Gravity.CENTER);
panel.setPadding(dp(28), dp(28), dp(28), dp(28));
TextView title = new TextView(this);
title.setText("ep-mail is locked");
title.setTextColor(Color.rgb(238, 230, 215));
title.setTextSize(22);
title.setGravity(Gravity.CENTER);
panel.addView(title, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
appLockMessage = new TextView(this);
appLockMessage.setText("Unlock with your Android screen lock to view mail.");
appLockMessage.setTextColor(Color.rgb(185, 171, 151));
appLockMessage.setTextSize(15);
appLockMessage.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams messageParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
messageParams.topMargin = dp(12);
panel.addView(appLockMessage, messageParams);
appLockButton = new Button(this);
appLockButton.setText("Unlock");
appLockButton.setOnClickListener(view -> requestDeviceUnlock());
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
buttonParams.gravity = Gravity.CENTER_HORIZONTAL;
buttonParams.topMargin = dp(24);
panel.addView(appLockButton, buttonParams);
FrameLayout.LayoutParams panelParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
appLockOverlay.addView(panel, panelParams);
appLockOverlay.setVisibility(View.GONE);
((FrameLayout) content).addView(appLockOverlay, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
private void requestDeviceUnlock() {
if (awaitingUnlockResult) return;
KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (keyguard == null || !keyguard.isDeviceSecure()) {
updateAppLockMessage("Set a PIN, pattern, or password in Android Settings to unlock ep-mail.");
configureUnlockButton();
return;
}
configureUnlockButton();
Intent confirmIntent = keyguard.createConfirmDeviceCredentialIntent(
"Unlock ep-mail",
"Confirm your Android screen lock to view mail."
);
if (confirmIntent == null) {
updateAppLockMessage("Android could not start screen-lock verification. Try again after unlocking your device.");
return;
}
awaitingUnlockResult = true;
try {
startActivityForResult(confirmIntent, UNLOCK_REQUEST_CODE);
} catch (Exception error) {
awaitingUnlockResult = false;
updateAppLockMessage("Could not start Android screen-lock verification. Try again.");
}
}
private void configureUnlockButton() {
if (appLockButton == null) return;
KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (keyguard != null && keyguard.isDeviceSecure()) {
appLockButton.setText("Unlock");
appLockButton.setOnClickListener(view -> requestDeviceUnlock());
} else {
appLockButton.setText("Open security settings");
appLockButton.setOnClickListener(view -> startActivity(
new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS)));
}
}
private void lockWebView() {
appLocked = true;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE);
if (getBridge() != null) {
WebView webView = getBridge().getWebView();
webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
webView.getSettings().setJavaScriptEnabled(false);
}
}
private void unlockWebView(boolean reload) {
appLocked = false;
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (getBridge() != null) {
WebView webView = getBridge().getWebView();
webView.getSettings().setJavaScriptEnabled(true);
webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO);
if (reload) webView.reload();
}
if (appLockOverlay != null) appLockOverlay.setVisibility(View.GONE);
if (appLockButton != null) {
appLockButton.setText("Unlock");
appLockButton.setOnClickListener(view -> requestDeviceUnlock());
}
}
private void updateAppLockMessage(String message) {
if (appLockMessage != null) appLockMessage.setText(message);
}
private int dp(int value) {
return Math.round(value * getResources().getDisplayMetrics().density);
}
} }
@@ -0,0 +1,15 @@
package studio.daybreak.mail
internal object NotificationPrivacyPolicy {
const val DEFAULT_SHOW_DETAILS = false
fun newMailText(showDetails: Boolean, email: String, count: Int): String =
if (showDetails) {
if (count == 1) email else "$count new messages · $email"
} else {
"Open ep-mail to check your inbox"
}
fun reminderText(showDetails: Boolean, subject: String): String =
if (showDetails && subject.isNotBlank()) subject else "A snoozed message is due"
}
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules xmlns:android="http://schemas.android.com/apk/res/android">
<cloud-backup>
<exclude domain="root" path="." />
<exclude domain="file" path="." />
<exclude domain="database" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="external" path="." />
</cloud-backup>
<device-transfer>
<exclude domain="root" path="." />
<exclude domain="file" path="." />
<exclude domain="database" path="." />
<exclude domain="sharedpref" path="." />
<exclude domain="external" path="." />
</device-transfer>
</data-extraction-rules>
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="." />
<cache-path name="my_cache_images" path="." />
</paths>
@@ -0,0 +1,54 @@
package studio.daybreak.mail
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class AndroidMailTransportTest {
@Test
fun imapUsesRequiredStarttlsWhenImplicitTlsIsOff() {
val properties = AndroidMailTransport.imapProperties(
MailServerConnection("imap.example.test", 143, false)
)
assertEquals("imap", properties.getProperty("mail.store.protocol"))
assertEquals("true", properties.getProperty("mail.imap.starttls.enable"))
assertEquals("true", properties.getProperty("mail.imap.starttls.required"))
assertEquals("true", properties.getProperty("mail.imap.ssl.checkserveridentity"))
assertNull(properties.getProperty("mail.imap.ssl.trust"))
assertNull(properties.getProperty("mail.imap.ssl.socketFactory"))
assertNull(properties.getProperty("mail.imap.ssl.enable"))
}
@Test
fun imapUsesImplicitTlsForSecurePort() {
val properties = AndroidMailTransport.imapProperties(
MailServerConnection("imap.example.test", 993, true)
)
assertEquals("imaps", properties.getProperty("mail.store.protocol"))
assertEquals("true", properties.getProperty("mail.imaps.ssl.enable"))
assertEquals("true", properties.getProperty("mail.imaps.ssl.checkserveridentity"))
assertNull(properties.getProperty("mail.imaps.ssl.trust"))
assertNull(properties.getProperty("mail.imaps.ssl.socketFactory"))
assertNull(properties.getProperty("mail.imaps.starttls.required"))
}
@Test
fun smtpSupportsStarttlsAndImplicitTlsWithoutDowngrade() {
val startTls = AndroidMailTransport.smtpProperties(
MailServerConnection("smtp.example.test", 587, false)
)
assertEquals("true", startTls.getProperty("mail.smtp.starttls.enable"))
assertEquals("true", startTls.getProperty("mail.smtp.starttls.required"))
assertNull(startTls.getProperty("mail.smtp.ssl.trust"))
assertNull(startTls.getProperty("mail.smtp.ssl.socketFactory"))
val implicitTls = AndroidMailTransport.smtpProperties(
MailServerConnection("smtp.example.test", 465, true)
)
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.enable"))
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.checkserveridentity"))
assertNull(implicitTls.getProperty("mail.smtp.ssl.trust"))
assertNull(implicitTls.getProperty("mail.smtp.ssl.socketFactory"))
assertNull(implicitTls.getProperty("mail.smtp.starttls.required"))
}
}
@@ -0,0 +1,66 @@
package studio.daybreak.mail
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
class AndroidPgpConfirmationGateTest {
@Test
fun cancelDoesNotRunProtectedActionAndCannotBeOverriddenLater() {
var prompt: AndroidPgpConfirmationGate.Prompt? = null
var protectedActionCount = 0
var cancelCount = 0
val gate = AndroidPgpConfirmationGate(
showPrompt = { prompt = it },
dispatch = { action -> action() }
)
gate.request(
title = "Confirm key change",
message = "Check the fingerprint",
confirmLabel = "Confirm",
onConfirmed = { protectedActionCount += 1 },
onCancelled = { cancelCount += 1 }
)
assertEquals(0, protectedActionCount)
assertEquals(0, cancelCount)
assertNotNull(prompt)
prompt!!.cancel()
prompt!!.confirm()
prompt!!.cancel()
assertEquals(0, protectedActionCount)
assertEquals(1, cancelCount)
}
@Test
fun confirmRunsProtectedActionExactlyOnce() {
var prompt: AndroidPgpConfirmationGate.Prompt? = null
var protectedActionCount = 0
var cancelCount = 0
val gate = AndroidPgpConfirmationGate(
showPrompt = { prompt = it },
dispatch = { action -> action() }
)
gate.request(
title = "Send plaintext?",
message = "The message will not be encrypted",
confirmLabel = "Send plaintext",
onConfirmed = { protectedActionCount += 1 },
onCancelled = { cancelCount += 1 }
)
assertNotNull(prompt)
assertEquals("Send plaintext", prompt!!.confirmLabel)
prompt!!.confirm()
prompt!!.confirm()
prompt!!.cancel()
assertEquals(1, protectedActionCount)
assertEquals(0, cancelCount)
assertTrue(prompt!!.message.contains("not be encrypted"))
}
}
@@ -0,0 +1,83 @@
package studio.daybreak.mail
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class AndroidPgpPolicyTest {
private val firstFingerprint = "0123456789ABCDEF0123456789ABCDEF01234567"
private val secondFingerprint = "89ABCDEF0123456789ABCDEF0123456789ABCDEF"
@Test
fun unchangedOrLoweredTrustDoesNotPrompt() {
val verified = contact(firstFingerprint, "alice@example.test", "verified")
assertNull(AndroidPgpPolicy.storeChangeWarning(listOf(verified), listOf(verified)))
assertNull(AndroidPgpPolicy.storeChangeWarning(listOf(verified), listOf(verified.copy(trust = "unknown"))))
}
@Test
fun trustElevationRequiresTheFullFingerprintWarning() {
val previous = contact(firstFingerprint, "alice@example.test", "unknown")
val warning = AndroidPgpPolicy.storeChangeWarning(
listOf(previous),
listOf(previous.copy(trust = "verified"))
)
assertTrue(warning!!.contains("alice@example.test"))
assertTrue(warning.contains("0123 4567 89AB CDEF"))
assertTrue(warning.contains("New trust: verified"))
}
@Test
fun addingAKeyForAnExistingAddressRequiresReplacementWarning() {
val previous = contact(firstFingerprint, "alice@example.test", "unknown")
val replacement = contact(secondFingerprint, "ALICE@example.test", "unknown")
val warning = AndroidPgpPolicy.storeChangeWarning(listOf(previous), listOf(previous, replacement))
assertTrue(warning!!.contains("different key is already stored"))
assertTrue(warning.contains("0123 4567 89AB CDEF"))
assertTrue(warning.contains("89AB CDEF 0123 4567"))
}
@Test
fun plaintextPromptNamesRecipientsAndMatchingKeyFingerprints() {
val warning = AndroidPgpPolicy.plaintextSendWarning(
recipients = listOf("Alice@example.test", "bob@example.test"),
availableKeys = listOf(AndroidPgpPolicy.RecipientKey("alice@example.test", firstFingerprint)),
encryptionWasRequested = false
)
assertTrue(warning!!.contains("alice@example.test"))
assertTrue(warning.contains("0123 4567 89AB CDEF"))
assertTrue(warning.contains("bob@example.test — no key stored"))
assertTrue(warning.contains("readable by the mail provider"))
}
@Test
fun noPlaintextPromptWhenNoKeyExistsAndEncryptionWasNotRequested() {
assertNull(
AndroidPgpPolicy.plaintextSendWarning(
recipients = listOf("alice@example.test"),
availableKeys = emptyList(),
encryptionWasRequested = false
)
)
}
@Test
fun explicitEncryptionRequestPromptsEvenWhenNoRecipientKeyExists() {
val warning = AndroidPgpPolicy.plaintextSendWarning(
recipients = listOf("alice@example.test"),
availableKeys = emptyList(),
encryptionWasRequested = true
)
assertTrue(warning!!.contains("OpenPGP was requested"))
assertTrue(warning.contains("alice@example.test — no key stored"))
assertFalse(warning.contains("Fingerprint:"))
}
private fun contact(fingerprint: String, email: String, trust: String) =
AndroidPgpPolicy.ContactKey(fingerprint, listOf(email), trust)
}
@@ -0,0 +1,14 @@
package studio.daybreak.mail
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class AndroidVaultKeyPolicyTest {
@Test
fun newKeyMayBeCreatedOnlyWhenThereIsNoEncryptedStore() {
assertTrue(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = false))
assertFalse(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = true))
assertTrue(AndroidVaultKeyPolicy.MISSING_KEY_MESSAGE.contains("not reset or replaced"))
}
}
@@ -0,0 +1,20 @@
package studio.daybreak.mail
import org.junit.Assert.assertEquals
import org.junit.Test
class AttachmentNamePolicyTest {
@Test
fun stripsPathSeparatorsAndControlCharacters() {
assertEquals(".._secret.txt", AttachmentNamePolicy.sanitize("../secret.txt"))
assertEquals("folder__secret.txt", AttachmentNamePolicy.sanitize("folder\\/secret.txt"))
assertEquals("bad_name.txt", AttachmentNamePolicy.sanitize("bad\u0000name.txt"))
}
@Test
fun suppliesSafeFallbackAndBoundsLength() {
assertEquals("attachment", AttachmentNamePolicy.sanitize(".."))
assertEquals("attachment", AttachmentNamePolicy.sanitize(" "))
assertEquals(180, AttachmentNamePolicy.sanitize("a".repeat(300)).length)
}
}
@@ -0,0 +1,54 @@
package studio.daybreak.mail
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
class DavUrlPolicyTest {
@Test
fun acceptsHttpsServerUrl() {
assertEquals("https://dav.example.test/calendar", DavUrlPolicy.parseServerUrl(
"https://dav.example.test/calendar"
).toString())
}
@Test
fun rejectsCleartextAndNonWebSchemes() {
assertThrows(IllegalArgumentException::class.java) {
DavUrlPolicy.parseServerUrl("http://localhost:8080/dav")
}
assertThrows(IllegalArgumentException::class.java) {
DavUrlPolicy.parseServerUrl("ftp://dav.example.test/dav")
}
}
@Test
fun rejectsEmbeddedCredentialsAndFragments() {
assertThrows(IllegalArgumentException::class.java) {
DavUrlPolicy.parseServerUrl("https://user:pass@dav.example.test/dav")
}
assertThrows(IllegalArgumentException::class.java) {
DavUrlPolicy.parseServerUrl("https://dav.example.test/dav#fragment")
}
}
@Test
fun allowsSameOriginAndRejectsCrossOriginTargets() {
DavUrlPolicy.requireSameOrigin(
"https://dav.example.test/root",
"https://dav.example.test/calendar/"
)
assertThrows(IllegalArgumentException::class.java) {
DavUrlPolicy.requireSameOrigin(
"https://dav.example.test/root",
"https://attacker.example.test/calendar/"
)
}
assertThrows(IllegalArgumentException::class.java) {
DavUrlPolicy.requireSameOrigin(
"https://dav.example.test/root",
"http://dav.example.test/calendar/"
)
}
}
}
@@ -0,0 +1,31 @@
package studio.daybreak.mail
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Test
class NotificationPrivacyPolicyTest {
@Test
fun notificationDetailsAreDisabledByDefault() {
assertFalse(NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS)
assertEquals(
"Open ep-mail to check your inbox",
NotificationPrivacyPolicy.newMailText(NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS, "person@example.test", 1)
)
assertEquals(
"A snoozed message is due",
NotificationPrivacyPolicy.reminderText(NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS, "Private subject")
)
}
@Test
fun detailsAppearOnlyAfterExplicitOptIn() {
assertEquals("person@example.test", NotificationPrivacyPolicy.newMailText(true, "person@example.test", 1))
assertEquals(
"3 new messages · person@example.test",
NotificationPrivacyPolicy.newMailText(true, "person@example.test", 3)
)
assertEquals("Private subject", NotificationPrivacyPolicy.reminderText(true, "Private subject"))
assertEquals("A snoozed message is due", NotificationPrivacyPolicy.reminderText(true, " "))
}
}
+35 -60
View File
@@ -1,56 +1,15 @@
(() => {
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{})); if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
const messages = []; const state = window.epMailState;
const contacts=[];
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))} function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
function safeRemoteImageUrl(value){if(typeof value!=='string'||value.length>2048)return null;try{const url=new URL(value);return url.protocol==='https:'&&url.hostname&&!url.username&&!url.password?url.href:null}catch{return null}} const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
function sanitizeMailHtml(value){ function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}}
const html=String(value||'').slice(0,100000);
const inertImages=html
.replace(/<(script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track)\b[\s\S]*?<\/\1\s*>/gi,'')
.replace(/<(?:script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track|link|base|meta)\b[^>]*>/gi,'')
.replace(/<!--[\s\S]*?-->/g,'')
.replace(/<img\b[^>]*>/gi,tag=>{
const source=tag.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const alt=tag.match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const remote=source&&(source[1]||source[2]||source[3]||'').trim();
const alternative=alt&&(alt[1]||alt[2]||alt[3]||'');
return `<img${remote?` data-remote-src="${esc(remote)}"`:''}${alternative?` alt="${esc(alternative)}"`:''}>`;
})
.replace(/\s(?:src|srcset|background|poster|action|formaction|href|xlink:href|srcdoc|dynsrc|lowsrc|style)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,'');
const document=new DOMParser().parseFromString(inertImages,'text/html');
const allowed=new Set(['a','p','div','span','br','hr','h1','h2','h3','h4','h5','h6','b','strong','i','em','u','s','del','blockquote','pre','code','ul','ol','li','table','thead','tbody','tfoot','tr','th','td','img']);
const discard=new Set(['script','style','iframe','frame','object','embed','svg','math','form','input','button','textarea','select','option','link','base','meta','video','audio','source','picture','track']);
let remoteImageCount=0;
const clean=parent=>{
for(const node of [...parent.childNodes]){
if(node.nodeType!==Node.ELEMENT_NODE){if(node.nodeType!==Node.TEXT_NODE)node.remove();continue}
const name=node.localName.toLowerCase();
if(discard.has(name)){node.remove();continue}
if(!allowed.has(name)){node.replaceWith(...node.childNodes);continue}
for(const attribute of [...node.attributes]){
const key=attribute.name.toLowerCase();
const keep=(name==='img'&&(key==='alt'||key==='data-remote-src'))||
(name==='td'||name==='th')&&['colspan','rowspan'].includes(key)&&/^\d{1,2}$/.test(attribute.value);
if(!keep)node.removeAttribute(attribute.name);
}
if(name==='img'){
const url=safeRemoteImageUrl(node.getAttribute('data-remote-src'));
if(url){node.setAttribute('data-remote-src',url);remoteImageCount+=1}
else node.removeAttribute('data-remote-src');
}
clean(node);
}
};
clean(document.body);
return {html:document.body.innerHTML,remoteImageCount};
}
function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
function openMessage(id){ function openMessage(id){
activeMessage=id; state.activeMessage=id;
const m=messages.find(x=>x.id===id); const m=state.messages.find(x=>x.id===id);
if(!m)return; if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
document.body.classList.add('reader-open');
m.unread=false; m.unread=false;
renderList(); renderList();
let safeHtml={html:'',remoteImageCount:0}; let safeHtml={html:'',remoteImageCount:0};
@@ -58,7 +17,8 @@ function openMessage(id){
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`; const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:''; const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join(''); const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`; $('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><button class="reader-back" id="reader-back" type="button" aria-label="Back to messages">Back</button><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;
$('#reader-back').onclick=()=>{state.activeMessage=null;document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader();renderList()};
$('#load-remote-images')?.addEventListener('click',()=>{ $('#load-remote-images')?.addEventListener('click',()=>{
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{ $('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src')); const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
@@ -67,18 +27,33 @@ function openMessage(id){
}); });
$('.remote-image-notice')?.remove(); $('.remote-image-notice')?.remove();
}); });
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()}; $('#reader-archive').onclick=()=>{m.archived=true;state.activeMessage=null;document.body.classList.remove('reader-open');toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()}; $('#reader-delete').onclick=()=>{m.deleted=true;state.activeMessage=null;document.body.classList.remove('reader-open');toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)}; $('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
$('#reply').onclick=()=>showCompose(m); $('#reply').onclick=()=>showCompose(m);
$('#forward').onclick=()=>showCompose(m,true); $('#forward').onclick=()=>showCompose(m,true);
} }
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`} function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)} function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(state.toastTimer);state.toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send&nbsp; ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()} function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send&nbsp; ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;state.messages.unshift({id:Date.now(),initials:(window.epMailFeatures.productivity?.profileName||window.epMailFeatures.mail.connectedAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(window.epMailFeatures.productivity?.profileName||window.epMailFeatures.mail.connectedAccount?.email?.split('@')[0]||'Me'),email:(window.epMailFeatures.mail.connectedAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
function switchView(view){activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?activeFolder:view==='calendar'?'Calendar':'Contacts';} function switchView(view){state.activeView=view;$$('.rail-button[data-view]').forEach(b=>b.classList.toggle('active',b.dataset.view===view));$('.mail-layout').classList.toggle('hidden',view!=='mail');$('#calendar-view').classList.toggle('hidden',view!=='calendar');$('#contacts-view').classList.toggle('hidden',view!=='contacts');$('#sidebar-title').textContent=view==='mail'?state.activeFolder:view==='calendar'?'Calendar':'Contacts';$('#crumb-parent').textContent=view==='mail'?'Mail':'Workspace';$('#crumb-current').textContent=view==='mail'?state.activeFolder:view==='calendar'?'Calendar':'Contacts';if(view==='calendar')window.epMailFeatures.productivity.renderCalendar();if(view==='contacts')window.epMailFeatures.productivity.renderContacts();}
function renderCalendar(){} $$('.folder').forEach(b=>b.onclick=()=>{state.activeFolder=b.dataset.folder;state.activeMessage=null;document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader();$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=state.activeFolder;$('#crumb-current').textContent=state.activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{document.body.classList.remove('reader-open');switchView(b.dataset.view);});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{state.query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';state.query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=state.messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>state.selectedIds.has(m.id));visible.forEach(m=>all?state.selectedIds.delete(m.id):state.selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{state.messages.filter(m=>state.selectedIds.has(m.id)).forEach(m=>m.archived=true);state.selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{state.messages.filter(m=>state.selectedIds.has(m.id)).forEach(m=>m.deleted=true);state.selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(state.activeMessage);
function showEvent(){}
function renderContacts(){} window.epMailShell = Object.freeze({
function showContact(){} state,
$$('.folder').forEach(b=>b.onclick=()=>{activeFolder=b.dataset.folder;$$('.folder').forEach(x=>x.classList.toggle('active',x===b));$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()});$$('.rail-button[data-view]').forEach(b=>b.onclick=()=>{switchView(b.dataset.view);if(b.dataset.view==='calendar')renderCalendar();if(b.dataset.view==='contacts')renderContacts()});function applyTheme(theme,showToast=false){const themes=['daylight','wasteland','ep-wasteland','ep-daylight'];const selected=themes.includes(theme)?theme:'ep-wasteland';const info={daylight:{name:'Eternity Daylight',icon:'☼'},wasteland:{name:'Wasteland',icon:'☾'},'ep-wasteland':{name:'EP Wasteland',icon:'◈'},'ep-daylight':{name:'EP Daylight',icon:'☀'}}[selected];document.body.classList.remove('wasteland','ep-wasteland','ep-daylight');if(selected!=='daylight')document.body.classList.add(selected);document.querySelector('meta[name=theme-color]')?.setAttribute('content',selected==='ep-wasteland'?'#161210':selected==='ep-daylight'?'#f1f1e9':selected==='wasteland'?'#eee8db':'#f4f5f1');localStorage.setItem('daybreak-theme',selected);const brandLogo=$("#brand-logo");if(brandLogo)brandLogo.src=selected==='ep-wasteland'?'logo-ep-wasteland.svg':'logo-ep-daylight.svg';if(showToast)toast(`${info.name} theme`)}applyTheme(localStorage.getItem('daybreak-theme')||'ep-wasteland');$('#search').oninput=e=>{query=e.target.value;renderList()};$('#search').addEventListener('keydown',e=>{if(e.key==='Escape'){e.target.value='';query='';renderList()}});$('#compose').onclick=()=>showCompose();$('#refresh').onclick=()=>{toast('You’re all up to date');renderList()};$('#select-all').onclick=()=>{const visible=messages.filter(m=>!m.archived&&!m.deleted);const all=visible.every(m=>selectedIds.has(m.id));visible.forEach(m=>all?selectedIds.delete(m.id):selectedIds.add(m.id));renderList()};$('#archive-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.archived=true);selectedIds.clear();renderList();toast('Selected messages archived')};$('#delete-selected').onclick=()=>{messages.filter(m=>selectedIds.has(m.id)).forEach(m=>m.deleted=true);selectedIds.clear();renderList();toast('Selected messages moved to Trash')};$('#sidebar-menu').onclick=()=>toast('More mailbox options');$$('.settings-button,.help-button,.tiny-plus,.text-button').forEach(b=>b.onclick=()=>toast('You’re all caught up'));document.addEventListener('keydown',e=>{if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==='k'){e.preventDefault();$('#search').focus()}if(e.key==='Escape')$('#modal-root').innerHTML=''});$('#today-label').textContent=new Intl.DateTimeFormat('en-US',{weekday:'long',month:'long',day:'numeric'}).format(new Date()).toUpperCase();$('#reader-pane').innerHTML=emptyReader();renderList();openMessage(activeMessage); select: $,
selectAll: $$,
escapeHtml: esc,
toast,
switchView,
applyTheme,
baseRenderList: renderList,
get renderList() { return renderList; },
get openMessage() { return openMessage; },
get showCompose() { return showCompose; },
emptyReader,
wrapRenderList(decorator) { renderList = decorator(renderList); },
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
wrapShowCompose(decorator) { showCompose = decorator(showCompose); }
});
})();
+25 -22
View File
@@ -1,4 +1,9 @@
(() => {
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes. // Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
const attachmentMailUi = window.epMailFeatures.mail;
const selectAttachmentUi = attachmentMailUi.select;
const selectAllAttachmentUi = attachmentMailUi.selectAll;
const toastAttachmentUi = attachmentMailUi.toast;
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash']; const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
let attachmentItems = []; let attachmentItems = [];
@@ -45,20 +50,18 @@ async function previewAttachment(target, details) {
} }
function downloadAttachment(details) { function downloadAttachment(details) {
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; } if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('Attachment download is available for connected mailbox messages'); return; }
window.daybreakMail.saveAttachment(details) window.daybreakMail.saveAttachment(details)
.then(result => { if (result.saved) toast('Attachment saved'); }) .then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
.catch(error => toast(error.message || 'Could not save attachment')); .catch(error => toastAttachmentUi(error.message || 'Could not save attachment'));
} }
// Add a Preview button to each attachment in the reader. // Add a Preview button to each attachment in the reader.
if (typeof openMessage === 'function') { attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
const baseOpenMessage = openMessage;
openMessage = function (id) {
baseOpenMessage(id); baseOpenMessage(id);
const message = messages.find(item => item.id === id); const message = attachmentMailUi.state.messages.find(item => item.id === id);
if (!message?.uid) return; if (!message?.uid || message.pgpDecrypted) return;
$$('#reader-pane .attachment').forEach(row => { selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
const download = row.querySelector('.download'); const download = row.querySelector('.download');
if (!download || row.querySelector('.preview-attachment')) return; if (!download || row.querySelector('.preview-attachment')) return;
const button = document.createElement('button'); const button = document.createElement('button');
@@ -73,12 +76,11 @@ if (typeof openMessage === 'function') {
panel = document.createElement('div'); panel = document.createElement('div');
panel.className = 'attachment-preview'; panel.className = 'attachment-preview';
row.after(panel); row.after(panel);
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename }); void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || attachmentMailUi.state.activeFolder, filename: download.dataset.filename });
}); });
download.before(button); download.before(button);
}); });
}; });
}
async function collectAttachments() { async function collectAttachments() {
const items = []; const items = [];
@@ -103,16 +105,16 @@ async function collectAttachments() {
} }
async function openAttachmentsView() { async function openAttachmentsView() {
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; } if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
const root = $('#modal-root'); const root = selectAttachmentUi('#modal-root');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`; root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
const close = () => { root.innerHTML = ''; }; const close = () => { root.innerHTML = ''; };
root.querySelector('.modal-close').onclick = close; root.querySelector('.modal-close').onclick = close;
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const list = $('#attachment-list'); const list = selectAttachmentUi('#attachment-list');
const render = () => { const render = () => {
const text = $('#attachment-search').value.trim().toLowerCase(); const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
const type = $('#attachment-type').value; const type = selectAttachmentUi('#attachment-type').value;
const shown = attachmentItems.filter(item => (!type || item.kind === type) && const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text))); (!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
list.replaceChildren(); list.replaceChildren();
@@ -146,16 +148,17 @@ async function openAttachmentsView() {
list.append(row); list.append(row);
}); });
}; };
$('#attachment-search').oninput = render; selectAttachmentUi('#attachment-search').oninput = render;
$('#attachment-type').onchange = render; selectAttachmentUi('#attachment-type').onchange = render;
try { try {
attachmentItems = await collectAttachments(); attachmentItems = await collectAttachments();
if ($('#attachment-list')) render(); if (selectAttachmentUi('#attachment-list')) render();
} catch (error) { } catch (error) {
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.'; if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#attachment-list').textContent = error.message || 'Could not load attachments.';
} }
} }
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
$('#attachments-nav')?.addEventListener('click', openAttachmentsView); selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
}); });
})();
+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*
+25 -15
View File
@@ -1,38 +1,48 @@
(() => {
const davProductivityUi = window.epMailFeatures.productivity;
const selectDavUi = davProductivityUi.select;
function davTypeName(type){return type==='caldav'?'calendar':'contacts'} function davTypeName(type){return type==='caldav'?'calendar':'contacts'}
async function syncDav(type, uploadLocal=false){ async function syncDav(type, uploadLocal=false){
try{ try{
const localOnly=type==='caldav'?savedEvents.filter(item=>!item._dav):savedContacts.filter(item=>!item._dav); const localOnly=type==='caldav'?davProductivityUi.events.filter(item=>!item._dav):davProductivityUi.contacts.filter(item=>!item._dav);
const result=await window.daybreakMail.davSync(type); const result=await window.daybreakMail.davSync(type);
if(type==='caldav'){ if(type==='caldav'){
if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){toast(`Could not upload “${event.title}”: ${error.message}`)}} if(uploadLocal)for(const event of localOnly){try{event._dav=await window.daybreakMail.davSaveEvent(event)}catch(error){davProductivityUi.toast(`Could not upload “${event.title}”: ${error.message}`)}}
savedEvents=[...localOnly,...result.items]; davProductivityUi.events=[...localOnly,...result.items];
productWrite(productKeys.events,savedEvents);renderCalendar();toast(`Synced ${result.items.length} calendar events`); davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar();davProductivityUi.toast(`Synced ${result.items.length} calendar events`);
}else{ }else{
if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){toast(`Could not upload “${contact.name}”: ${error.message}`)}} if(uploadLocal)for(const contact of localOnly){try{contact._dav=await window.daybreakMail.davSaveContact(contact)}catch(error){davProductivityUi.toast(`Could not upload “${contact.name}”: ${error.message}`)}}
savedContacts=[...localOnly,...result.items]; davProductivityUi.contacts=[...localOnly,...result.items];
productWrite(productKeys.contacts,savedContacts);renderContacts();toast(`Synced ${result.items.length} contacts`); davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
} }
}catch(error){toast(error.message||`Could not sync ${davTypeName(type)}`)} }catch(error){davProductivityUi.toast(error.message||`Could not sync ${davTypeName(type)}`)}
} }
async function openDavManager(type){ async function openDavManager(type){
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV'; const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
try{ try{
const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId']; const data=await window.daybreakMail.davList(),accounts=data[type]||[],activeId=data[type==='caldav'?'activeCaldavId':'activeCarddavId'];
const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${esc(account.username)}</strong><small>${esc(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>esc(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${esc(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${esc(account.id)}">Remove</button></div></div>`).join(''); const rows=accounts.map(account=>`<div class="account-row"><div class="account-row-info"><strong>${davProductivityUi.escapeHtml(account.username)}</strong><small>${davProductivityUi.escapeHtml(account.serverUrl)} · ${account.collections.length} ${type==='caldav'?'calendars':'address books'}</small><small>${account.collections.map(collection=>davProductivityUi.escapeHtml(collection.name)).join(', ')}</small></div><div class="account-row-actions">${account.id===activeId?'<span class="account-current">Current</span>':`<button class="outline-button" data-dav-activate="${davProductivityUi.escapeHtml(account.id)}">Use</button>`}<button class="discard" data-dav-remove="${davProductivityUi.escapeHtml(account.id)}">Remove</button></div></div>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`; root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${label} servers</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields account-list">${rows||`<p class="account-note">No ${label} server connected.</p>`}</div><div class="compose-footer"><button class="discard modal-close">Close</button><button class="send-button" id="add-dav-server">+ Add server</button></div></div></div>`;
const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; const close=()=>root.innerHTML='';root.querySelectorAll('.modal-close').forEach(button=>button.onclick=close);root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type); root.querySelector('#add-dav-server').onclick=()=>showDavConnect(type);
root.onclick=async event=>{ root.onclick=async event=>{
const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){toast(error.message)}return} const activate=event.target.closest('[data-dav-activate]');if(activate){try{await window.daybreakMail.davActivate(type,activate.dataset.davActivate);close();await syncDav(type)}catch(error){davProductivityUi.toast(error.message)}return}
const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){savedEvents=savedEvents.filter(item=>!item._dav);productWrite(productKeys.events,savedEvents);renderCalendar()}else{savedContacts=savedContacts.filter(item=>!item._dav);productWrite(productKeys.contacts,savedContacts);renderContacts()}await openDavManager(type)}catch(error){toast(error.message)} } const remove=event.target.closest('[data-dav-remove]');if(remove){if(!confirm(`Remove this ${label} server from ep-mail?`))return;try{const result=await window.daybreakMail.davRemove(type,remove.dataset.davRemove);close();if(result.activeId)await syncDav(type);else if(type==='caldav'){davProductivityUi.events=davProductivityUi.events.filter(item=>!item._dav);davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar()}else{davProductivityUi.contacts=davProductivityUi.contacts.filter(item=>!item._dav);davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts()}await openDavManager(type)}catch(error){davProductivityUi.toast(error.message)} }
}; };
}catch(error){toast(error.message||`Could not load ${label} servers`)} }catch(error){davProductivityUi.toast(error.message||`Could not load ${label} servers`)}
} }
function showDavConnect(type){ function showDavConnect(type){
const root=$('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV'; const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test &amp; connect</button></div></div></div>`; root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Connect ${label} server</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Use the DAV server URL from your provider. Your password is encrypted in the OS credential store; secure HTTPS is required.</p><label class="compose-line"><span>Server URL</span><input id="dav-server-url" type="url" placeholder="https://dav.example.com/remote.php/dav"></label><label class="compose-line"><span>Username</span><input id="dav-username" autocomplete="username" placeholder="name@example.com"></label><label class="compose-line"><span>Password</span><input id="dav-password" type="password" autocomplete="current-password" placeholder="App password"></label><p id="dav-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="dav-cancel">Cancel</button><button class="send-button" id="dav-connect">Test &amp; connect</button></div></div></div>`;
const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close; const close=()=>root.innerHTML='';root.querySelector('.modal-close').onclick=close;root.querySelector('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};root.querySelector('#dav-cancel').onclick=close;
root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}}; root.querySelector('#dav-connect').onclick=async()=>{const button=root.querySelector('#dav-connect'),status=root.querySelector('#dav-status');button.disabled=true;status.textContent='Checking the server and discovering collections…';try{await window.daybreakMail.davConnect({type,serverUrl:root.querySelector('#dav-server-url').value,username:root.querySelector('#dav-username').value,password:root.querySelector('#dav-password').value});close();davProductivityUi.toast(`${label} server connected`);await syncDav(type,true)}catch(error){status.textContent=error.message||`Could not connect to ${label}`;button.disabled=false}};
root.querySelector('#dav-server-url').focus(); root.querySelector('#dav-server-url').focus();
} }
document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true); document.addEventListener('click',event=>{const button=event.target.closest('#caldav-sync,#carddav-sync');if(!button)return;event.preventDefault();event.stopImmediatePropagation();syncDav(button.id.startsWith('caldav')?'caldav':'carddav')},true);
window.epMailFeatures.dav = Object.freeze({
openManager: openDavManager,
sync: syncDav
});
})();
+28
View File
@@ -0,0 +1,28 @@
const { randomUUID } = require('node:crypto');
function createAccountStore(secureStore, { createId = randomUUID } = {}) {
return {
async load() {
try {
const stored = await secureStore.load();
if (Array.isArray(stored.accounts)) return stored;
if (stored.email) {
const account = { ...stored, id: stored.id || createId() };
const migrated = { accounts: [account], activeId: account.id };
await secureStore.save(migrated);
return migrated;
}
return { accounts: [], activeId: null };
} catch (error) {
if (error.code === 'ENOENT') return null;
throw error;
}
},
save(store) {
return secureStore.save(store);
}
};
}
module.exports = { createAccountStore };
+40
View File
@@ -0,0 +1,40 @@
const { randomUUID } = require('node:crypto');
function escapeIcal(value = '') {
return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;');
}
function escapeVcard(value = '') {
return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;');
}
function safeDavUid(value, createId) {
const uid = String(value || createId());
if (!uid || uid.length > 255 || /[\\/\\?#\u0000-\u001f\u007f]/.test(uid)) {
throw new Error('The DAV item identifier is invalid.');
}
return uid;
}
function makeCalendarData(event, { createId = randomUUID, now = () => new Date() } = {}) {
const uid = safeDavUid(event._dav?.uid, createId);
const stamp = now().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
const start = event.time
? new Date(`${event.date}T${event.time}:00`).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
: event.date.replace(/-/g, '');
const endDate = event.time
? new Date(new Date(`${event.date}T${event.time}:00`).getTime() + 3600000)
.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
: null;
return `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${uid}\r\nDTSTAMP:${stamp}\r\n${event.time ? `DTSTART:${start}\r\nDTEND:${endDate}\r\n` : `DTSTART;VALUE=DATE:${start}\r\n`}SUMMARY:${escapeIcal(event.title)}\r\n${event.place ? `LOCATION:${escapeIcal(event.place)}\r\n` : ''}${event.notes ? `DESCRIPTION:${escapeIcal(event.notes)}\r\n` : ''}END:VEVENT\r\nEND:VCALENDAR\r\n`;
}
function makeVcard(contact, { createId = randomUUID } = {}) {
const name = String(contact.name || '').trim().split(/\s+/);
const first = name.shift() || '';
const last = name.join(' ');
const uid = safeDavUid(contact._dav?.uid, createId);
return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${uid}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`;
}
module.exports = { escapeIcal, escapeVcard, makeCalendarData, makeVcard };
+63
View File
@@ -0,0 +1,63 @@
function asSafeDavUrl(value, baseUrl, serverOrigin) {
if (typeof value !== 'string' || !value.trim()) return null;
try {
const url = new URL(value, baseUrl);
if (url.origin !== serverOrigin || url.username || url.password || url.search || url.hash) return null;
return url;
} catch {
return null;
}
}
function assertDavObjectReference({ config, remote, collections, objects }) {
if (!config || typeof config.id !== 'string' || typeof config.serverUrl !== 'string') {
throw new Error('The DAV account reference is invalid.');
}
if (!remote || typeof remote !== 'object' || Array.isArray(remote) || remote.accountId !== config.id) {
throw new Error('This DAV item does not belong to the selected account.');
}
if (!Array.isArray(collections) || !Array.isArray(objects)) {
throw new Error('The DAV collection could not be verified.');
}
let serverUrl;
try {
serverUrl = new URL(config.serverUrl);
} catch {
throw new Error('The DAV server address is invalid.');
}
if (!['https:', 'http:'].includes(serverUrl.protocol) || serverUrl.username || serverUrl.password) {
throw new Error('The DAV server address is invalid.');
}
const requestedCollection = asSafeDavUrl(remote.collectionUrl, serverUrl.href, serverUrl.origin);
const collection = collections.find(candidate => {
const url = asSafeDavUrl(candidate?.url, serverUrl.href, serverUrl.origin);
return url && requestedCollection && url.href === requestedCollection.href;
});
if (!collection || !requestedCollection) throw new Error('This DAV collection is not available on the selected server.');
const collectionUrl = asSafeDavUrl(collection.url, serverUrl.href, serverUrl.origin);
const objectUrl = asSafeDavUrl(remote.objectUrl, collectionUrl.href, serverUrl.origin);
if (!objectUrl) throw new Error('This DAV object address is not valid for the selected server.');
const collectionPath = collectionUrl.pathname.endsWith('/') ? collectionUrl.pathname : `${collectionUrl.pathname}/`;
if (objectUrl.pathname === collectionPath || !objectUrl.pathname.startsWith(collectionPath)) {
throw new Error('This DAV object is outside the selected collection.');
}
const object = objects.find(candidate => {
const url = asSafeDavUrl(candidate?.url, collectionUrl.href, serverUrl.origin);
return url && url.href === objectUrl.href;
});
if (!object) throw new Error('This DAV object is no longer available in the selected collection.');
if (object.etag != null && remote.etag !== object.etag) {
throw new Error('This DAV item has changed on the server. Sync again before editing it.');
}
if (remote.etag != null && typeof remote.etag !== 'string') {
throw new Error('The DAV object version is invalid.');
}
return { collection, object, collectionUrl: collectionUrl.href, objectUrl: objectUrl.href };
}
module.exports = { assertDavObjectReference };
+259
View File
@@ -0,0 +1,259 @@
function registerDavIpcHandlers({
registerIpcHandler,
readDavStore,
saveDavStore,
davPublicConfig,
openDavClient,
activeDavConfig,
getICAL,
makeCalendarData,
makeVcard,
randomUUID,
assertDavObjectReference
}) {
registerIpcHandler('dav:list', async () => {
const store = await readDavStore();
return {
caldav: store.caldav.map(davPublicConfig),
carddav: store.carddav.map(davPublicConfig),
activeCaldavId: store.activeCaldavId,
activeCarddavId: store.activeCarddavId
};
});
registerIpcHandler('dav:connect', async (_event, input) => {
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
const serverUrl = String(input?.serverUrl || '').trim();
const username = String(input?.username || '').trim();
const password = String(input?.password || '');
let parsedUrl;
try { parsedUrl = new URL(serverUrl); } catch { throw new Error('Enter a valid CalDAV or CardDAV server URL.'); }
if (!['https:', 'http:'].includes(parsedUrl.protocol) || parsedUrl.username || parsedUrl.password ||
(parsedUrl.protocol === 'http:' && !['localhost', '127.0.0.1', '::1'].includes(parsedUrl.hostname))) {
throw new Error('DAV server URLs must use HTTPS and must not contain embedded credentials.');
}
if (!username || !password) throw new Error('Enter the DAV username and password.');
const config = { id: randomUUID(), type, serverUrl: parsedUrl.href, username, password };
const client = await openDavClient(config, type);
const collections = type === 'caldav' ? await client.fetchCalendars() : await client.fetchAddressBooks();
if (!collections.length) throw new Error(`No ${type === 'caldav' ? 'calendars' : 'address books'} were found on this server.`);
config.collections = collections.map(collection => ({
url: collection.url,
name: typeof collection.displayName === 'string' ? collection.displayName : collection.url
}));
const store = await readDavStore();
const key = type;
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
const duplicate = store[key].find(account => account.serverUrl === config.serverUrl && account.username.toLowerCase() === username.toLowerCase());
if (duplicate) config.id = duplicate.id;
store[key] = [...store[key].filter(account => account.id !== config.id), config];
store[activeKey] = config.id;
await saveDavStore(store);
return {
config: davPublicConfig(config),
collections: config.collections,
accounts: {
caldav: store.caldav.map(davPublicConfig),
carddav: store.carddav.map(davPublicConfig),
activeCaldavId: store.activeCaldavId,
activeCarddavId: store.activeCarddavId
}
};
});
registerIpcHandler('dav:activate', async (_event, input) => {
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
const store = await readDavStore();
const config = store[type].find(item => item.id === input?.id);
if (!config) throw new Error('That DAV account could not be found.');
store[type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId'] = config.id;
await saveDavStore(store);
return { id: config.id };
});
registerIpcHandler('dav:remove', async (_event, input) => {
const type = input?.type === 'carddav' ? 'carddav' : 'caldav';
const store = await readDavStore();
store[type] = store[type].filter(item => item.id !== input?.id);
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
if (store[activeKey] === input?.id) store[activeKey] = store[type][0]?.id || null;
await saveDavStore(store);
return { accounts: store[type].map(davPublicConfig), activeId: store[activeKey] };
});
registerIpcHandler('dav:sync', async (_event, requestedType) => {
const type = requestedType === 'carddav' ? 'carddav' : 'caldav';
const store = await readDavStore();
const config = activeDavConfig(store, type);
if (!config) throw new Error(`Connect a ${type === 'caldav' ? 'CalDAV' : 'CardDAV'} server first.`);
const client = await openDavClient(config, type);
if (type === 'caldav') {
const { default: ICAL } = await getICAL();
const calendars = await client.fetchCalendars();
const result = [];
for (const calendar of calendars) {
const objects = await client.fetchCalendarObjects({ calendar });
for (const object of objects) {
if (!object.data) continue;
try {
const component = new ICAL.Component(ICAL.parse(object.data));
for (const part of component.getAllSubcomponents('vevent')) {
const parsed = new ICAL.Event(part);
if (!parsed.startDate) continue;
const start = parsed.startDate.toJSDate();
result.push({
id: `dav:${config.id}:${encodeURIComponent(object.url)}:${encodeURIComponent(parsed.uid)}`,
title: parsed.summary || '(no title)',
date: `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')}`,
time: parsed.startDate.isDate ? '' : `${String(start.getHours()).padStart(2, '0')}:${String(start.getMinutes()).padStart(2, '0')}`,
with: part.getAllProperties('attendee').map(property => String(property.getFirstValue() || '').replace(/^mailto:/i, '')).join(', '),
place: parsed.location || '',
notes: parsed.description || '',
_dav: { accountId: config.id, collectionUrl: calendar.url, objectUrl: object.url, etag: object.etag, uid: parsed.uid }
});
}
} catch {}
}
}
return { items: result, account: davPublicConfig(config) };
}
const { default: ICAL } = await getICAL();
const books = await client.fetchAddressBooks();
const result = [];
for (const book of books) {
const cards = await client.fetchVCards({ addressBook: book });
for (const card of cards) {
if (!card.data) continue;
try {
const parsed = new ICAL.Component(ICAL.parse(card.data));
const name = String(parsed.getFirstPropertyValue('fn') || '').trim();
if (!name) continue;
const emails = parsed.getAllProperties('email').map(property => String(property.getFirstValue() || ''));
const uid = String(parsed.getFirstPropertyValue('uid') || '');
result.push({
id: `dav:${config.id}:${encodeURIComponent(card.url)}:${encodeURIComponent(uid)}`,
name,
email: emails[0] || '',
note: String(parsed.getFirstPropertyValue('note') || ''),
initials: name.split(/\s+/).map(part => part[0]).join('').slice(0, 2).toUpperCase(),
color: '#dce9dd',
_dav: { accountId: config.id, collectionUrl: book.url, objectUrl: card.url, etag: card.etag, uid }
});
} catch {}
}
}
return { items: result, account: davPublicConfig(config) };
});
registerIpcHandler('dav:save-event', async (_event, input) => {
const store = await readDavStore();
const remote = input?._dav;
const config = activeDavConfig(store, 'caldav', remote?.accountId);
if (!config) return null;
const client = await openDavClient(config, 'caldav');
const calendars = await client.fetchCalendars();
const calendar = remote?.collectionUrl
? calendars.find(item => item.url === remote.collectionUrl)
: calendars[0];
if (!calendar) throw new Error('No writable calendar was found.');
let trustedObject = null;
if (remote?.objectUrl) {
const objects = await client.fetchCalendarObjects({ calendar });
trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects });
}
const uid = remote?.uid || randomUUID();
const data = makeCalendarData({ ...input, _dav: { ...remote, uid } });
if (remote?.objectUrl) {
const response = await client.updateCalendarObject({
calendarObject: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag }
});
return {
accountId: config.id,
collectionUrl: calendar.url,
objectUrl: trustedObject.objectUrl,
etag: response.headers.get('etag') || remote.etag,
uid
};
}
const filename = `${encodeURIComponent(uid)}.ics`;
const response = await client.createCalendarObject({ calendar, iCalString: data.replace(`UID:${uid}`, `UID:${uid}`), filename });
return {
accountId: config.id,
collectionUrl: calendar.url,
objectUrl: new URL(filename, calendar.url.endsWith('/') ? calendar.url : `${calendar.url}/`).href,
etag: response.headers.get('etag'),
uid
};
});
registerIpcHandler('dav:delete-event', async (_event, remote) => {
const store = await readDavStore();
const config = activeDavConfig(store, 'caldav', remote?.accountId);
if (!config || !remote?.objectUrl) return;
const client = await openDavClient(config, 'caldav');
const calendars = await client.fetchCalendars();
const calendar = calendars.find(item => item.url === remote.collectionUrl);
if (!calendar) throw new Error('This DAV collection is not available on the selected server.');
const objects = await client.fetchCalendarObjects({ calendar });
const trustedObject = assertDavObjectReference({ config, remote, collections: calendars, objects });
await client.deleteCalendarObject({
calendarObject: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag }
});
});
registerIpcHandler('dav:save-contact', async (_event, input) => {
const store = await readDavStore();
const remote = input?._dav;
const config = activeDavConfig(store, 'carddav', remote?.accountId);
if (!config) return null;
const client = await openDavClient(config, 'carddav');
const books = await client.fetchAddressBooks();
const book = remote?.collectionUrl
? books.find(item => item.url === remote.collectionUrl)
: books[0];
if (!book) throw new Error('No writable address book was found.');
let trustedObject = null;
if (remote?.objectUrl) {
const cards = await client.fetchVCards({ addressBook: book });
trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards });
}
const uid = remote?.uid || randomUUID();
const data = makeVcard({ ...input, _dav: { ...remote, uid } });
if (remote?.objectUrl) {
const response = await client.updateVCard({
vCard: { url: trustedObject.objectUrl, data, etag: trustedObject.object.etag ?? remote.etag }
});
return {
accountId: config.id,
collectionUrl: book.url,
objectUrl: trustedObject.objectUrl,
etag: response.headers.get('etag') || remote.etag,
uid
};
}
const filename = `${encodeURIComponent(uid)}.vcf`;
const response = await client.createVCard({ addressBook: book, vCardString: data, filename });
return {
accountId: config.id,
collectionUrl: book.url,
objectUrl: new URL(filename, book.url.endsWith('/') ? book.url : `${book.url}/`).href,
etag: response.headers.get('etag'),
uid
};
});
registerIpcHandler('dav:delete-contact', async (_event, remote) => {
const store = await readDavStore();
const config = activeDavConfig(store, 'carddav', remote?.accountId);
if (!config || !remote?.objectUrl) return;
const client = await openDavClient(config, 'carddav');
const books = await client.fetchAddressBooks();
const book = books.find(item => item.url === remote.collectionUrl);
if (!book) throw new Error('This DAV collection is not available on the selected server.');
const cards = await client.fetchVCards({ addressBook: book });
const trustedObject = assertDavObjectReference({ config, remote, collections: books, objects: cards });
await client.deleteVCard({ vCard: { url: trustedObject.objectUrl, etag: trustedObject.object.etag ?? remote.etag } });
});
}
module.exports = { registerDavIpcHandlers };
+426
View File
@@ -0,0 +1,426 @@
const { createAttachmentService } = require('../mail/attachment-service.cjs');
function registerMailIpcHandlers(dependencies) {
const {
registerIpcHandler,
BrowserWindow,
dialog,
shell,
fs,
credentialsPath,
readAccount,
readAccountStore,
saveAccountStore,
updateAccountStore,
saveAccount,
publicAccount,
normalizeAccount,
connectMail,
authorizeOAuthAccount,
listOAuthProviders,
requestBackgroundSync,
CUSTOM_FOLDER_PREFIX,
flushMailOutbox,
fetchMailbox,
cachedMailbox,
listCustomFolders,
imapClient,
validFolderName,
isConnectivityFailure,
randomUUID,
serializeOutgoingAttachments,
normalizeOutgoingAttachments,
sendMailSyncUpdate,
applyMessageAction,
mailOutbox,
pgpMail,
PgpError,
getMailparser,
folderPath,
sendMailNow,
pgpFailure
} = dependencies;
registerIpcHandler('mail:get-account', async () => {
const account = await readAccount();
return account ? publicAccount(account) : null;
});
registerIpcHandler('mail:list-accounts', async () => {
const store = (await readAccountStore()) || { accounts: [], activeId: null };
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
});
registerIpcHandler('mail:list-oauth-providers', async () => listOAuthProviders());
registerIpcHandler('mail:select-account', async (_event, accountId) => {
const account = await updateAccountStore(store => {
const selected = store.accounts.find(item => item.id === accountId);
if (!selected) throw new Error('That mail account is no longer available.');
store.activeId = selected.id;
return selected;
});
requestBackgroundSync();
return publicAccount(account);
});
registerIpcHandler('mail:remove-account', async (_event, accountId) => {
const result = await updateAccountStore(store => {
store.accounts = store.accounts.filter(account => account.id !== accountId);
if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null;
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
});
requestBackgroundSync(accountId);
requestBackgroundSync();
return result;
});
registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
const existing = await readAccount(accountId);
if (!existing) throw new Error('That mail account is no longer available.');
let account = normalizeAccount({
...existing,
...input,
authMethod: input?.authMethod || existing.authMethod || 'password',
password: String(input?.password || '') || existing.password || ''
});
account.id = existing.id;
if (account.authMethod === 'oauth2') {
if (!input?.reauthorizeOAuth && existing.authMethod === 'oauth2' && existing.oauthProvider === account.oauthProvider && existing.oauthRefreshToken) {
account.oauthAccessToken = existing.oauthAccessToken;
account.oauthRefreshToken = existing.oauthRefreshToken;
account.oauthAccessTokenExpiresAt = existing.oauthAccessTokenExpiresAt;
} else {
account = await authorizeOAuthAccount(account);
account.id = existing.id;
}
}
try {
const status = await connectMail(account);
const savedAccount = await updateAccountStore(store => {
const current = store.accounts.find(item => item.id === existing.id);
if (!current) throw new Error('That mail account is no longer available.');
const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost;
store.accounts = store.accounts.map(item => item.id === existing.id
? {
...account,
syncState: endpointChanged ? undefined : current.syncState,
snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []),
ruleLabels: endpointChanged ? {} : (current.ruleLabels || {})
}
: item);
return store.accounts.find(item => item.id === existing.id);
});
requestBackgroundSync(existing.id);
return { ...publicAccount(savedAccount), ...status };
} catch (error) {
throw new Error(`Could not update the mailbox: ${error.message}`);
}
});
registerIpcHandler('mail:connect', async (_event, input) => {
let account = normalizeAccount(input);
try {
if (account.authMethod === 'oauth2') account = await authorizeOAuthAccount(account);
const status = await connectMail(account);
const saved = await saveAccount(account);
requestBackgroundSync(saved.id);
return { ok: true, ...publicAccount(saved), ...status };
} catch (error) {
throw new Error(`Could not connect to the mailbox: ${error.message}`);
}
});
registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before syncing.');
const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']);
const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder;
const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX)
? selectedFolder : 'Inbox';
const { folder: _filterFolder, ...criteria } = filters;
try {
await flushMailOutbox(account);
return await fetchMailbox(account, folder, offset, 20, criteria);
} catch (error) {
if (!isConnectivityFailure(error)) throw error;
const cached = cachedMailbox(account, folder, offset, 20, criteria);
if (!cached.total) throw error;
return cached;
}
});
registerIpcHandler('mail:list-folders', async () => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before listing folders.');
const client = await imapClient(account);
try {
await client.connect();
return { folders: await listCustomFolders(client) };
} catch (error) {
if (isConnectivityFailure(error)) return { folders: [], offline: true };
throw error;
} finally {
if (client.usable) await client.logout().catch(() => {});
}
});
registerIpcHandler('mail:create-folder', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before creating folders.');
const name = validFolderName(input?.name);
const client = await imapClient(account);
try {
await client.connect();
const existing = await client.list();
if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) {
throw new Error('A folder with that name already exists.');
}
const created = await client.mailboxCreate(name);
await client.mailboxSubscribe(created.path).catch(() => {});
return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) };
} catch (error) {
if (error.message === 'A folder with that name already exists.') throw error;
throw new Error(`Could not create the folder: ${error.message}`);
} finally {
if (client.usable) await client.logout().catch(() => {});
}
});
registerIpcHandler('mail:list-drafts', async () => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before opening drafts.');
return { drafts: account.drafts || [], offline: true };
});
registerIpcHandler('mail:save-draft', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before saving drafts.');
const draft = {
id: String(input?.id || randomUUID()),
to: String(input?.to || '').slice(0, 4000),
cc: String(input?.cc || '').slice(0, 4000),
subject: String(input?.subject || '').slice(0, 998),
text: String(input?.text || '').slice(0, 500000),
attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)),
updatedAt: Date.now()
};
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
const drafts = saved.drafts || [];
saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500);
});
return draft;
});
registerIpcHandler('mail:delete-draft', async (_event, id) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before deleting drafts.');
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id);
});
return { ok: true };
});
registerIpcHandler('mail:set-snooze', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before setting a reminder.');
const uid = Number(input?.uid);
const folder = String(input?.sourceFolder || input?.folder || 'Inbox');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.');
const dueAt = input?.dueAt == null ? null : Number(input.dueAt);
if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) {
throw new Error('Choose a reminder time in the future.');
}
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
const snoozes = saved.snoozedMessages || [];
const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder));
if (dueAt != null) {
remaining.push({
uid,
folder,
dueAt,
subject: String(input.subject || '').slice(0, 200)
});
}
saved.snoozedMessages = remaining;
});
sendMailSyncUpdate({
accountId: account.id,
foldersChanged: ['Snoozed', folder]
});
return { ok: true, snoozed: dueAt != null };
});
registerIpcHandler('mail:update-message', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before changing messages.');
try {
return await applyMessageAction(account, input);
} catch (error) {
if (!isConnectivityFailure(error)) throw error;
return mailOutbox.queueMessageAction(account, input);
}
});
// Encrypted messages keep their attachments inside the encrypted payload.
async function parseForAttachments(source) {
const { simpleParser } = await getMailparser();
const parsed = await simpleParser(source);
const kind = pgpMail.detect(parsed);
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed;
try {
return (await pgpMail.decrypt(parsed)).parsed;
} catch (error) {
if (error instanceof PgpError) throw new Error(error.code === 'PASSPHRASE_REQUIRED' ? 'Open the message and unlock it before using its attachments.' : error.message);
throw error;
}
}
const attachmentService = createAttachmentService({ imapClient, folderPath, parseForAttachments });
registerIpcHandler('mail:save-attachment', async (event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before downloading attachments.');
const parent = BrowserWindow.fromWebContents(event.sender);
return attachmentService.saveAttachment(account, input, options => dialog.showSaveDialog(parent, options));
});
registerIpcHandler('mail:preview-attachment', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before previewing attachments.');
return attachmentService.previewAttachment(account, input);
});
registerIpcHandler('mail:open-external', async (event, rawUrl) => {
let target;
try {
target = new URL(String(rawUrl || ''));
} catch {
throw new Error('This link is not a valid web address.');
}
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
throw new Error('Only standard web links can be opened from mail.');
}
const parent = BrowserWindow.fromWebContents(event.sender);
const confirmation = await dialog.showMessageBox(parent, {
type: 'warning',
title: 'Open external link?',
message: 'Email links can lead to fake sign-in pages or harmful content.',
detail: `Check the full address before continuing:\n${target.href}`,
buttons: ['Cancel', 'Open link'],
defaultId: 0,
cancelId: 0,
noLink: true
});
if (confirmation.response !== 1) return { opened: false };
await shell.openExternal(target.href);
return { opened: true };
});
registerIpcHandler('mail:sync-inbox', async () => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before syncing.');
return fetchMailbox(account, 'Inbox');
});
registerIpcHandler('mail:send', async (event, message) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before sending.');
const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null;
const queuedMessage = {
to: message.to,
cc: message.cc,
subject: message.subject,
text: message.text,
displayName: message.displayName,
messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`,
attachments: message.attachments
};
const attachments = normalizeOutgoingAttachments(message?.attachments);
queuedMessage.attachments = serializeOutgoingAttachments(attachments);
delete queuedMessage.pgp;
if (!pgpOptions?.encrypt) {
const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean);
const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email });
if (status.recipients.length && !status.missing.length) {
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
type: 'warning',
buttons: ['Cancel', 'Send anyway'],
defaultId: 0,
cancelId: 0,
title: 'Send without encryption?',
message: 'Public keys are available for all recipients.',
detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.',
noLink: true
});
if (response !== 1) throw new Error('Plaintext send cancelled.');
}
}
if (pgpOptions) {
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
const signature = String(account.signature || '').slice(0, 5000);
const body = String(queuedMessage.text || '').slice(0, 500000);
const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
try {
const built = await pgpMail.build({
from: { name: fromName, address: account.email },
to: queuedMessage.to,
cc: queuedMessage.cc,
subject: String(queuedMessage.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: queuedMessage.messageId,
encrypt: Boolean(pgpOptions.encrypt),
sign: Boolean(pgpOptions.sign),
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null,
attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }))
});
queuedMessage.rawBase64 = built.raw.toString('base64');
queuedMessage.envelope = built.envelope;
queuedMessage.text = '';
queuedMessage.attachments = [];
} catch (error) {
if (error instanceof PgpError) return pgpFailure(error);
throw error;
}
}
try {
return await sendMailNow(account, queuedMessage);
} catch (error) {
if (!isConnectivityFailure(error)) throw error;
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
saved.mailOutbox = saved.mailOutbox || [];
saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() });
});
return { ok: true, queued: true };
}
});
registerIpcHandler('mail:disconnect', async (_event, accountId) => {
const store = await readAccountStore();
if (!store) return { accounts: [], activeId: null };
if (accountId) {
store.accounts = store.accounts.filter(account => account.id !== accountId);
} else {
store.accounts = [];
}
if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true });
else {
if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id;
await saveAccountStore(store);
}
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
});
}
module.exports = { registerMailIpcHandlers };
+303
View File
@@ -0,0 +1,303 @@
function pgpFailure(error) {
return {
failed: true,
code: error.code,
message: error.message,
fingerprint: error.details?.fingerprint || null,
email: error.details?.email || null,
missing: error.details?.missing || []
};
}
function registerPgpIpcHandlers({
registerIpcHandler,
BrowserWindow,
dialog,
fs,
getOpenPGP,
openpgp,
pgpKeys,
pgpCache,
pgpMail,
PgpError,
pgpKeyServers,
listServers,
MAX_CUSTOM_SERVERS,
normalizeCustomServer,
randomUUID,
readAccount,
imapClient,
folderPath,
getMailparser,
extractMailContent
}) {
async function fetchMessageSource(account, folder, uid) {
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
const client = await imapClient(account);
try {
await client.connect();
const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) throw new Error('That mail folder could not be found.');
const lock = await client.getMailboxLock(mailboxPath);
try {
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
if (!item?.source) throw new Error('The message is no longer available.');
return item.source;
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
async function saveKeyFile(event, defaultName, content) {
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: defaultName });
if (result.canceled || !result.filePath) return { canceled: true };
await fs.writeFile(result.filePath, content, { mode: 0o600 });
return { saved: true };
}
const pgpFingerprint = value => {
const fingerprint = String(value || '').toUpperCase();
if (!/^[0-9A-F]{40,64}$/.test(fingerprint)) throw new Error('That key could not be identified.');
return fingerprint;
};
registerIpcHandler('pgp:list', () => pgpKeys.list());
registerIpcHandler('pgp:generate', (_event, input) => pgpKeys.generate({
name: input?.name, email: input?.email, passphrase: input?.passphrase, accountId: input?.accountId || null
}));
registerIpcHandler('pgp:import', async (event, input) => {
let armoredKey = input?.armoredKey;
if (!armoredKey) {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
properties: ['openFile'], filters: [{ name: 'OpenPGP keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
});
if (result.canceled || !result.filePaths[0]) return { canceled: true };
const stat = await fs.stat(result.filePaths[0]);
if (stat.size > 200000) throw new Error('That key file is too large.');
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
}
return { key: await pgpKeys.import({ armoredKey, passphrase: input?.passphrase, accountId: input?.accountId || null }) };
});
registerIpcHandler('pgp:export-public', async (event, fingerprint) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-public-${id.slice(-16)}.asc`, await pgpKeys.exportPublic(id));
});
registerIpcHandler('pgp:export-private', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-private-${id.slice(-16)}.asc`, await pgpKeys.exportPrivate(id, passphrase));
});
registerIpcHandler('pgp:change-passphrase', async (_event, input) => {
const id = pgpFingerprint(input?.fingerprint);
const result = await pgpKeys.changePassphrase(id, input?.currentPassphrase, input?.newPassphrase);
pgpCache.clear(id);
return result;
});
registerIpcHandler('pgp:export-revocation', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase));
});
registerIpcHandler('pgp:delete', async (_event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
const result = await pgpKeys.remove(id, passphrase);
pgpCache.clear(id);
return result;
});
registerIpcHandler('pgp:decrypt-message', async (_event, input) => {
const account = await readAccount();
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 { simpleParser } = await getMailparser();
const outer = await simpleParser(source);
try {
const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null });
const content = extractMailContent(result.parsed);
return {
ok: true,
body: content.body,
html: content.html,
links: content.links,
attachments: content.attachments,
attachment: content.attachment,
size: content.size,
signatures: result.signatures,
attachedKeys: result.attachedKeys.map(key => ({ fingerprint: key.fingerprint, emails: key.emails, armoredKey: key.armoredKey }))
};
} catch (error) {
if (error instanceof PgpError) return pgpFailure(error);
throw error;
}
});
registerIpcHandler('pgp:check-send', async (_event, input) => {
const account = await readAccount();
return pgpMail.recipientStatus([input?.to, input?.cc], { sign: Boolean(input?.sign), from: account?.email || '' });
});
registerIpcHandler('pgp:contacts', () => pgpKeys.listContacts());
registerIpcHandler('pgp:add-contact', async (event, input) => {
let armoredKey = typeof input?.armoredKey === 'string' ? input.armoredKey : '';
if (!armoredKey) {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
properties: ['openFile'], filters: [{ name: 'OpenPGP public keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
});
if (result.canceled || !result.filePaths[0]) return { canceled: true };
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');
}
const key = await (getOpenPGP ? (await getOpenPGP()).readKey({ armoredKey }) : openpgp.readKey({ armoredKey })).catch(() => {
throw new Error('That is not a valid OpenPGP public key.');
});
const fingerprint = key.getFingerprint().toUpperCase();
const emails = [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
const existing = await pgpKeys.listContacts();
const overlaps = existing.filter(item => (item.emails || []).some(email => emails.includes(String(email).toLowerCase())));
if (overlaps.length) {
const detail = overlaps.map(item => {
const name = item.name || 'Unknown contact';
const addresses = (item.emails || []).join(', ') || 'no address';
const fp = String(item.fingerprint || '').replace(/(.{4})/g, '$1 ').trim();
return `${name} (${addresses})\nFingerprint: ${fp}`;
}).join('\n\n');
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
type: 'warning',
buttons: ['Cancel', 'Replace key'],
defaultId: 0,
cancelId: 0,
title: 'Confirm key replacement',
message: 'A different public key already exists for this email address.',
detail: `New key:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nExisting key(s):\n${detail}\n\nOnly continue if you verified the new fingerprint with the owner.`,
noLink: true
});
if (response !== 1) throw new Error('Key replacement cancelled.');
}
const source = ['message', 'keyserver', 'paste'].includes(input?.source) ? input.source : 'import';
return pgpKeys.addContact({ armoredKey, source });
});
registerIpcHandler('pgp:set-trust', async (event, fingerprint, trust) => {
const id = pgpFingerprint(fingerprint);
const level = String(trust);
// Raising trust changes which key outgoing mail is encrypted to, so confirm it here, outside the renderer.
if (level !== 'unknown') {
const contact = (await pgpKeys.listContacts()).find(item => item.fingerprint === id);
if (!contact) throw new Error('That contact key was not found.');
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
type: 'question',
buttons: ['Cancel', `Mark as ${level}`],
defaultId: 0,
cancelId: 0,
title: 'Confirm key trust',
message: `Mark this key as ${level}?`,
detail: `${contact.name || ''} ${(contact.emails || []).join(', ')}\nFingerprint:\n${id.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly continue if you checked this fingerprint with the owner.`
});
if (response !== 1) throw new Error('Trust change cancelled.');
}
return pgpKeys.setTrust(id, level);
});
registerIpcHandler('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
registerIpcHandler('pgp:export-contact', async (event, fingerprint) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-contact-${id.slice(-16)}.asc`, await pgpKeys.exportContact(id));
});
registerIpcHandler('pgp:get-settings', () => pgpKeys.getSettings());
registerIpcHandler('pgp:set-settings', async (_event, input) => {
const settings = await pgpKeys.setSettings({ cacheMinutes: input?.cacheMinutes });
pgpCache.clear();
return settings;
});
registerIpcHandler('pgp:key-servers', async () => {
const settings = await pgpKeys.getSettings();
return listServers(settings.customKeyServers, settings.enabledKeyServers);
});
registerIpcHandler('pgp:set-key-server-enabled', async (_event, input) => {
if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
const settings = await pgpKeys.getSettings();
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
const serverId = String(input?.serverId || '');
if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.');
const enabled = new Set(settings.enabledKeyServers);
if (input.enabled) enabled.add(serverId);
else enabled.delete(serverId);
await pgpKeys.setSettings({
cacheMinutes: settings.cacheMinutes,
customKeyServers: settings.customKeyServers,
enabledKeyServers: [...enabled]
});
return { serverId, enabled: input.enabled };
});
registerIpcHandler('pgp:add-key-server', async (event, input) => {
const candidate = normalizeCustomServer(input);
const settings = await pgpKeys.getSettings();
const customServers = settings.customKeyServers.map(normalizeCustomServer);
if (customServers.length >= MAX_CUSTOM_SERVERS) throw new Error(`You can configure up to ${MAX_CUSTOM_SERVERS} custom key servers.`);
if (customServers.some(server => server.url === candidate.url && server.protocol === candidate.protocol)) {
throw new Error('That key server is already configured.');
}
const url = new URL(candidate.url);
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
type: 'warning',
buttons: ['Cancel', 'Add server'],
defaultId: 0,
cancelId: 0,
title: 'Add custom key server?',
message: `Allow ep-mail to contact ${url.host} for OpenPGP keys?`,
detail: `Protocol: ${candidate.protocol.toUpperCase()}\nEndpoint: ${candidate.url}\nThe server may learn which email addresses you search for. Only add a server you trust.`,
noLink: true
});
if (response !== 1) return { canceled: true };
candidate.id = randomUUID();
const updated = await pgpKeys.setSettings({
cacheMinutes: settings.cacheMinutes,
customKeyServers: [...customServers, candidate]
});
return { server: updated.customKeyServers[updated.customKeyServers.length - 1] };
});
registerIpcHandler('pgp:remove-key-server', async (_event, serverId) => {
const id = String(serverId || '');
const settings = await pgpKeys.getSettings();
const customServers = settings.customKeyServers.filter(server => server.id !== id);
if (customServers.length === settings.customKeyServers.length) throw new Error('That custom key server was not found.');
await pgpKeys.setSettings({
cacheMinutes: settings.cacheMinutes,
customKeyServers,
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id)
});
return { removed: true };
});
registerIpcHandler('pgp:find-key', async (_event, input) => {
const settings = await pgpKeys.getSettings();
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
return pgpKeyServers.lookupEnabled(servers, input?.email);
});
registerIpcHandler('pgp:publish-key', async (event, input) => {
const fingerprint = pgpFingerprint(input?.fingerprint);
const settings = await pgpKeys.getSettings();
const server = listServers(settings.customKeyServers, settings.enabledKeyServers).find(item => item.id === String(input?.serverId || ''));
if (!server) throw new Error('Choose a configured key server.');
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
if (!entry.email) throw new Error('This key has no email address to publish.');
const armoredKey = await pgpKeys.exportPublic(fingerprint);
const publicKey = await (getOpenPGP ? (await getOpenPGP()).readKey({ armoredKey }) : openpgp.readKey({ armoredKey }));
const emails = [...new Set(publicKey.getUserIDs()
.map(userId => (/<([^>]+)>/.exec(userId)?.[1] || (userId.includes('@') ? userId : '')).trim().toLowerCase())
.filter(Boolean))];
if (!emails.includes(entry.email.toLowerCase())) throw new Error('The selected key no longer matches its stored email address.');
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
type: 'warning',
buttons: ['Cancel', 'Publish public key'],
defaultId: 0,
cancelId: 0,
title: 'Publish public key?',
message: `Publish the public key for ${emails.join(', ')} to ${server.name}?`,
detail: `Fingerprint:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly the public key will be sent. This exposes the email address(es) in the key to the server, which may retain them. The server may send a verification email before the key becomes searchable.`,
noLink: true
});
if (response !== 1) return { canceled: true };
return pgpKeyServers.publish(server, entry.email, armoredKey, fingerprint);
});
registerIpcHandler('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
}
module.exports = { pgpFailure, registerPgpIpcHandlers };
+24
View File
@@ -0,0 +1,24 @@
function extractMailContent(parsed) {
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
const body = bodyText
? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40)
: ['This message has no plain-text body.'];
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
.map(match => (match[1] || match[2] || match[3] || '').replace(/&amp;/gi, '&').replace(/&#x2f;/gi, '/'))
.filter(Boolean)
.slice(0, 30);
const files = (parsed.attachments || [])
.filter(file => !/^application\/pgp-(signature|encrypted)/i.test(file.contentType || ''));
return {
bodyText,
body,
html: html.slice(0, 100000),
links,
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: files[0]?.filename || null,
size: files[0]?.size ? `${(files[0].size / 1048576).toFixed(1)} MB` : ''
};
}
module.exports = { extractMailContent };
+124
View File
@@ -0,0 +1,124 @@
const { randomUUID } = require('node:crypto');
const CUSTOM_FOLDER_PREFIX = 'Folder:';
const RESERVED_FOLDER_NAMES = new Set(['inbox', 'sent', 'drafts', 'archive', 'trash', 'starred', 'snoozed', 'junk', 'spam']);
function normalizeAccount(input, { createId = randomUUID } = {}) {
const email = String(input?.email || '').trim();
const authMethod = input?.authMethod === undefined ? 'password' : String(input.authMethod);
if (!['password', 'oauth2'].includes(authMethod)) throw new Error('Choose a supported sign-in method.');
const oauthProvider = authMethod === 'oauth2' ? String(input?.oauthProvider || '') : '';
if (authMethod === 'oauth2' && !['google', 'microsoft'].includes(oauthProvider)) {
throw new Error('Choose Google or Microsoft OAuth2 sign-in.');
}
const providerDefaults = oauthProvider === 'google'
? { imapHost: 'imap.gmail.com', smtpHost: 'smtp.gmail.com', imapPort: 993, smtpPort: 587, imapSecure: true }
: oauthProvider === 'microsoft'
? { imapHost: 'outlook.office365.com', smtpHost: 'smtp.office365.com', imapPort: 993, smtpPort: 587, imapSecure: true }
: { imapHost: '', smtpHost: '', imapPort: 143, smtpPort: 587, imapSecure: false };
const password = authMethod === 'password' ? String(input?.password || '') : '';
const imapHost = String(oauthProvider ? providerDefaults.imapHost : input?.imapHost || providerDefaults.imapHost).trim();
const smtpHost = String(oauthProvider ? providerDefaults.smtpHost : input?.smtpHost || providerDefaults.smtpHost).trim();
const displayName = String(input?.displayName || '').trim().slice(0, 80);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !imapHost || !smtpHost || (authMethod === 'password' && !password)) {
throw new Error(authMethod === 'password'
? 'Enter a valid email, password, and both mail server names.'
: 'Enter a valid email and supported OAuth mail servers.');
}
if (!displayName) throw new Error('Enter a display name for this mail account.');
const imapPort = Number(oauthProvider ? providerDefaults.imapPort : input?.imapPort ?? providerDefaults.imapPort);
const smtpPort = Number(oauthProvider ? providerDefaults.smtpPort : input?.smtpPort ?? providerDefaults.smtpPort);
if (![imapPort, smtpPort].every(port => Number.isInteger(port) && port >= 1 && port <= 65535)) {
throw new Error('Enter valid IMAP and SMTP ports.');
}
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
throw new Error('Choose a supported mailbox sync interval.');
}
const inputRules = Array.isArray(input?.rules) ? input.rules : [];
if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.');
const rules = inputRules.map((rule, index) => {
const senderContains = String(rule?.senderContains || '').trim().slice(0, 200);
const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200);
const action = String(rule?.action || '');
const value = String(rule?.value || '').trim().slice(0, 200);
if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) {
throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`);
}
if ((action === 'move' || action === 'label') && !value) {
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
}
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value) && !value.startsWith(CUSTOM_FOLDER_PREFIX)) {
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders.`);
}
return { id: String(rule.id || createId()), senderContains, subjectContains, action, value };
});
return {
email, password, authMethod, oauthProvider: oauthProvider || null,
displayName, imapHost, smtpHost, imapPort, smtpPort,
imapSecure: oauthProvider ? providerDefaults.imapSecure : input?.imapSecure === undefined ? providerDefaults.imapSecure : Boolean(input.imapSecure),
smtpSecure: oauthProvider ? false : input?.smtpSecure === undefined ? false : Boolean(input.smtpSecure),
signature: String(input?.signature || '').slice(0, 5000),
notificationsEnabled: input?.notificationsEnabled !== false,
syncIntervalMinutes,
rules
};
}
function publicAccount(account) {
return {
id: account.id,
email: account.email,
displayName: account.displayName || '',
authMethod: account.authMethod === 'oauth2' ? 'oauth2' : 'password',
oauthProvider: account.authMethod === 'oauth2' ? account.oauthProvider || null : null,
imapHost: account.imapHost,
smtpHost: account.smtpHost,
imapPort: Number(account.imapPort) || (account.authMethod === 'oauth2' ? 993 : 143),
smtpPort: Number(account.smtpPort) || 587,
imapSecure: Boolean(account.imapSecure),
smtpSecure: Boolean(account.smtpSecure),
signature: account.signature || '',
notificationsEnabled: account.notificationsEnabled !== false,
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
rules: Array.isArray(account.rules) ? account.rules : []
};
}
function isReservedFolderName(name) {
return RESERVED_FOLDER_NAMES.has(String(name).toLowerCase());
}
function validFolderName(input) {
const name = String(input || '').trim();
if (!name || name.length > 100) throw new Error('Enter a folder name of up to 100 characters.');
if (/[\\/.*%#&\u0000-\u001f]/.test(name)) throw new Error('Folder names cannot contain / \\ . * % # & or control characters.');
if (isReservedFolderName(name)) throw new Error('That folder name is reserved.');
return name;
}
function filterMailboxMessages(messages, filters = {}) {
const text = String(filters.query || '').trim().toLowerCase();
const sender = String(filters.sender || '').trim().toLowerCase();
const subject = String(filters.subject || '').trim().toLowerCase();
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
return messages.filter(message => {
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
const date = Number(message.timestamp || 0);
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
(!after || date >= after) && (!before || date <= before) &&
(!filters.hasAttachments || (message.attachments || []).length > 0);
});
}
module.exports = {
CUSTOM_FOLDER_PREFIX,
filterMailboxMessages,
isReservedFolderName,
normalizeAccount,
publicAccount,
validFolderName
};
+53
View File
@@ -0,0 +1,53 @@
function createMessageActionService({ imapClient, folderPath, findSpecialMailbox, updateAccountStore }) {
async function applyMessageAction(account, input) {
const uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox');
const action = String(input?.action || '');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
const client = await imapClient(account);
try {
await client.connect();
const sourcePath = await folderPath(client, folder);
if (!sourcePath) throw new Error('That mail folder could not be found.');
const lock = await client.getMailboxLock(sourcePath);
try {
if (action === 'star') {
if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true });
} else if (action === 'unread') {
if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true });
else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true });
} else {
const target = action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: action === 'delete'
? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
: 'INBOX';
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
if (action === 'delete') await client.messageDelete(uid, { uid: true });
}
else await client.messageMove(uid, target, { uid: true });
}
} finally {
lock.release();
}
if (action === 'archive' || action === 'delete' || action === 'inbox') {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) {
saved.snoozedMessages = (saved.snoozedMessages || [])
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
}
});
}
return { ok: true };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
return { applyMessageAction };
}
module.exports = { createMessageActionService };
+61
View File
@@ -0,0 +1,61 @@
const fs = require('node:fs/promises');
function createAttachmentService({ imapClient, folderPath, parseForAttachments, writeFile = fs.writeFile }) {
async function loadAttachment(account, input, selectAttachment) {
const uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox');
const filename = String(input?.filename || 'attachment');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
const client = await imapClient(account);
try {
await client.connect();
const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) throw new Error('That mail folder could not be found.');
const lock = await client.getMailboxLock(mailboxPath);
try {
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
if (!item?.source) throw new Error('The message is no longer available.');
const parsed = await parseForAttachments(item.source);
const attachment = selectAttachment(parsed.attachments || [], filename);
if (!attachment) throw new Error('No attachment was found in this message.');
return { attachment, filename };
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
async function saveAttachment(account, input, showSaveDialog) {
const { attachment, filename } = await loadAttachment(account, input, (attachments, selectedName) =>
attachments.find(file => (file.filename || 'attachment') === selectedName) || attachments[0]);
const safeFilename = filename.replace(/[\\/:*?"<>|]/g, '_');
const result = await showSaveDialog({
defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_')
});
if (result.canceled || !result.filePath) return { canceled: true };
await writeFile(result.filePath, attachment.content);
return { saved: true };
}
async function previewAttachment(account, input) {
const { attachment } = await loadAttachment(account, input, (attachments, filename) =>
attachments.find(file => (file.filename || 'attachment') === filename));
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
const size = attachment.content.length;
if (/^image\/(png|jpe?g|gif|webp|bmp|svg\+xml)$/.test(mimeType)) {
if (size > 5 * 1048576) return { kind: 'none', reason: 'This image is too large to preview. Download it instead.' };
return { kind: 'image', dataUrl: `data:${mimeType};base64,${attachment.content.toString('base64')}` };
}
if (mimeType.startsWith('text/') || ['application/json', 'application/xml'].includes(mimeType)) {
return { kind: 'text', text: attachment.content.subarray(0, 100000).toString('utf8'), truncated: size > 100000 };
}
return { kind: 'none', reason: 'No preview is available for this file type. Download it to open it.' };
}
return { previewAttachment, saveAttachment };
}
module.exports = { createAttachmentService };
+59
View File
@@ -0,0 +1,59 @@
function createMailConnections({ ImapFlow, createTransport, getImapFlow, getNodemailer, oauthTokenManager }) {
let ImapFlowModule = ImapFlow;
let nodemailerModule = createTransport ? { createTransport } : null;
async function imapClient(account, options = {}) {
if (!ImapFlowModule) {
const module = await getImapFlow();
ImapFlowModule = module.ImapFlow || module.default || module;
}
const isOAuth = account.authMethod === 'oauth2';
const auth = isOAuth
? { user: account.email, accessToken: await oauthTokenManager.getAccessToken(account) }
: { user: account.email, pass: account.password };
return new ImapFlowModule({
host: account.imapHost,
port: account.imapPort,
secure: Boolean(account.imapSecure),
doSTARTTLS: !account.imapSecure,
auth,
tls: { rejectUnauthorized: true },
logger: false,
connectionTimeout: 15000,
greetingTimeout: 10000,
socketTimeout: 20000,
...options
});
}
async function smtpTransport(account) {
if (!nodemailerModule) {
nodemailerModule = await getNodemailer();
}
const isOAuth = account.authMethod === 'oauth2';
const auth = isOAuth
? {
type: 'OAuth2',
user: account.email,
accessToken: await oauthTokenManager.getAccessToken(account),
expires: account.oauthAccessTokenExpiresAt
}
: { user: account.email, pass: account.password };
const secure = Boolean(account.smtpSecure);
return nodemailerModule.createTransport({
host: account.smtpHost,
port: account.smtpPort,
secure,
requireTLS: !secure,
auth,
tls: { rejectUnauthorized: true, servername: account.smtpHost },
connectionTimeout: 15000,
greetingTimeout: 10000,
socketTimeout: 20000
});
}
return Object.freeze({ imapClient, smtpTransport });
}
module.exports = { createMailConnections };
+10
View File
@@ -0,0 +1,10 @@
function isConnectivityFailure(error) {
const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']);
for (let current = error; current; current = current.cause) {
if (networkCodes.has(current.code)) return true;
if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true;
}
return false;
}
module.exports = { isConnectivityFailure };
+47
View File
@@ -0,0 +1,47 @@
function createFolderService({ customFolderPrefix = 'Folder:', isReservedFolderName = () => false } = {}) {
async function findSpecialMailbox(client, specialUse, fallbackNames, createName = null) {
const mailboxes = await client.list();
const match = mailboxes.find(mailbox => mailbox.specialUse?.toLowerCase() === specialUse.toLowerCase()) ||
mailboxes.find(mailbox => fallbackNames.includes(mailbox.path.toLowerCase().split(/[./]/).pop()));
if (match) return match.path;
if (!createName) return null;
return (await client.mailboxCreate(createName)).path;
}
async function findSentMailbox(client, createIfMissing = false) {
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
}
async function listCustomFolders(client) {
return (await client.list())
.filter(mailbox => !mailbox.flags?.has('\\Noselect') && !mailbox.specialUse &&
mailbox.path.toUpperCase() !== 'INBOX' &&
!isReservedFolderName(mailbox.path.toLowerCase().split(/[./]/).pop()) &&
!['sent items', 'sent mail', 'sent messages', 'archives', 'all mail', 'deleted items', 'deleted messages']
.includes(mailbox.path.toLowerCase().split(/[./]/).pop()))
.map(mailbox => ({ name: mailbox.name, path: mailbox.path, id: customFolderPrefix + mailbox.path }))
.sort((a, b) => a.path.localeCompare(b.path));
}
async function folderPath(client, folder, createIfMissing = false) {
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
const definitions = {
Sent: ['\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], 'Sent'],
Archive: ['\\Archive', ['archive', 'archives', 'all mail'], 'Archive'],
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
};
const definition = definitions[folder];
if (!definition && typeof folder === 'string' && folder.startsWith(customFolderPrefix)) {
const path = folder.slice(customFolderPrefix.length);
const match = (await client.list()).find(mailbox => mailbox.path === path);
if (!match || match.flags?.has('\\Noselect')) throw new Error('This folder is not available on the mail server.');
return match.path;
}
if (!definition) throw new Error('This folder is not available on the mail server.');
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
}
return { findSpecialMailbox, findSentMailbox, folderPath, listCustomFolders };
}
module.exports = { createFolderService };
+107
View File
@@ -0,0 +1,107 @@
function createIdleWatcherManager({
readAccountStore,
readAccount,
imapClient,
backgroundSyncGenerations,
concurrency = 2,
logError = (...args) => console.error(...args),
wait = delay => new Promise(resolve => {
const timer = setTimeout(resolve, delay);
timer.unref();
})
}) {
const idleWatchers = new Map();
let requestSync = () => {};
function setRequestBackgroundSync(callback) {
requestSync = callback;
}
function stopIdleWatcher(accountId) {
const watcher = idleWatchers.get(accountId);
if (!watcher) return;
watcher.stopped = true;
watcher.client?.close();
idleWatchers.delete(accountId);
}
function startIdleWatcher(account) {
if (idleWatchers.has(account.id)) return;
const watcher = {
generation: backgroundSyncGenerations.get(account.id) || 0,
stopped: false,
client: null
};
idleWatchers.set(account.id, watcher);
void runIdleWatcher(account.id, watcher).catch(error => {
logError(`IMAP IDLE watcher failed for ${account.email}:`, error);
});
}
async function runIdleWatcher(accountId, watcher) {
let failures = 0;
while (!watcher.stopped && backgroundSyncGenerations.get(accountId) === watcher.generation) {
let client;
try {
const account = await readAccount(accountId);
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
client = await imapClient(account, {
autoIdleDelay: 10_000,
maxIdleTime: 25 * 60 * 1000,
socketTimeout: 30 * 60 * 1000
});
watcher.client = client;
let signalDisconnected;
const disconnected = new Promise(resolve => { signalDisconnected = resolve; });
client.on('exists', event => {
if (event.path.toLowerCase() === 'inbox' && event.count > event.prevCount) requestSync();
});
client.on('flags', event => {
if (event.path.toLowerCase() === 'inbox') requestSync();
});
client.on('error', error => {
if (!watcher.stopped) logError(`IMAP IDLE connection failed for ${account.email}:`, error);
signalDisconnected();
});
client.once('close', signalDisconnected);
await client.connect();
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
await client.mailboxOpen('INBOX', { readOnly: true });
const connectedAt = Date.now();
await disconnected;
if (Date.now() - connectedAt > 60_000) failures = 0;
} catch (error) {
if (!watcher.stopped) logError(`IMAP IDLE watcher disconnected for ${accountId}:`, error);
} finally {
if (watcher.client === client) watcher.client = null;
if (client?.usable) await client.logout().catch(() => client.close());
else client?.close();
}
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
const retryDelay = Math.min(5 * 60 * 1000, 15_000 * (2 ** Math.min(failures, 5)));
failures += 1;
await wait(retryDelay);
}
}
async function reconcileIdleWatchers() {
const store = (await readAccountStore()) || { accounts: [] };
const desiredAccounts = store.accounts.slice(0, concurrency);
const desiredIds = new Set(desiredAccounts.map(account => account.id));
for (const [accountId, watcher] of idleWatchers) {
if (!desiredIds.has(accountId) || watcher.generation !== (backgroundSyncGenerations.get(accountId) || 0)) {
stopIdleWatcher(accountId);
}
}
for (const account of desiredAccounts) startIdleWatcher(account);
}
function stopAll() {
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
}
return { reconcileIdleWatchers, setRequestBackgroundSync, stopAll, stopIdleWatcher };
}
module.exports = { createIdleWatcherManager };
+34
View File
@@ -0,0 +1,34 @@
function createOAuthTokenManager({ oauth2Service, persistTokens, now = Date.now }) {
const refreshOperations = new Map();
async function getAccessToken(account) {
if (account?.authMethod !== 'oauth2') throw new Error('This account does not use OAuth2.');
if (account.oauthAccessToken && Number(account.oauthAccessTokenExpiresAt) > now() + 60_000) {
return account.oauthAccessToken;
}
if (!account.oauthRefreshToken) {
throw new Error('Reconnect this OAuth2 account to continue.');
}
const key = String(account.id || `${account.oauthProvider}:${account.email}`);
let pending = refreshOperations.get(key);
if (!pending) {
pending = (async () => {
const tokens = await oauth2Service.refresh(account.oauthProvider, account.oauthRefreshToken);
await persistTokens(account.id, tokens);
return tokens;
})();
refreshOperations.set(key, pending);
pending.finally(() => {
if (refreshOperations.get(key) === pending) refreshOperations.delete(key);
}).catch(() => {});
}
const tokens = await pending;
Object.assign(account, tokens);
return tokens.oauthAccessToken;
}
return Object.freeze({ getAccessToken });
}
module.exports = { createOAuthTokenManager };
+212
View File
@@ -0,0 +1,212 @@
const { createHash, randomBytes, timingSafeEqual } = require('node:crypto');
const http = require('node:http');
const GOOGLE_SCOPE = 'https://mail.google.com/';
const MICROSOFT_SCOPES = [
'offline_access',
'https://outlook.office.com/IMAP.AccessAsUser.All',
'https://outlook.office.com/SMTP.Send'
].join(' ');
function loadOAuthProviderConfig(environment = process.env) {
const googleClientId = String(environment.EP_MAIL_GOOGLE_OAUTH_CLIENT_ID || '').trim();
const microsoftClientId = String(environment.EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID || '').trim();
const microsoftTenant = String(environment.EP_MAIL_MICROSOFT_OAUTH_TENANT_ID || 'common').trim();
if (microsoftTenant && !/^(?:common|organizations|consumers|[a-f0-9-]{36})$/i.test(microsoftTenant)) {
throw new Error('The Microsoft OAuth tenant ID is invalid.');
}
return {
...(googleClientId ? {
google: {
clientId: googleClientId,
clientSecret: String(environment.EP_MAIL_GOOGLE_OAUTH_CLIENT_SECRET || '').trim(),
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/v2/auth',
tokenEndpoint: 'https://oauth2.googleapis.com/token',
scope: GOOGLE_SCOPE,
redirectHost: 'localhost'
}
} : {}),
...(microsoftClientId ? {
microsoft: {
clientId: microsoftClientId,
tenant: microsoftTenant || 'common',
authorizationEndpoint: `https://login.microsoftonline.com/${microsoftTenant || 'common'}/oauth2/v2.0/authorize`,
tokenEndpoint: `https://login.microsoftonline.com/${microsoftTenant || 'common'}/oauth2/v2.0/token`,
scope: MICROSOFT_SCOPES,
redirectHost: 'localhost'
}
} : {})
};
}
function createOAuth2Service({
providers,
openExternal,
fetchImpl = globalThis.fetch,
createServer = http.createServer,
timeoutMs = 3 * 60 * 1000
}) {
function listProviders() {
return [
{ id: 'google', label: 'Google', configured: Boolean(providers.google?.clientId) },
{ id: 'microsoft', label: 'Microsoft', configured: Boolean(providers.microsoft?.clientId) }
];
}
function providerConfig(provider) {
const config = providers[provider];
if (!['google', 'microsoft'].includes(provider) || !config?.clientId) {
throw new Error(`OAuth2 sign-in for ${provider} is not configured on this desktop build.`);
}
return config;
}
async function requestTokens(config, parameters) {
const body = new URLSearchParams({ client_id: config.clientId, ...parameters });
if (config.clientSecret) body.set('client_secret', config.clientSecret);
let response;
try {
response = await fetchImpl(config.tokenEndpoint, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body,
signal: AbortSignal.timeout(20_000),
redirect: 'error'
});
} catch {
throw new Error('Could not contact the OAuth2 provider. Check your network and try again.');
}
const data = await response.json().catch(() => ({}));
if (!response.ok) {
const detail = String(data.error_description || data.error || '').slice(0, 240).replace(/\s+/g, ' ');
throw new Error(detail ? `OAuth2 sign-in failed: ${detail}` : 'OAuth2 sign-in failed. Try again.');
}
if (typeof data.access_token !== 'string' || !data.access_token || !Number.isFinite(Number(data.expires_in))) {
throw new Error('The OAuth2 provider returned an invalid token response.');
}
return {
oauthAccessToken: data.access_token,
oauthRefreshToken: typeof data.refresh_token === 'string' && data.refresh_token
? data.refresh_token : parameters.refresh_token || '',
oauthAccessTokenExpiresAt: Date.now() + Math.max(0, Number(data.expires_in)) * 1000
};
}
async function authorize(provider, email) {
const config = providerConfig(provider);
if (typeof email !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
throw new Error('Enter a valid email address before authorizing OAuth2.');
}
if (typeof openExternal !== 'function' || typeof fetchImpl !== 'function') {
throw new Error('Desktop OAuth2 sign-in is unavailable.');
}
const state = randomBytes(32).toString('base64url');
const verifier = randomBytes(48).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('base64url');
let settleCallback;
let callbackComplete = false;
const callback = new Promise((resolve, reject) => {
settleCallback = { resolve, reject };
});
callback.catch(() => {});
const server = createServer((request, response) => {
if (request.method !== 'GET') {
response.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' }).end('Method not allowed');
return;
}
const callbackUrl = new URL(request.url || '/', 'http://localhost');
if (callbackUrl.pathname !== '/') {
response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found');
return;
}
const returnedState = callbackUrl.searchParams.get('state') || '';
const expected = Buffer.from(state);
const received = Buffer.from(returnedState);
if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('OAuth2 state validation failed. You can close this window.');
if (!callbackComplete) {
callbackComplete = true;
settleCallback.reject(new Error('OAuth2 state validation failed. Please try again.'));
}
return;
}
const error = callbackUrl.searchParams.get('error');
if (error) {
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('Sign-in was not completed. You can close this window.');
if (!callbackComplete) {
callbackComplete = true;
settleCallback.reject(new Error('OAuth2 authorization was cancelled or denied.'));
}
return;
}
const code = callbackUrl.searchParams.get('code');
if (!code) {
response.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' }).end('The authorization response was incomplete. You can close this window.');
return;
}
response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
.end('<!doctype html><title>ep-mail</title><p>Sign-in complete. You may close this browser window and return to ep-mail.</p>');
if (!callbackComplete) {
callbackComplete = true;
settleCallback.resolve(code);
}
});
let timeout;
try {
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, 'localhost', resolve);
});
const port = server.address().port;
const redirectUri = `http://${config.redirectHost}:${port}`;
const authorizationUrl = new URL(config.authorizationEndpoint);
authorizationUrl.search = new URLSearchParams({
client_id: config.clientId,
redirect_uri: redirectUri,
response_type: 'code',
response_mode: 'query',
scope: config.scope,
state,
code_challenge: challenge,
code_challenge_method: 'S256',
login_hint: email,
...(provider === 'google' ? { access_type: 'offline', prompt: 'consent' } : {})
}).toString();
timeout = setTimeout(() => {
if (!callbackComplete) {
callbackComplete = true;
settleCallback.reject(new Error('OAuth2 sign-in timed out. Try again.'));
}
}, timeoutMs);
await openExternal(authorizationUrl.href);
const code = await callback;
return await requestTokens(config, {
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
code_verifier: verifier,
scope: config.scope
});
} finally {
clearTimeout(timeout);
await new Promise(resolve => server.close(() => resolve()));
}
}
async function refresh(provider, refreshToken) {
const config = providerConfig(provider);
if (typeof refreshToken !== 'string' || !refreshToken) {
throw new Error(`Reconnect this ${provider === 'google' ? 'Google' : 'Microsoft'} account to continue.`);
}
return requestTokens(config, {
grant_type: 'refresh_token',
refresh_token: refreshToken,
scope: config.scope
});
}
return Object.freeze({ listProviders, authorize, refresh });
}
module.exports = { createOAuth2Service, loadOAuthProviderConfig };
+71
View File
@@ -0,0 +1,71 @@
const { randomUUID } = require('node:crypto');
function applyQueuedActionToCache(account, input) {
const folder = String(input.folder || 'Inbox');
const cache = account.mailCache?.[folder];
if (!cache) return;
const index = cache.findIndex(message => Number(message.uid || message.id) === Number(input.uid));
if (index < 0) return;
const [message] = cache.splice(index, 1);
if (input.action === 'star' || input.action === 'unread') {
message[input.action] = Boolean(input.enabled);
cache.splice(index, 0, message);
return;
}
const target = input.action === 'archive' ? 'Archive' : input.action === 'delete' ? 'Trash' : input.action === 'inbox' ? 'Inbox' : null;
if (!target) {
cache.splice(index, 0, message);
return;
}
message.sourceFolder = target;
message.archived = target === 'Archive';
message.deleted = target === 'Trash';
account.mailCache[target] = account.mailCache[target] || [];
account.mailCache[target] = [...account.mailCache[target].filter(item => Number(item.uid || item.id) !== Number(input.uid)), message].slice(-50);
}
function createMailOutboxService({
sendMailNow,
applyMessageAction,
updateAccountStore,
isConnectivityFailure,
createId = randomUUID,
now = Date.now,
logError = (...args) => console.error(...args)
}) {
async function flushMailOutbox(account) {
const operations = [...(account.mailOutbox || [])];
for (const operation of operations) {
try {
if (operation.type === 'send') await sendMailNow(account, operation.data);
else if (operation.type === 'action') await applyMessageAction(account, operation.data);
else throw new Error('Unsupported queued mail operation.');
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) saved.mailOutbox = (saved.mailOutbox || []).filter(item => item.id !== operation.id);
});
} catch (error) {
if (isConnectivityFailure(error)) break;
logError(`Could not complete queued mail operation ${operation.id}:`, error);
break;
}
}
}
async function queueMessageAction(account, input) {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) throw new Error('That mail account is no longer available.');
saved.mailOutbox = saved.mailOutbox || [];
saved.mailOutbox = saved.mailOutbox.filter(item => !(item.type === 'action' &&
Number(item.data?.uid) === Number(input.uid) && item.data?.folder === input.folder && item.data?.action === input.action));
saved.mailOutbox.push({ id: createId(), type: 'action', data: input, createdAt: now() });
applyQueuedActionToCache(saved, input);
});
return { ok: true, queued: true };
}
return { flushMailOutbox, queueMessageAction };
}
module.exports = { applyQueuedActionToCache, createMailOutboxService };
+65
View File
@@ -0,0 +1,65 @@
function createMailReader({
imapClient,
folderPath,
toUiMessage,
cacheMailboxMessages,
fetchSnoozedMailbox,
filterMailboxMessages
}) {
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
const client = await imapClient(account);
try {
await client.connect();
const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) return { messages: [], total: 0 };
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
const snoozed = new Set((account.snoozedMessages || [])
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
.map(item => Number(item.uid)));
if (Object.values(filters).some(value => value && value !== false)) {
const searchStart = Math.max(1, mailbox.exists - 4999);
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}) : [];
const all = [];
for (const item of fetched) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
all.push(message);
}
await cacheMailboxMessages(account.id, folder, all);
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
const start = Math.max(0, Number(offset) || 0);
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
}
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
const fetched = await client.fetchAll(`${first}:${end}`, {
uid: true,
envelope: true,
flags: true,
internalDate: true,
source: true
});
const messages = [];
for (const item of fetched.reverse()) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
messages.push(message);
}
await cacheMailboxMessages(account.id, folder, messages);
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
return { fetchMailbox };
}
module.exports = { createMailReader };
+64
View File
@@ -0,0 +1,64 @@
const { randomUUID } = require('node:crypto');
const nodemailer = require('nodemailer');
const { normalizeOutgoingAttachments } = require('../mail-attachments.cjs');
function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTransport = nodemailer.createTransport }) {
async function sendMailNow(account, message) {
const to = String(message?.to || '').trim();
if (!to) throw new Error('Add at least one recipient.');
const attachments = normalizeOutgoingAttachments(message?.attachments);
const transport = await smtpTransport(account);
const sentMessageId = String(message.messageId || `<${randomUUID()}@ep-mail.local>`);
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
const body = String(message?.text || '').slice(0, 500000);
const signature = String(account.signature || '').slice(0, 5000);
const messageOptions = {
from: { name: fromName, address: account.email },
to,
cc: String(message.cc || '').trim() || undefined,
subject: String(message.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: sentMessageId,
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
};
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
try {
if (rawMessage) await transport.sendMail({ envelope: message.envelope, raw: rawMessage });
else await transport.sendMail(messageOptions);
} finally {
transport.close();
}
let savedToSent = false;
const copy = createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
try {
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
const client = await imapClient(account);
try {
await client.connect();
const sentPath = await findSentMailbox(client, true);
const lock = await client.getMailboxLock(sentPath);
try {
const existing = await client.search({ header: { 'message-id': sentMessageId } }, { uid: true });
if (!existing.length) await client.append(sentPath, rendered.message, ['\\Seen'], new Date());
savedToSent = true;
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
} catch {
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
}
return { ok: true, savedToSent };
}
return { sendMailNow };
}
module.exports = { createMailSender };
+56
View File
@@ -0,0 +1,56 @@
function createSnoozeReminderService({
readAccountStore,
updateAccountStore,
showNotification,
sendMailSyncUpdate,
now = Date.now,
logError = (...args) => console.error(...args)
}) {
let checkInProgress = false;
async function checkSnoozeReminders() {
if (checkInProgress) return;
checkInProgress = true;
try {
const current = await readAccountStore();
if (!current?.accounts.some(account =>
(account.snoozedMessages || []).some(item => Number(item.dueAt) <= now())
)) return;
const due = await updateAccountStore(store => {
const reminders = [];
for (const account of store.accounts) {
const snoozes = account.snoozedMessages || [];
const remaining = [];
for (const item of snoozes) {
if (Number(item.dueAt) <= now()) reminders.push({
accountId: account.id,
email: account.email,
notificationsEnabled: account.notificationsEnabled !== false,
...item
});
else remaining.push(item);
}
account.snoozedMessages = remaining;
}
return reminders;
});
for (const reminder of due) {
if (reminder.notificationsEnabled !== false) showNotification(reminder);
sendMailSyncUpdate({
accountId: reminder.accountId,
snoozeReminder: true,
snoozedFolder: reminder.folder,
foldersChanged: ['Snoozed', reminder.folder]
});
}
} catch (error) {
logError('Could not process snooze reminders:', error);
} finally {
checkInProgress = false;
}
}
return { checkSnoozeReminders };
}
module.exports = { createSnoozeReminderService };
+90
View File
@@ -0,0 +1,90 @@
function createBackgroundSyncCoordinator({
readAccountStore,
syncAccountMailboxes,
backgroundSyncGenerations,
backgroundSyncFailures,
lastBackgroundSyncAt,
flagSnapshots,
reconcileIdleWatchers,
sendMailSyncUpdate,
showNewMailNotification,
concurrency = 2,
retryIntervalMs = 2 * 60 * 1000,
now = Date.now,
logError = (...args) => console.error(...args)
}) {
let backgroundSyncInProgress = false;
let backgroundSyncRequested = false;
async function syncAccountWithBackoff(account, periodicOnly = false) {
if (periodicOnly) {
const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000;
if (now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return;
}
const failure = backgroundSyncFailures.get(account.id);
if (failure && now() < failure.retryAt) return;
lastBackgroundSyncAt.set(account.id, now());
const generation = backgroundSyncGenerations.get(account.id) || 0;
try {
const result = await syncAccountMailboxes(account);
if (backgroundSyncGenerations.get(account.id) !== generation) return;
backgroundSyncFailures.delete(account.id);
if (result.newCount || result.changedFolders.length) {
const update = { accountId: account.id, newCount: result.newCount, foldersChanged: result.changedFolders };
sendMailSyncUpdate(update);
showNewMailNotification(account, result.newCount);
}
} catch (error) {
const attempts = (failure?.attempts || 0) + 1;
const retryDelay = Math.min(30 * 60 * 1000, retryIntervalMs * (2 ** Math.min(attempts - 1, 4)));
backgroundSyncFailures.set(account.id, { attempts, retryAt: now() + retryDelay });
logError(`Background mail sync failed for ${account.email}:`, error);
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
}
}
async function runBackgroundSync(periodicOnly = false) {
if (backgroundSyncInProgress) {
if (!periodicOnly) backgroundSyncRequested = true;
return;
}
backgroundSyncInProgress = true;
let onlyDueAccounts = periodicOnly;
try {
do {
backgroundSyncRequested = false;
const store = (await readAccountStore()) || { accounts: [] };
for (let index = 0; index < store.accounts.length; index += concurrency) {
await Promise.all(store.accounts.slice(index, index + concurrency)
.map(account => syncAccountWithBackoff(account, onlyDueAccounts)));
}
if (backgroundSyncRequested) onlyDueAccounts = false;
} while (backgroundSyncRequested);
} finally {
backgroundSyncInProgress = false;
if (backgroundSyncRequested) void runBackgroundSync().catch(error => logError('Background mail sync failed:', error));
}
}
function requestBackgroundSync(accountId = null, force = false) {
if (accountId) {
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
backgroundSyncFailures.delete(accountId);
flagSnapshots.delete(accountId);
}
if (force) {
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
}
void reconcileIdleWatchers().catch(error => logError('Could not reconcile IMAP IDLE watchers:', error));
if (backgroundSyncInProgress) {
if (accountId || force) backgroundSyncRequested = true;
return;
}
backgroundSyncRequested = true;
void runBackgroundSync().catch(error => logError('Background mail sync failed:', error));
}
return { requestBackgroundSync, runBackgroundSync, syncAccountWithBackoff };
}
module.exports = { createBackgroundSyncCoordinator };
+152
View File
@@ -0,0 +1,152 @@
function backgroundFolderLabel(mailbox) {
const specialUse = String(mailbox.specialUse || '').toLowerCase();
if (specialUse === '\\sent') return 'Sent';
if (specialUse === '\\archive') return 'Archive';
if (specialUse === '\\trash') return 'Trash';
if (mailbox.path.toLowerCase() === 'inbox') return 'Inbox';
const finalPart = mailbox.path.toLowerCase().split(/[./]/).pop();
if (['sent', 'sent items', 'sent mail', 'sent messages'].includes(finalPart)) return 'Sent';
if (['archive', 'archives', 'all mail'].includes(finalPart)) return 'Archive';
if (['trash', 'deleted items', 'deleted messages'].includes(finalPart)) return 'Trash';
return mailbox.path;
}
function createMailboxSyncService({
imapClient,
flushMailOutbox,
updateAccountStore,
saveAccountSyncState,
backgroundSyncGenerations,
flagSnapshots,
findSpecialMailbox,
folderPath,
logError = (...args) => console.error(...args)
}) {
async function syncAccountMailboxes(account) {
await flushMailOutbox(account);
const generation = backgroundSyncGenerations.get(account.id) || 0;
const client = await imapClient(account);
try {
await client.connect();
const mailboxes = await client.list();
const states = { ...(account.syncState?.folders || {}) };
const accountSnapshots = new Map(flagSnapshots.get(account.id) || []);
let inboxNewCount = 0;
const changedFolders = [];
const ruleActions = [];
for (const listedMailbox of mailboxes) {
const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true });
const folder = listedMailbox.path;
const label = backgroundFolderLabel(listedMailbox);
const uidValidity = String(mailbox.uidValidity);
const uidCeiling = Math.max(0, Number(mailbox.uidNext) - 1);
const oldState = states[folder];
const cursorIsValid = oldState?.uidValidity === uidValidity && Number.isInteger(oldState.lastUid);
if (!cursorIsValid) {
states[folder] = {
uidValidity,
lastUid: uidCeiling,
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : null
};
if (!mailbox.highestModseq) {
const initialFlags = await client.fetchAll('1:*', { uid: true, flags: true });
accountSnapshots.set(folder, {
uidValidity,
flags: new Map(initialFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]))
});
}
continue;
}
const previousUid = Number(oldState.lastUid);
const added = uidCeiling > previousUid
? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true })
: [];
if (label === 'Inbox' && account.rules?.length) {
for (const item of added) {
const rule = account.rules.find(candidate => {
const sender = (item.envelope?.from || []).map(address => `${address.name || ''} ${address.address || ''}`).join(' ').toLowerCase();
const subject = String(item.envelope?.subject || '').toLowerCase();
return (!candidate.senderContains || sender.includes(candidate.senderContains.toLowerCase())) &&
(!candidate.subjectContains || subject.includes(candidate.subjectContains.toLowerCase()));
});
if (rule) ruleActions.push({ uid: Number(item.uid), folder, rule });
}
}
let flagsChanged = false;
if (mailbox.highestModseq && oldState.highestModseq) {
const changed = await client.fetchAll('1:*', { uid: true, flags: true, modseq: true }, {
uid: true,
changedSince: BigInt(oldState.highestModseq)
});
flagsChanged = changed.some(item => Number(item.uid) <= previousUid);
} else if (!mailbox.highestModseq) {
const currentFlags = await client.fetchAll('1:*', { uid: true, flags: true });
const nextSnapshot = new Map(currentFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]));
const previousSnapshot = accountSnapshots.get(folder);
if (previousSnapshot?.uidValidity === uidValidity) {
flagsChanged = [...previousSnapshot.flags].some(([uid, flags]) => uid <= previousUid && nextSnapshot.get(uid) !== flags);
}
accountSnapshots.set(folder, { uidValidity, flags: nextSnapshot });
}
states[folder] = {
uidValidity,
lastUid: Math.max(previousUid, uidCeiling),
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : oldState.highestModseq || null
};
if (added.length && label === 'Inbox') inboxNewCount += added.length;
if (added.length || flagsChanged) changedFolders.push(label);
}
const ruleLabels = [];
for (const { uid, folder, rule } of ruleActions) {
const lock = await client.getMailboxLock(folder);
try {
if (rule.action === 'flag') {
await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
} else if (rule.action === 'archive' || rule.action === 'move') {
const target = rule.action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: await folderPath(client, rule.value);
if (!target) throw new Error(`Rule destination mailbox "${rule.value}" was not found.`);
if (target !== folder) await client.messageMove(uid, target, { uid: true });
changedFolders.push(rule.action === 'archive' ? 'Archive' : backgroundFolderLabel({ path: target }));
} else if (rule.action === 'label') {
ruleLabels.push({ key: `${folder}:${uid}`, label: rule.value });
}
} catch (error) {
logError(`Could not apply mail rule "${rule.id}" to message ${uid}:`, error);
} finally {
lock.release();
}
}
if (ruleLabels.length) {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) return;
saved.ruleLabels = saved.ruleLabels || {};
for (const { key, label } of ruleLabels) {
saved.ruleLabels[key] = [...new Set([...(saved.ruleLabels[key] || []), label])];
}
});
}
const saved = await saveAccountSyncState(account.id, generation, states);
if (!saved || backgroundSyncGenerations.get(account.id) !== generation) {
return { newCount: 0, changedFolders: [] };
}
flagSnapshots.set(account.id, accountSnapshots);
return { newCount: inboxNewCount, changedFolders: [...new Set(changedFolders)] };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
return { syncAccountMailboxes };
}
module.exports = { backgroundFolderLabel, createMailboxSyncService };
+321 -1634
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -4,6 +4,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
getAppVersion: () => ipcRenderer.invoke('app:get-version'), getAppVersion: () => ipcRenderer.invoke('app:get-version'),
getAccount: () => ipcRenderer.invoke('mail:get-account'), getAccount: () => ipcRenderer.invoke('mail:get-account'),
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'), listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
listOAuthProviders: () => ipcRenderer.invoke('mail:list-oauth-providers'),
selectAccount: id => ipcRenderer.invoke('mail:select-account', id), selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id), removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
connect: details => ipcRenderer.invoke('mail:connect', details), connect: details => ipcRenderer.invoke('mail:connect', details),
+33
View File
@@ -0,0 +1,33 @@
const fs = require('node:fs/promises');
const path = require('node:path');
function createSecureJsonStore({ getFilePath, safeStorage, assertSecureStorage, unavailableMessage }) {
if (typeof getFilePath !== 'function') throw new TypeError('A file path provider is required.');
if (!safeStorage || typeof safeStorage.encryptStringAsync !== 'function' ||
typeof safeStorage.decryptStringAsync !== 'function' ||
typeof safeStorage.isAsyncEncryptionAvailable !== 'function') {
throw new TypeError('An asynchronous safe storage adapter is required.');
}
if (typeof assertSecureStorage !== 'function') throw new TypeError('A secure-storage check is required.');
return {
async load() {
assertSecureStorage();
const encrypted = await fs.readFile(getFilePath());
const { result } = await safeStorage.decryptStringAsync(encrypted);
return JSON.parse(result);
},
async save(value) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error(unavailableMessage);
const file = getFilePath();
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(value));
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 });
await fs.rename(`${file}.tmp`, file);
}
};
}
module.exports = { createSecureJsonStore };
+312
View File
@@ -0,0 +1,312 @@
const MAX_DEPTH = 20;
const MAX_VALUES = 25_000;
const MAX_COLLECTION_ITEMS = 5_000;
const MAX_STRING_LENGTH = 1_000_000;
const MAX_ARMORED_KEY_LENGTH = 200_000;
const str = (max = MAX_STRING_LENGTH, options = {}) => ({ type: 'string', max, ...options });
const num = options => ({ type: 'number', ...options });
const bool = () => ({ type: 'boolean' });
const record = (fields, options = {}) => ({ type: 'object', fields, ...options });
const array = (item, maxItems = MAX_COLLECTION_ITEMS) => ({ type: 'array', item, maxItems });
const attachmentFields = {
filename: str(255),
contentType: str(200),
contentBase64: str(Infinity, { required: true })
};
const ruleFields = {
id: str(100),
senderContains: str(200),
subjectContains: str(200),
action: { type: 'enum', values: ['archive', 'move', 'label', 'flag'] },
value: str(200)
};
const davRemoteFields = {
accountId: str(256),
collectionUrl: str(4096),
objectUrl: str(4096),
etag: str(1024, { nullable: true }),
uid: str(255, { nullable: true })
};
const objectFieldSchemas = {
'mail:update-account': [null, {
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
reauthorizeOAuth: bool(),
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
rules: array(record(ruleFields), 50)
}],
'mail:connect': [{
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
rules: array(record(ruleFields), 50)
}],
'mail:sync-folder': [null, null, {
folder: str(256), query: str(2000), sender: str(1000), subject: str(1000),
after: str(20), before: str(20), hasAttachments: bool()
}],
'mail:create-folder': [{ name: str(100) }],
'mail:save-draft': [{
id: str(256), to: str(4000), cc: str(4000), subject: str(998), text: str(500_000),
attachments: array(record(attachmentFields))
}],
'mail:set-snooze': [{
uid: num({ integer: true, min: 1 }), folder: str(256), sourceFolder: str(256),
dueAt: num({ nullable: true }), subject: str(200)
}],
'mail:update-message': [{
uid: num({ integer: true, min: 1 }), folder: str(256),
action: { type: 'enum', values: ['star', 'unread', 'archive', 'delete', 'inbox'] }, enabled: bool()
}],
'mail:save-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }],
'mail:preview-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }],
'mail:send': [{
to: str(4000), cc: str(4000), subject: str(998), text: str(500_000), displayName: str(80),
messageId: str(998), attachments: array(record(attachmentFields)),
pgp: record({ encrypt: bool(), sign: bool(), passphrase: str(4096, { nullable: true }) }, { nullable: true })
}],
'pgp:generate': [{ name: str(200), email: str(320), passphrase: str(4096), accountId: str(256, { nullable: true }) }],
'pgp:import': [{ armoredKey: str(MAX_ARMORED_KEY_LENGTH), passphrase: str(4096), accountId: str(256, { nullable: true }) }],
'pgp:change-passphrase': [{ fingerprint: str(64), currentPassphrase: str(4096), newPassphrase: str(4096) }],
'pgp:decrypt-message': [{ folder: str(256), uid: num({ integer: true, min: 1 }), passphrase: str(4096, { nullable: true }) }],
'pgp:check-send': [{ to: str(4000), cc: str(4000), sign: bool() }],
'pgp:add-contact': [{ armoredKey: str(MAX_ARMORED_KEY_LENGTH), passphrase: str(4096), source: { type: 'enum', values: ['import', 'message', 'paste', 'keyserver'] } }],
'pgp:set-settings': [{ cacheMinutes: num({ min: 0, max: 1440 }) }],
'pgp:set-key-server-enabled': [{ serverId: str(256), enabled: bool() }],
'pgp:add-key-server': [{ name: str(60), url: str(300), protocol: { type: 'enum', values: ['hkp', 'vks'] } }],
'pgp:find-key': [{ email: str(320) }],
'pgp:publish-key': [{ fingerprint: str(64), serverId: str(256) }],
'dav:connect': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, serverUrl: str(2048), username: str(1024), password: str(4096) }],
'dav:activate': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, id: str(256) }],
'dav:remove': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, id: str(256) }],
'dav:save-event': [{
title: str(120), date: str(20), time: str(20), with: str(4000), place: str(1000), notes: str(5000),
_dav: record(davRemoteFields, { nullable: true })
}],
'dav:delete-event': [davRemoteFields],
'dav:save-contact': [{
name: str(100), email: str(320), note: str(5000),
_dav: record(davRemoteFields, { nullable: true })
}],
'dav:delete-contact': [davRemoteFields]
};
const positionalEnums = {
'pgp:set-trust': { 1: ['unknown', 'trusted', 'verified'] }
};
const positionalFieldSchemas = {
'mail:select-account': { 0: str(256) },
'mail:remove-account': { 0: str(256) },
'mail:delete-draft': { 0: str(256) },
'mail:disconnect': { 0: str(256) },
'mail:open-external': { 0: str(2048) },
'pgp:export-public': { 0: str(64) },
'pgp:export-private': { 0: str(64), 1: str(4096) },
'pgp:export-revocation': { 0: str(64), 1: str(4096) },
'pgp:delete': { 0: str(64), 1: str(4096) },
'pgp:set-trust': { 0: str(64) },
'pgp:remove-contact': { 0: str(64) },
'pgp:export-contact': { 0: str(64) },
'pgp:remove-key-server': { 0: str(256) }
};
const sendMessageFields = new Set(['to', 'cc', 'subject', 'text', 'displayName', 'messageId', 'attachments', 'pgp']);
const schemas = {
'app:get-version': [],
'mail:get-account': [],
'mail:list-accounts': [],
'mail:list-oauth-providers': [],
'mail:select-account': ['string'],
'mail:remove-account': ['string'],
'mail:update-account': ['string', 'object'],
'mail:connect': ['object'],
'mail:sync-folder': ['string', 'number?', 'object?'],
'mail:list-folders': [],
'mail:create-folder': ['object'],
'mail:list-drafts': [],
'mail:save-draft': ['object'],
'mail:delete-draft': ['string'],
'mail:set-snooze': ['object'],
'mail:update-message': ['object'],
'mail:save-attachment': ['object'],
'mail:preview-attachment': ['object'],
'mail:send': ['object'],
'mail:open-external': ['string'],
'mail:sync-inbox': [],
'mail:disconnect': ['string?'],
'pgp:list': [],
'pgp:generate': ['object'],
'pgp:import': ['object'],
'pgp:export-public': ['string'],
'pgp:export-private': ['string', 'string'],
'pgp:change-passphrase': ['object'],
'pgp:export-revocation': ['string', 'string'],
'pgp:delete': ['string', 'string'],
'pgp:decrypt-message': ['object'],
'pgp:check-send': ['object'],
'pgp:contacts': [],
'pgp:add-contact': ['object'],
'pgp:set-trust': ['string', 'string'],
'pgp:remove-contact': ['string'],
'pgp:export-contact': ['string'],
'pgp:get-settings': [],
'pgp:set-settings': ['object'],
'pgp:key-servers': [],
'pgp:set-key-server-enabled': ['object'],
'pgp:add-key-server': ['object'],
'pgp:remove-key-server': ['string'],
'pgp:find-key': ['object'],
'pgp:publish-key': ['object'],
'pgp:forget-passphrases': [],
'dav:list': [],
'dav:connect': ['object'],
'dav:activate': ['object'],
'dav:remove': ['object'],
'dav:sync': ['enum:caldav,carddav'],
'dav:save-event': ['object'],
'dav:delete-event': ['object'],
'dav:save-contact': ['object'],
'dav:delete-contact': ['object']
};
function isRecord(value) {
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function validateTree(value, channel) {
let values = 0;
const ancestors = new WeakSet();
function visit(current, depth, key = '') {
values += 1;
if (values > MAX_VALUES) throw new Error(`Too many values in IPC request for ${channel}.`);
if (depth > MAX_DEPTH) throw new Error(`IPC request for ${channel} is nested too deeply.`);
if (current === null || current === undefined || typeof current === 'boolean') return;
if (typeof current === 'number') {
if (!Number.isFinite(current)) throw new Error(`Invalid number in IPC request for ${channel}.`);
return;
}
if (typeof current === 'string') {
const limit = key === 'armoredKey' ? MAX_ARMORED_KEY_LENGTH :
['contentBase64', 'rawBase64'].includes(key) ? Infinity : MAX_STRING_LENGTH;
if (current.length > limit) throw new Error(`String value is too large in IPC request for ${channel}.`);
return;
}
if (typeof current !== 'object' || (!Array.isArray(current) && !isRecord(current))) {
throw new Error(`Unsupported value in IPC request for ${channel}.`);
}
if (ancestors.has(current)) throw new Error(`Cyclic value in IPC request for ${channel}.`);
ancestors.add(current);
if (Array.isArray(current)) {
if (current.length > MAX_COLLECTION_ITEMS) throw new Error(`Too many items in IPC request for ${channel}.`);
for (const item of current) visit(item, depth + 1);
} else {
const entries = Object.entries(current);
if (entries.length > MAX_COLLECTION_ITEMS) throw new Error(`Too many fields in IPC request for ${channel}.`);
for (const [childKey, child] of entries) {
if (['__proto__', 'prototype', 'constructor'].includes(childKey)) {
throw new Error(`Unsafe field in IPC request for ${channel}.`);
}
visit(child, depth + 1, childKey);
}
}
ancestors.delete(current);
}
visit(value, 0);
}
function validateField(value, field, channel, fieldPath) {
if (value === undefined) {
if (field.required) throw new Error(`Missing ${fieldPath} in IPC request for ${channel}.`);
return;
}
if (value === null && field.nullable) return;
if (field.type === 'string') {
if (typeof value !== 'string') throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
if (value.length > field.max) throw new Error(`The ${fieldPath} value is too large in IPC request for ${channel}.`);
return;
}
if (field.type === 'number') {
if (typeof value !== 'number' || !Number.isFinite(value) ||
(field.integer && !Number.isInteger(value)) ||
(field.min !== undefined && value < field.min) ||
(field.max !== undefined && value > field.max)) {
throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
}
return;
}
if (field.type === 'boolean') {
if (typeof value !== 'boolean') throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
return;
}
if (field.type === 'enum') {
if (!field.values.includes(value)) throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
return;
}
if (field.type === 'array') {
if (!Array.isArray(value) || value.length > field.maxItems) {
throw new Error(`Invalid ${fieldPath} list in IPC request for ${channel}.`);
}
value.forEach((item, index) => validateField(item, field.item, channel, `${fieldPath}[${index}]`));
return;
}
if (field.type === 'object') {
if (!isRecord(value)) throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
for (const [name, childField] of Object.entries(field.fields || {})) {
validateField(value[name], childField, channel, `${fieldPath}.${name}`);
}
return;
}
throw new Error(`Unsupported validation rule for ${channel}.${fieldPath}.`);
}
function validateIpcArguments(channel, args) {
const schema = schemas[channel];
if (!schema) throw new Error(`Unknown IPC channel: ${channel}.`);
if (!Array.isArray(args)) throw new TypeError('IPC arguments must be an array.');
const required = schema.filter(type => !type.endsWith('?')).length;
if (args.length < required || args.length > schema.length) {
throw new Error(`Invalid argument count for IPC channel ${channel}.`);
}
for (let index = 0; index < args.length; index += 1) {
const expected = schema[index].replace(/\?$/, '');
const value = args[index];
if (value === undefined && schema[index].endsWith('?')) continue;
const isEnum = expected.startsWith('enum:');
const typeIsValid = expected === 'object'
? isRecord(value)
: isEnum
? expected.slice('enum:'.length).split(',').includes(value)
: typeof value === expected;
if (!typeIsValid) {
throw new Error(`Invalid ${expected} argument ${index + 1} for IPC channel ${channel}.`);
}
validateTree(value, channel);
const fieldSchema = objectFieldSchemas[channel]?.[index];
if (fieldSchema) validateField(value, { type: 'object', fields: fieldSchema }, channel, `argument ${index + 1}`);
const enumValues = positionalEnums[channel]?.[index];
if (enumValues && !enumValues.includes(value)) throw new Error(`Invalid argument ${index + 1} for IPC channel ${channel}.`);
const positionalField = positionalFieldSchemas[channel]?.[index];
if (positionalField) validateField(value, positionalField, channel, `argument ${index + 1}`);
}
if (channel === 'mail:send') {
const unknown = Object.keys(args[0]).find(key => !sendMessageFields.has(key));
if (unknown) throw new Error(`Unsupported message field for IPC channel ${channel}.`);
}
}
function hasIpcSchema(channel) {
return Object.hasOwn(schemas, channel);
}
module.exports = { hasIpcSchema, validateIpcArguments };
+31
View File
@@ -0,0 +1,31 @@
const path = require('node:path');
const { fileURLToPath } = require('node:url');
function isTrustedApplicationUrl(rawUrl, expectedFile) {
let actualFile;
try {
const url = new URL(rawUrl);
if (url.protocol !== 'file:' || url.search || url.hash) {
return false;
}
actualFile = fileURLToPath(url);
} catch {
return false;
}
const expected = path.resolve(expectedFile);
const actual = path.resolve(actualFile);
return process.platform === 'win32'
? actual.toLowerCase() === expected.toLowerCase()
: actual === expected;
}
function assertTrustedIpcSender(event, expectedFile) {
const frame = event?.senderFrame;
if (!frame || !event?.sender || frame !== event.sender.mainFrame ||
!isTrustedApplicationUrl(frame.url, expectedFile)) {
throw new Error('This request must come from the application window.');
}
}
module.exports = { assertTrustedIpcSender, isTrustedApplicationUrl };
+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*
+5 -2
View File
@@ -64,13 +64,16 @@
</div> </div>
<div id="modal-root"></div> <div id="modal-root"></div>
<div id="toast" class="toast" role="status" aria-live="polite"></div> <div id="toast" class="toast" role="status" aria-live="polite"></div>
<script src="renderer-state.js"></script>
<script src="mail-content-security.js"></script>
<script src="app.js"></script> <script src="app.js"></script>
<script src="platform-bridge.js"></script> <script src="platform-bridge-loader.js"></script>
<script src="renderer-mail-api.js"></script>
<script src="mail-ui.js"></script> <script src="mail-ui.js"></script>
<script src="productivity.js"></script> <script src="productivity.js"></script>
<script src="snooze-ui.js"></script> <script src="snooze-ui.js"></script>
<script src="account-ui.js"></script>
<script src="dav-ui.js"></script> <script src="dav-ui.js"></script>
<script src="account-ui.js"></script>
<script src="shortcuts.js"></script> <script src="shortcuts.js"></script>
<script src="attachments.js"></script> <script src="attachments.js"></script>
<script src="pgp-ui.js"></script> <script src="pgp-ui.js"></script>
+76
View File
@@ -0,0 +1,76 @@
(function installMailContentSecurity(root) {
if (typeof module === 'object' && module.exports) {
module.exports = { createMailContentSecurity };
return;
}
root.epMailFeatures = root.epMailFeatures || {};
Object.defineProperty(root.epMailFeatures, 'contentSecurity', {
value: createMailContentSecurity(root),
enumerable: false
});
function createMailContentSecurity(browserRoot) {
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, character => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
})[character]);
}
function safeRemoteImageUrl(value) {
if (typeof value !== 'string' || value.length > 2048) return null;
try {
const url = new URL(value);
return url.protocol === 'https:' && url.hostname && !url.username && !url.password ? url.href : null;
} catch {
return null;
}
}
function sanitizeMailHtml(value) {
const html = String(value || '').slice(0, 100000);
const inertImages = html
.replace(/<(script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track)\b[\s\S]*?<\/\1\s*>/gi, '')
.replace(/<(?:script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track|link|base|meta)\b[^>]*>/gi, '')
.replace(/<!--[\s\S]*?-->/g, '')
.replace(/<img\b[^>]*>/gi, tag => {
const source = tag.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const alt = tag.match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const remote = source && (source[1] || source[2] || source[3] || '').trim();
const alternative = alt && (alt[1] || alt[2] || alt[3] || '');
return `<img${remote ? ` data-remote-src="${escapeHtml(remote)}"` : ''}${alternative ? ` alt="${escapeHtml(alternative)}"` : ''}>`;
})
.replace(/\s(?:src|srcset|background|poster|action|formaction|href|xlink:href|srcdoc|dynsrc|lowsrc|style)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, '');
const document = new browserRoot.DOMParser().parseFromString(inertImages, 'text/html');
const allowed = new Set(['a', 'p', 'div', 'span', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'b', 'strong', 'i', 'em', 'u', 's', 'del', 'blockquote', 'pre', 'code', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'img']);
const discard = new Set(['script', 'style', 'iframe', 'frame', 'object', 'embed', 'svg', 'math', 'form', 'input', 'button', 'textarea', 'select', 'option', 'link', 'base', 'meta', 'video', 'audio', 'source', 'picture', 'track']);
let remoteImageCount = 0;
const clean = parent => {
for (const node of [...parent.childNodes]) {
if (node.nodeType !== browserRoot.Node.ELEMENT_NODE) {
if (node.nodeType !== browserRoot.Node.TEXT_NODE) node.remove();
continue;
}
const name = node.localName.toLowerCase();
if (discard.has(name)) { node.remove(); continue; }
if (!allowed.has(name)) { node.replaceWith(...node.childNodes); continue; }
for (const attribute of [...node.attributes]) {
const key = attribute.name.toLowerCase();
const keep = (name === 'img' && (key === 'alt' || key === 'data-remote-src')) ||
(name === 'td' || name === 'th') && ['colspan', 'rowspan'].includes(key) && /^\d{1,2}$/.test(attribute.value);
if (!keep) node.removeAttribute(attribute.name);
}
if (name === 'img') {
const url = safeRemoteImageUrl(node.getAttribute('data-remote-src'));
if (url) { node.setAttribute('data-remote-src', url); remoteImageCount += 1; }
else node.removeAttribute('data-remote-src');
}
clean(node);
}
};
clean(document.body);
return { html: document.body.innerHTML, remoteImageCount };
}
return Object.freeze({ safeRemoteImageUrl, sanitizeMailHtml });
}
})(typeof window === 'undefined' ? globalThis : window);
+380 -252
View File
@@ -1,10 +1,21 @@
let connectedMailAccount = null; (() => {
let mailPageOffset = 0; const rendererState = window.epMailState;
let mailTotal = 0; const appShell = window.epMailShell;
let mailboxSyncPromise = null; const selectMailUi = appShell.select;
let mailboxSyncQueued = false; const selectAllMailUi = appShell.selectAll;
let mailboxRefreshPending = false; const escapeMailUi = appShell.escapeHtml;
let folderBeforeSearch = null; const toastMailUi = appShell.toast;
const mailFeatureState = {
connectedAccount: null,
pageOffset: 0,
total: 0,
syncPromise: null,
syncQueued: false,
refreshPending: false,
folderBeforeSearch: null,
customFolders: [],
selectedDraftIds: new Set()
};
const senderBrandDomains = { const senderBrandDomains = {
amazon: ['amazon.com', 'amazon.co.uk'], amazon: ['amazon.com', 'amazon.co.uk'],
@@ -62,24 +73,23 @@ function messageLinks(message) {
.slice(0, 30); .slice(0, 30);
} }
const originalOpenMessage = openMessage; appShell.wrapOpenMessage(originalOpenMessage => function (id) {
openMessage = function (id) {
originalOpenMessage(id); originalOpenMessage(id);
const message = messages.find(item => item.id === id); const message = rendererState.messages.find(item => item.id === id);
if (!message) return; if (!message) return;
const senderReasons = suspiciousSenderReasons(message); const senderReasons = suspiciousSenderReasons(message);
const links = messageLinks(message); const links = messageLinks(message);
const warnings = []; const warnings = [];
if (senderReasons.length) { if (senderReasons.length) {
warnings.push(`<section class="mail-safety-warning" role="alert"><strong>Sender details may be misleading</strong><ul>${senderReasons.map(reason => `<li>${esc(reason)}</li>`).join('')}</ul><small>Sender names and addresses can be forged. Verify the sender through a trusted channel.</small></section>`); warnings.push(`<section class="mail-safety-warning" role="alert"><strong>Sender details may be misleading</strong><ul>${senderReasons.map(reason => `<li>${escapeMailUi(reason)}</li>`).join('')}</ul><small>Sender names and addresses can be forged. Verify the sender through a trusted channel.</small></section>`);
} }
const linkCards = links.map((link, index) => ` const linkCards = links.map((link, index) => `
<div class="mail-link-row ${link.reasons.length ? 'mail-link-risky' : ''}"> <div class="mail-link-row ${link.reasons.length ? 'mail-link-risky' : ''}">
<div><strong>${link.reasons.length ? 'Potentially unsafe link' : 'External link'}</strong><span>${esc(link.host)}</span> <div><strong>${link.reasons.length ? 'Potentially unsafe link' : 'External link'}</strong><span>${escapeMailUi(link.host)}</span>
${link.reasons.length ? `<small>${esc(link.reasons.join('; '))}</small>` : ''}</div> ${link.reasons.length ? `<small>${escapeMailUi(link.reasons.join('; '))}</small>` : ''}</div>
<button type="button" class="mail-link-open" data-mail-link="${index}">Review &amp; open</button> <button type="button" class="mail-link-open" data-mail-link="${index}">Review &amp; open</button>
</div>`).join(''); </div>`).join('');
const reader = $('#reader-pane'); const reader = selectMailUi('#reader-pane');
const header = reader.querySelector('.reader-header'); const header = reader.querySelector('.reader-header');
if (warnings.length && header) header.insertAdjacentHTML('afterend', warnings.join('')); if (warnings.length && header) header.insertAdjacentHTML('afterend', warnings.join(''));
const replyBar = reader.querySelector('.reply-bar'); const replyBar = reader.querySelector('.reply-bar');
@@ -93,25 +103,23 @@ openMessage = function (id) {
try { try {
await window.daybreakMail.openExternal(link.url); await window.daybreakMail.openExternal(link.url);
} catch (error) { } catch (error) {
toast(error.message || 'Could not open this link'); toastMailUi(error.message || 'Could not open this link');
} finally { } finally {
button.disabled = false; button.disabled = false;
} }
}; };
}); });
} }
}; });
let customFolders = [];
function renderCustomFolders() { function renderCustomFolders() {
const box = $('#custom-folders'); const box = selectMailUi('#custom-folders');
if (!box) return; if (!box) return;
box.replaceChildren(...customFolders.map(folder => { box.replaceChildren(...mailFeatureState.customFolders.map(folder => {
const button = document.createElement('button'); const button = document.createElement('button');
button.className = 'folder custom-folder'; button.className = 'folder custom-folder';
button.dataset.folder = folder.id; button.dataset.folder = folder.id;
button.classList.toggle('active', activeFolder === folder.id); button.classList.toggle('active', rendererState.activeFolder === folder.id);
const glyph = document.createElement('span'); const glyph = document.createElement('span');
glyph.className = 'nav-glyph'; glyph.className = 'nav-glyph';
glyph.textContent = '▭'; glyph.textContent = '▭';
@@ -120,12 +128,12 @@ function renderCustomFolders() {
button.title = folder.path; button.title = folder.path;
button.append(glyph, label); button.append(glyph, label);
button.addEventListener('click', () => { button.addEventListener('click', () => {
if ($('#filter-folder').value) { $('#filter-folder').value = ''; folderBeforeSearch = null; } if (selectMailUi('#filter-folder').value) { selectMailUi('#filter-folder').value = ''; mailFeatureState.folderBeforeSearch = null; }
activeFolder = folder.id; rendererState.activeFolder = folder.id;
$$('.folder').forEach(item => item.classList.toggle('active', item === button)); selectAllMailUi('.folder').forEach(item => item.classList.toggle('active', item === button));
$('#sidebar-title').textContent = folder.name; selectMailUi('#sidebar-title').textContent = folder.name;
$('#crumb-current').textContent = folder.name; selectMailUi('#crumb-current').textContent = folder.name;
mailPageOffset = 0; mailFeatureState.pageOffset = 0;
void syncMailbox(false, { offset: 0 }); void syncMailbox(false, { offset: 0 });
}); });
return button; return button;
@@ -133,21 +141,21 @@ function renderCustomFolders() {
} }
async function loadCustomFolders() { async function loadCustomFolders() {
if (!connectedMailAccount || !window.daybreakMail?.listFolders) return; if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
try { try {
customFolders = (await window.daybreakMail.listFolders()).folders || []; mailFeatureState.customFolders = (await window.daybreakMail.listFolders()).folders || [];
renderCustomFolders(); renderCustomFolders();
} catch {} } catch {}
} }
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders. // Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
function ruleFolderSelect(selected = 'Inbox') { function ruleFolderSelect(selected = 'Inbox') {
const options = [['Inbox', 'Inbox'], ['Archive', 'Archive'], ['Trash', 'Trash'], ...customFolders.map(folder => [folder.id, folder.name])]; const options = [['Inbox', 'Inbox'], ['Archive', 'Archive'], ['Trash', 'Trash'], ...mailFeatureState.customFolders.map(folder => [folder.id, folder.name])];
if (!options.some(([value]) => value === selected)) { if (!options.some(([value]) => value === selected)) {
options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]); options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]);
} }
return '<select class="mail-rule-value" aria-label="Destination folder">' + return '<select class="mail-rule-value" aria-label="Destination folder">' +
options.map(([value, name]) => '<option value="' + esc(value) + '"' + (value === selected ? ' selected' : '') + '>' + esc(name) + '</option>').join('') + '</select>'; options.map(([value, name]) => '<option value="' + escapeMailUi(value) + '"' + (value === selected ? ' selected' : '') + '>' + escapeMailUi(name) + '</option>').join('') + '</select>';
} }
// window.prompt() is not available in Electron, so ask for text in an in-app dialog. // window.prompt() is not available in Electron, so ask for text in an in-app dialog.
@@ -170,25 +178,25 @@ function askText(title, label, placeholder = '') {
} }
async function createMailFolder() { async function createMailFolder() {
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; } if (!mailFeatureState.connectedAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = await askText('New mail folder', 'Name'); const name = await askText('New mail folder', 'Name');
if (!name) return; if (!name) return;
try { try {
const result = await window.daybreakMail.createFolder(name); const result = await window.daybreakMail.createFolder(name);
customFolders = result.folders || customFolders; mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
renderCustomFolders(); renderCustomFolders();
toast(`Folder “${result.folder?.name || name}” created`); toastMailUi(`Folder “${result.folder?.name || name}” created`);
} catch (error) { } catch (error) {
toast(error.message || 'Could not create the folder'); toastMailUi(error.message || 'Could not create the folder');
} }
} }
function updateAccountCard(account) { function updateAccountCard(account) {
const card = $('#account-settings'); const card = selectMailUi('#account-settings');
if (!card) return; if (!card) return;
const email = account.email || ''; const email = account.email || '';
const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase()); const localName = (email.split('@')[0] || 'Mail account').replace(/[._-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase());
const displayName = account.displayName?.trim() || profileSettings.name.trim() || localName; const displayName = account.displayName?.trim() || window.epMailFeatures.productivity?.profileName?.trim() || localName;
const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2); const initials = displayName.split(/\s+/).filter(Boolean).map(part => part[0]).join('').slice(0, 2);
card.querySelector('.account-avatar').textContent = initials || 'M'; card.querySelector('.account-avatar').textContent = initials || 'M';
card.querySelector('.account-info strong').textContent = displayName; card.querySelector('.account-info strong').textContent = displayName;
@@ -197,7 +205,7 @@ function updateAccountCard(account) {
if (typeof renderLabels === 'function') renderLabels(); if (typeof renderLabels === 'function') renderLabels();
void loadCustomFolders(); void loadCustomFolders();
card.querySelector('.online-dot').style.background = '#70ad7b'; card.querySelector('.online-dot').style.background = '#70ad7b';
const profileButton = $('.top-avatar'); const profileButton = selectMailUi('.top-avatar');
if (profileButton) { if (profileButton) {
profileButton.textContent = initials || 'M'; profileButton.textContent = initials || 'M';
profileButton.title = `${displayName} <${email}>`; profileButton.title = `${displayName} <${email}>`;
@@ -205,38 +213,117 @@ function updateAccountCard(account) {
} }
} }
function openMailAccount(existingAccount = null) { function openMailAccount(existingAccount = null) {
const root = $('#modal-root'); const root = selectMailUi('#modal-root');
const editing = Boolean(existingAccount); const editing = Boolean(existingAccount);
const displayName = existingAccount?.displayName || profileSettings.name || ''; const displayName = existingAccount?.displayName || window.epMailFeatures.productivity?.profileName || '';
const ruleMarkup = (existingAccount?.rules || []).map(rule => ` const ruleMarkup = (existingAccount?.rules || []).map(rule => `
<div class="mail-rule-row"> <div class="mail-rule-row">
<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule.senderContains || '')}"> <input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${escapeMailUi(rule.senderContains || '')}">
<input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule.subjectContains || '')}"> <input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${escapeMailUi(rule.subjectContains || '')}">
<select class="mail-rule-action" aria-label="Rule action"> <select class="mail-rule-action" aria-label="Rule action">
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')} ${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
</select> </select>
${rule.action==='move' ${rule.action==='move'
? `${ruleFolderSelect(rule.value)}` ? `${ruleFolderSelect(rule.value)}`
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`} : `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${escapeMailUi(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button> <button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
</div>`).join(''); </div>`).join('');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${esc(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${esc(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${esc(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${esc(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${esc(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save &amp; reconnect' : 'Test &amp; connect'}</button></div></div></div>`; root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Credentials are stored encrypted. Choose the server's advertised TLS mode and ports.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password / app password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>IMAP port</span><input id="mail-account-imap-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.imapPort || (existingAccount?.authMethod === 'oauth2' ? 993 : 143)}"></label><label class="compose-line mail-security-option"><span>IMAP implicit SSL/TLS (usually port 993)</span><input id="mail-account-imap-secure" type="checkbox"${existingAccount?.imapSecure ? ' checked' : ''}></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>SMTP port</span><input id="mail-account-smtp-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.smtpPort || 587}"></label><label class="compose-line mail-security-option"><span>SMTP implicit SSL/TLS (usually port 465)</span><input id="mail-account-smtp-secure" type="checkbox"${existingAccount?.smtpSecure ? ' checked' : ''}></label><p class="account-note">For IMAP port 143 and SMTP port 587, leave implicit SSL/TLS off to use required STARTTLS. Common Gmail settings are IMAP SSL/TLS on port 993 and SMTP STARTTLS on port 587; use an app password if required by your provider.</p><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save &amp; reconnect' : 'Test &amp; connect'}</button></div></div></div>`;
const authMethodRow = document.createElement('label');
authMethodRow.className = 'compose-line';
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
const emailRow = selectMailUi('#mail-account-email').closest('.compose-line');
emailRow.after(authMethodRow);
const oauthProviderRow = document.createElement('label');
oauthProviderRow.className = 'compose-line';
oauthProviderRow.innerHTML = '<span>Provider</span><select id="mail-account-oauth-provider" class="settings-select"><option value="google">Google</option><option value="microsoft">Microsoft</option></select>';
authMethodRow.after(oauthProviderRow);
const reauthorizeRow = document.createElement('label');
reauthorizeRow.className = 'compose-line';
reauthorizeRow.innerHTML = '<span>Sign in again</span><input id="mail-account-reauthorize" type="checkbox">';
oauthProviderRow.after(reauthorizeRow);
const authMethodSelect = selectMailUi('#mail-account-auth-method');
const oauthProviderSelect = selectMailUi('#mail-account-oauth-provider');
let configuredOAuthProviders = null;
const oauthMethodOption = [...authMethodSelect.options].find(option => option.value === 'oauth2');
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
const imapPortRow = selectMailUi('#mail-account-imap-port').closest('.compose-line');
const imapSecureRow = selectMailUi('#mail-account-imap-secure').closest('.compose-line');
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
const smtpPortRow = selectMailUi('#mail-account-smtp-port').closest('.compose-line');
const smtpSecureRow = selectMailUi('#mail-account-smtp-secure').closest('.compose-line');
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
const setProviderServers = () => {
const servers = oauthProviderSelect.value === 'google'
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
selectMailUi('#mail-account-imap').value = servers.imap;
selectMailUi('#mail-account-imap-port').value = '993';
selectMailUi('#mail-account-imap-secure').checked = true;
selectMailUi('#mail-account-smtp').value = servers.smtp;
selectMailUi('#mail-account-smtp-port').value = '587';
selectMailUi('#mail-account-smtp-secure').checked = false;
};
const updateAuthFields = () => {
const oauth = authMethodSelect.value === 'oauth2';
if (oauth) setProviderServers();
oauthProviderRow.hidden = !oauth;
reauthorizeRow.hidden = !oauth || !editing;
passwordRow.hidden = oauth;
imapRow.hidden = oauth;
imapPortRow.hidden = oauth;
imapSecureRow.hidden = oauth;
smtpRow.hidden = oauth;
smtpPortRow.hidden = oauth;
smtpSecureRow.hidden = oauth;
authNote.textContent = oauth
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
: configuredOAuthProviders && configuredOAuthProviders.size === 0
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
: 'Credentials are stored encrypted. Connections require verified TLS.';
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
? 'Leave blank to keep current password' : 'Enter mailbox password';
};
authMethodSelect.onchange = updateAuthFields;
oauthProviderSelect.onchange = setProviderServers;
updateAuthFields();
if (typeof window.daybreakMail?.listOAuthProviders === 'function') {
window.daybreakMail.listOAuthProviders().then(providers => {
const configured = new Set((providers || []).filter(provider => provider.configured).map(provider => provider.id));
configuredOAuthProviders = configured;
for (const option of oauthProviderSelect.options) option.disabled = !configured.has(option.value) && !(editing && existingAccount?.oauthProvider === option.value);
if (oauthMethodOption) oauthMethodOption.disabled = configured.size === 0 && !(editing && existingAccount?.authMethod === 'oauth2');
if (!existingAccount?.oauthProvider && !configured.has(oauthProviderSelect.value)) {
const available = [...configured][0];
if (available) oauthProviderSelect.value = available;
}
if (authMethodSelect.value === 'oauth2' && oauthProviderSelect.selectedOptions[0]?.disabled) authMethodSelect.value = 'password';
updateAuthFields();
}).catch(() => {});
} else {
authMethodRow.hidden = true;
oauthProviderRow.hidden = true;
}
const close = () => { root.innerHTML = ''; }; const close = () => { root.innerHTML = ''; };
$$('.modal-close').forEach(button => button.onclick = close); selectAllMailUi('.modal-close').forEach(button => button.onclick = close);
$('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); }); selectMailUi('.modal-overlay').addEventListener('click', event => { if (event.target.classList.contains('modal-overlay')) close(); });
$('#disconnect-mail').onclick = close; selectMailUi('#disconnect-mail').onclick = close;
const addRuleRow = rule => { const addRuleRow = rule => {
const row = document.createElement('div'); const row = document.createElement('div');
row.className = 'mail-rule-row'; row.className = 'mail-rule-row';
row.innerHTML = `<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${esc(rule?.senderContains || '')}"><input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${esc(rule?.subjectContains || '')}"><select class="mail-rule-action" aria-label="Rule action"><option value="archive">Archive</option><option value="move">Move to folder</option><option value="label">Apply label</option><option value="flag">Flag</option></select><input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule?.value || '')}"><button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>`; row.innerHTML = `<input class="mail-rule-sender" maxlength="200" aria-label="Sender contains" placeholder="Sender contains" value="${escapeMailUi(rule?.senderContains || '')}"><input class="mail-rule-subject" maxlength="200" aria-label="Subject contains" placeholder="Subject contains" value="${escapeMailUi(rule?.subjectContains || '')}"><select class="mail-rule-action" aria-label="Rule action"><option value="archive">Archive</option><option value="move">Move to folder</option><option value="label">Apply label</option><option value="flag">Flag</option></select><input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${escapeMailUi(rule?.value || '')}"><button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>`;
row.querySelector('.mail-rule-action').value = rule?.action || 'archive'; row.querySelector('.mail-rule-action').value = rule?.action || 'archive';
$('#mail-rule-list').append(row); selectMailUi('#mail-rule-list').append(row);
}; };
$('#add-mail-rule').onclick = () => addRuleRow(); selectMailUi('#add-mail-rule').onclick = () => addRuleRow();
$('#mail-rule-list').onclick = event => { selectMailUi('#mail-rule-list').onclick = event => {
if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove(); if (event.target.closest('.remove-mail-rule')) event.target.closest('.mail-rule-row').remove();
}; };
$('#mail-rule-list').onchange = event => { selectMailUi('#mail-rule-list').onchange = event => {
if (!event.target.matches('.mail-rule-action')) return; if (!event.target.matches('.mail-rule-action')) return;
const row = event.target.closest('.mail-rule-row'); const row = event.target.closest('.mail-rule-row');
const value = row.querySelector('.mail-rule-value'); const value = row.querySelector('.mail-rule-value');
@@ -248,27 +335,45 @@ function openMailAccount(existingAccount = null) {
} }
row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag'; row.querySelector('.mail-rule-value').disabled = event.target.value === 'flag';
}; };
$('#connect-mail').onclick = async () => { selectMailUi('#connect-mail').onclick = async () => {
const button = $('#connect-mail'); const button = selectMailUi('#connect-mail');
const status = $('#mail-account-status'); const status = selectMailUi('#mail-account-status');
const password = $('#mail-account-password').value; const password = selectMailUi('#mail-account-password').value;
const name = $('#mail-account-display-name').value.trim(); const authMethod = authMethodSelect.value;
if (!name) { status.textContent = 'Enter a display name for this mail account.'; $('#mail-account-display-name').focus(); return; } const oauthProvider = oauthProviderSelect.value;
if (!editing && !password) { status.textContent = 'Enter the mailbox password to connect.'; $('#mail-account-password').focus(); return; } const name = selectMailUi('#mail-account-display-name').value.trim();
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
if (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
const imapPort = Number(selectMailUi('#mail-account-imap-port').value);
const smtpPort = Number(selectMailUi('#mail-account-smtp-port').value);
if (authMethod === 'password' && (![imapPort, smtpPort].every(port => Number.isInteger(port) && port >= 1 && port <= 65535))) {
status.textContent = 'Enter valid IMAP and SMTP ports (1–65535).';
return;
}
button.disabled = true; button.disabled = true;
button.textContent = editing ? 'Checking updated settings…' : 'Checking secure connections…'; const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
status.textContent = editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.'; button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
status.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth)
? 'Opening your browser for secure provider sign-in…'
: editing ? 'Testing the updated mailbox settings before saving.' : 'Checking IMAP and SMTP sign-in. This may take a moment.';
try { try {
const details = { const details = {
email: $('#mail-account-email').value, email: selectMailUi('#mail-account-email').value,
password, password,
authMethod,
...(authMethod === 'oauth2' ? { oauthProvider } : {}),
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
displayName: name, displayName: name,
imapHost: $('#mail-account-imap').value, imapHost: selectMailUi('#mail-account-imap').value,
smtpHost: $('#mail-account-smtp').value, imapPort,
signature: $('#mail-account-signature').value, imapSecure: selectMailUi('#mail-account-imap-secure').checked,
notificationsEnabled: $('#mail-account-notifications').checked, smtpHost: selectMailUi('#mail-account-smtp').value,
syncIntervalMinutes: Number($('#mail-account-sync-interval').value), smtpPort,
rules: [...$('#mail-rule-list').querySelectorAll('.mail-rule-row')].map(row => ({ smtpSecure: selectMailUi('#mail-account-smtp-secure').checked,
signature: selectMailUi('#mail-account-signature').value,
notificationsEnabled: selectMailUi('#mail-account-notifications').checked,
syncIntervalMinutes: Number(selectMailUi('#mail-account-sync-interval').value),
rules: [...selectMailUi('#mail-rule-list').querySelectorAll('.mail-rule-row')].map(row => ({
senderContains: row.querySelector('.mail-rule-sender').value, senderContains: row.querySelector('.mail-rule-sender').value,
subjectContains: row.querySelector('.mail-rule-subject').value, subjectContains: row.querySelector('.mail-rule-subject').value,
action: row.querySelector('.mail-rule-action').value, action: row.querySelector('.mail-rule-action').value,
@@ -281,74 +386,72 @@ function openMailAccount(existingAccount = null) {
if (editing) { if (editing) {
const accountList = await window.daybreakMail.listAccounts(); const accountList = await window.daybreakMail.listAccounts();
if (accountList.activeId === account.id) { if (accountList.activeId === account.id) {
connectedMailAccount = account; mailFeatureState.connectedAccount = account;
updateAccountCard(account); updateAccountCard(account);
mailPageOffset = 0; mailFeatureState.pageOffset = 0;
close(); close();
await syncMailbox(false, { offset: 0 }); await syncMailbox(false, { offset: 0 });
} else { } else {
close(); close();
} }
toast('Mailbox settings updated'); toastMailUi('Mailbox settings updated');
} else { } else {
connectedMailAccount = account; mailFeatureState.connectedAccount = account;
updateAccountCard(account); updateAccountCard(account);
close(); close();
toast('Mailbox connected securely'); toastMailUi(authMethod === 'oauth2' ? 'OAuth2 mailbox connected securely' : 'Mailbox connected securely');
await syncMailbox(true); await syncMailbox(true);
} }
} catch (error) { } catch (error) {
status.textContent = error.message || 'Could not connect. Check the account details and try again.'; status.textContent = error.message || 'Could not connect. Check the account details and try again.';
button.disabled = false; button.disabled = false;
button.textContent = editing ? 'Save & reconnect' : 'Test & connect'; button.textContent = authMethod === 'oauth2' ? 'Authorize & connect' : editing ? 'Save & reconnect' : 'Test & connect';
} }
}; };
$('#mail-account-email').focus(); selectMailUi('#mail-account-email').focus();
} }
function mailSearchFilters() { function mailSearchFilters() {
return { return {
query: $('#search').value.trim(), query: selectMailUi('#search').value.trim(),
sender: $('#filter-sender').value.trim(), sender: selectMailUi('#filter-sender').value.trim(),
subject: $('#filter-subject').value.trim(), subject: selectMailUi('#filter-subject').value.trim(),
after: $('#filter-after').value, after: selectMailUi('#filter-after').value,
before: $('#filter-before').value, before: selectMailUi('#filter-before').value,
hasAttachments: $('#filter-attachments').checked, hasAttachments: selectMailUi('#filter-attachments').checked,
folder: $('#filter-folder').value folder: selectMailUi('#filter-folder').value
}; };
} }
const selectedDraftIds = new Set();
async function deleteSelectedDrafts() { async function deleteSelectedDrafts() {
const ids = messages.map(message => String(message.id)).filter(id => selectedDraftIds.has(id)); const ids = rendererState.messages.map(message => String(message.id)).filter(id => mailFeatureState.selectedDraftIds.has(id));
if (!ids.length) { toast('Select one or more drafts first'); return; } if (!ids.length) { toastMailUi('Select one or more drafts first'); return; }
if (!confirm(`Delete ${ids.length} selected draft${ids.length === 1 ? '' : 's'}?`)) return; if (!confirm(`Delete ${ids.length} selected draft${ids.length === 1 ? '' : 's'}?`)) return;
try { try {
for (const id of ids) await window.daybreakMail.deleteDraft(id); for (const id of ids) await window.daybreakMail.deleteDraft(id);
selectedDraftIds.clear(); mailFeatureState.selectedDraftIds.clear();
toast(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`); toastMailUi(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`);
await syncMailbox(false); await syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete the drafts'); } } catch (error) { toastMailUi(error.message || 'Could not delete the drafts'); }
} }
// In the Drafts folder the shared toolbar acts on drafts, which use string ids. // In the Drafts folder the shared toolbar acts on drafts, which use string ids.
document.addEventListener('click', event => { document.addEventListener('click', event => {
if (activeFolder !== 'Drafts') return; if (rendererState.activeFolder !== 'Drafts') return;
const button = event.target.closest('#select-all, #delete-selected, #archive-selected, #mark-unread'); const button = event.target.closest('#select-all, #delete-selected, #archive-selected, #mark-unread');
if (!button) return; if (!button) return;
event.stopImmediatePropagation(); event.stopImmediatePropagation();
if (button.id === 'select-all') { if (button.id === 'select-all') {
const ids = messages.map(message => String(message.id)); const ids = rendererState.messages.map(message => String(message.id));
const all = ids.length && ids.every(id => selectedDraftIds.has(id)); const all = ids.length && ids.every(id => mailFeatureState.selectedDraftIds.has(id));
ids.forEach(id => all ? selectedDraftIds.delete(id) : selectedDraftIds.add(id)); ids.forEach(id => all ? mailFeatureState.selectedDraftIds.delete(id) : mailFeatureState.selectedDraftIds.add(id));
renderDrafts(messages.map(message => message.draft)); renderDrafts(rendererState.messages.map(message => message.draft));
} else if (button.id === 'delete-selected') void deleteSelectedDrafts(); } else if (button.id === 'delete-selected') void deleteSelectedDrafts();
}, true); }, true);
function renderDrafts(drafts) { function renderDrafts(drafts) {
const present = new Set(drafts.map(draft => String(draft.id))); const present = new Set(drafts.map(draft => String(draft.id)));
[...selectedDraftIds].forEach(id => { if (!present.has(id)) selectedDraftIds.delete(id); }); [...mailFeatureState.selectedDraftIds].forEach(id => { if (!present.has(id)) mailFeatureState.selectedDraftIds.delete(id); });
messages.splice(0, messages.length, ...drafts.map(draft => ({ rendererState.messages.splice(0, rendererState.messages.length, ...drafts.map(draft => ({
id: draft.id, id: draft.id,
sender: 'Draft', sender: 'Draft',
email: draft.to || 'No recipient', email: draft.to || 'No recipient',
@@ -360,41 +463,40 @@ function renderDrafts(drafts) {
color: '#dce6df', color: '#dce6df',
draft draft
}))); })));
$('#message-list').innerHTML = messages.length ? messages.map(message => ` selectMailUi('#message-list').innerHTML = rendererState.messages.length ? rendererState.messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div> <div class="message" data-id="${escapeMailUi(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${mailFeatureState.selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div> <div class="message-body"><div class="sender">${escapeMailUi(message.email)}</div><div class="subject">${escapeMailUi(message.subject)}</div><div class="snippet">${escapeMailUi(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span><button type="button" class="icon-button draft-delete" title="Delete draft" aria-label="Delete draft">⌫</button></div></div>`).join('') : <div class="message-meta"><span class="time">${escapeMailUi(message.date)}</span><button type="button" class="icon-button draft-delete" title="Delete draft" aria-label="Delete draft">⌫</button></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>'; '<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft'); const start = selectMailUi('#start-draft');
if (start) start.onclick = () => showCompose(); if (start) start.onclick = () => appShell.showCompose();
$$('.message').forEach(row => row.onclick = event => { selectAllMailUi('.message').forEach(row => row.onclick = event => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft; const draft = rendererState.messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (event.target.closest('.row-check')) { if (event.target.closest('.row-check')) {
event.stopPropagation(); event.stopPropagation();
const id = row.dataset.id; const id = row.dataset.id;
selectedDraftIds.has(id) ? selectedDraftIds.delete(id) : selectedDraftIds.add(id); mailFeatureState.selectedDraftIds.has(id) ? mailFeatureState.selectedDraftIds.delete(id) : mailFeatureState.selectedDraftIds.add(id);
return; return;
} }
if (event.target.closest('.draft-delete')) { if (event.target.closest('.draft-delete')) {
event.stopPropagation(); event.stopPropagation();
if (!draft || !confirm('Delete this draft?')) return; if (!draft || !confirm('Delete this draft?')) return;
window.daybreakMail.deleteDraft(draft.id) window.daybreakMail.deleteDraft(draft.id)
.then(() => { toast('Draft deleted'); return syncMailbox(false); }) .then(() => { toastMailUi('Draft deleted'); return syncMailbox(false); })
.catch(error => toast(error.message || 'Could not delete the draft')); .catch(error => toastMailUi(error.message || 'Could not delete the draft'));
return; return;
} }
if (draft) showCompose(null, false, draft); if (draft) appShell.showCompose(null, false, draft);
}); });
$('#reader-pane').innerHTML = emptyReader(); selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
$('#pagination').textContent = `${messages.length} drafts`; selectMailUi('#pagination').textContent = `${rendererState.messages.length} drafts`;
$('#load-more').classList.add('hidden'); selectMailUi('#load-more').classList.add('hidden');
} }
function setupDraftComposer() { function setupDraftComposer() {
const original = window.showCompose; appShell.wrapShowCompose((original) => (reply, forward = false, draft = null) => {
window.showCompose = (reply, forward = false, draft = null) => {
original(reply, forward); original(reply, forward);
const root = $('#modal-root'); const root = selectMailUi('#modal-root');
const modal = root.querySelector('.compose-modal'); const modal = root.querySelector('.compose-modal');
if (!modal) return; if (!modal) return;
modal.dataset.draftId = draft?.id || ''; modal.dataset.draftId = draft?.id || '';
@@ -441,7 +543,7 @@ function setupDraftComposer() {
remove.onclick = () => { remove.onclick = () => {
attachments.splice(index, 1); attachments.splice(index, 1);
renderAttachments(); renderAttachments();
void persist().catch(error => toast(error.message || 'Could not save the draft')); void persist().catch(error => toastMailUi(error.message || 'Could not save the draft'));
}; };
row.append(name, size, remove); row.append(name, size, remove);
attachmentList.append(row); attachmentList.append(row);
@@ -468,7 +570,7 @@ function setupDraftComposer() {
renderAttachments(); renderAttachments();
await persist(); await persist();
} catch (error) { } catch (error) {
toast(error.message || 'Could not add the selected files'); toastMailUi(error.message || 'Could not add the selected files');
} finally { } finally {
attachmentInput.value = ''; attachmentInput.value = '';
attachButton.disabled = false; attachButton.disabled = false;
@@ -476,10 +578,10 @@ function setupDraftComposer() {
}; };
renderAttachments(); renderAttachments();
if (draft) { if (draft) {
$('#compose-to').value = draft.to || ''; selectMailUi('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || ''; selectMailUi('#compose-cc').value = draft.cc || '';
$('#compose-subject').value = draft.subject || ''; selectMailUi('#compose-subject').value = draft.subject || '';
$('#compose-body').value = draft.text || ''; selectMailUi('#compose-body').value = draft.text || '';
modal.querySelector('.modal-head span').textContent = 'Edit draft'; modal.querySelector('.modal-head span').textContent = 'Edit draft';
} }
const save = document.createElement('button'); const save = document.createElement('button');
@@ -487,17 +589,17 @@ function setupDraftComposer() {
save.className = 'discard'; save.className = 'discard';
save.id = 'save-draft'; save.id = 'save-draft';
save.textContent = 'Save draft'; save.textContent = 'Save draft';
modal.querySelector('.compose-footer').insertBefore(save, $('#send')); modal.querySelector('.compose-footer').insertBefore(save, selectMailUi('#send'));
let saveTimer; let saveTimer;
let closed = false; let closed = false;
const persist = async () => { const persist = async () => {
if (closed || !$('#compose-to')) return; if (closed || !selectMailUi('#compose-to')) return;
const values = { const values = {
id: modal.dataset.draftId || window.crypto.randomUUID(), id: modal.dataset.draftId || window.crypto.randomUUID(),
to: $('#compose-to').value, to: selectMailUi('#compose-to').value,
cc: $('#compose-cc').value, cc: selectMailUi('#compose-cc').value,
subject: $('#compose-subject').value, subject: selectMailUi('#compose-subject').value,
text: $('#compose-body').value, text: selectMailUi('#compose-body').value,
attachments attachments
}; };
if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return; if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
@@ -508,112 +610,112 @@ function setupDraftComposer() {
save.onclick = async () => { save.onclick = async () => {
try { try {
await persist(); await persist();
toast('Draft saved on this device'); toastMailUi('Draft saved on this device');
if (activeFolder === 'Drafts') void syncMailbox(false); if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not save draft'); } } catch (error) { toastMailUi(error.message || 'Could not save draft'); }
}; };
modal.addEventListener('input', () => { modal.addEventListener('input', () => {
clearTimeout(saveTimer); clearTimeout(saveTimer);
saveTimer = setTimeout(() => persist().catch(error => toast(error.message || 'Could not save draft')), 700); saveTimer = setTimeout(() => persist().catch(error => toastMailUi(error.message || 'Could not save draft')), 700);
}); });
modal.querySelector('.modal-overlay')?.addEventListener('click', event => { modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
if (!event.target.classList.contains('modal-overlay')) return; if (!event.target.classList.contains('modal-overlay')) return;
clearTimeout(saveTimer); clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); }) persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft')); .catch(error => toastMailUi(error.message || 'Could not save draft'));
closed = true; closed = true;
}, true); }, true);
root.querySelector('.modal-close')?.addEventListener('click', () => { root.querySelector('.modal-close')?.addEventListener('click', () => {
clearTimeout(saveTimer); clearTimeout(saveTimer);
persist().then(() => { if (activeFolder === 'Drafts') void syncMailbox(false); }) persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
.catch(error => toast(error.message || 'Could not save draft')); .catch(error => toastMailUi(error.message || 'Could not save draft'));
closed = true; closed = true;
}, true); }, true);
$('#discard').onclick = async () => { selectMailUi('#discard').onclick = async () => {
clearTimeout(saveTimer); clearTimeout(saveTimer);
closed = true; closed = true;
try { try {
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId); if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
root.innerHTML = ''; root.innerHTML = '';
if (activeFolder === 'Drafts') void syncMailbox(false); if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete draft'); } } catch (error) { toastMailUi(error.message || 'Could not delete draft'); }
}; };
$('#send').addEventListener('click', () => { selectMailUi('#send').addEventListener('click', () => {
clearTimeout(saveTimer); clearTimeout(saveTimer);
closed = true; closed = true;
}, true); }, true);
}; });
} }
async function syncMailbox(showToast, options = {}) { async function syncMailbox(showToast, options = {}) {
if (mailboxSyncPromise) { if (mailFeatureState.syncPromise) {
mailboxSyncQueued = true; mailFeatureState.syncQueued = true;
return mailboxSyncPromise; return mailFeatureState.syncPromise;
} }
if (!connectedMailAccount || !window.daybreakMail) { if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
openMailAccount(); openMailAccount();
return; return;
} }
const refresh = $('#refresh'); const refresh = selectMailUi('#refresh');
if (refresh) refresh.disabled = true; if (refresh) refresh.disabled = true;
const sync = (async () => { const sync = (async () => {
try { try {
if (activeFolder === 'Drafts') { if (rendererState.activeFolder === 'Drafts') {
const result = await window.daybreakMail.listDrafts(); const result = await window.daybreakMail.listDrafts();
renderDrafts(result.drafts || []); renderDrafts(result.drafts || []);
if (showToast) toast(`${result.drafts.length} saved drafts`); if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
return; return;
} }
const previouslyActiveMessage = activeMessage; const previouslyActiveMessage = rendererState.activeMessage;
const offset = options.offset ?? (options.append ? mailPageOffset + messages.length : mailPageOffset); const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
const result = await window.daybreakMail.syncFolder(activeFolder, offset, mailSearchFilters()); const result = await window.daybreakMail.syncFolder(rendererState.activeFolder, offset, mailSearchFilters());
if (options.append) messages.push(...result.messages); if (options.append) rendererState.messages.push(...result.messages);
else messages.splice(0, messages.length, ...result.messages); else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
messages.forEach(message => { rendererState.messages.forEach(message => {
try { try {
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]'); const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
message.tags = [...new Set([...(message.tags || []), ...localTags])]; message.tags = [...new Set([...(message.tags || []), ...localTags])];
} catch {} } catch {}
}); });
if (!options.append) mailPageOffset = offset; if (!options.append) mailFeatureState.pageOffset = offset;
mailTotal = result.total; mailFeatureState.total = result.total;
activeMessage = messages.some(message => message.id === previouslyActiveMessage) rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
? previouslyActiveMessage ? previouslyActiveMessage
: messages[0]?.id; : rendererState.messages[0]?.id;
selectedIds.clear(); rendererState.selectedIds.clear();
const unread = messages.filter(message => message.unread).length; const unread = rendererState.messages.filter(message => message.unread).length;
const inboxCount = $('.folder[data-folder="Inbox"] .count'); const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
if (inboxCount) inboxCount.textContent = String(unread); if (inboxCount) inboxCount.textContent = String(unread);
const pagination = $('#pagination'); const pagination = selectMailUi('#pagination');
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages'; if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
const loadMore = $('#load-more'); const loadMore = selectMailUi('#load-more');
if (loadMore) loadMore.classList.toggle('hidden', mailPageOffset + messages.length >= result.total); if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total);
query = ''; rendererState.query = '';
renderList(); appShell.renderList();
if (activeMessage) { if (rendererState.activeMessage) {
openMessage(activeMessage); appShell.openMessage(rendererState.activeMessage);
const current = messages.find(message => message.id === activeMessage); const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || activeFolder, action: 'unread', enabled: false }).catch(() => {}); if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
} }
else $('#reader-pane').innerHTML = emptyReader(); else selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
updateAccountCard(connectedMailAccount); updateAccountCard(mailFeatureState.connectedAccount);
const status = $('#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) toast(`Synced ${messages.length} messages`); if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
} catch (error) { } catch (error) {
toast(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;
} }
})(); })();
mailboxSyncPromise = sync; mailFeatureState.syncPromise = sync;
try { try {
await sync; await sync;
} finally { } finally {
mailboxSyncPromise = null; mailFeatureState.syncPromise = null;
if (mailboxSyncQueued) { if (mailFeatureState.syncQueued) {
mailboxSyncQueued = false; mailFeatureState.syncQueued = false;
void syncMailbox(false); void syncMailbox(false);
} }
} }
@@ -623,41 +725,41 @@ if (window.daybreakMail) {
setupDraftComposer(); setupDraftComposer();
let searchTimer; let searchTimer;
const searchControls = ['#search', '#filter-folder', '#filter-sender', '#filter-subject', '#filter-after', '#filter-before', '#filter-attachments']; const searchControls = ['#search', '#filter-folder', '#filter-sender', '#filter-subject', '#filter-after', '#filter-before', '#filter-attachments'];
$('#search-filters-toggle').onclick = () => { selectMailUi('#search-filters-toggle').onclick = () => {
const panel = $('#search-filters'); const panel = selectMailUi('#search-filters');
const expanded = panel.classList.toggle('hidden') === false; const expanded = panel.classList.toggle('hidden') === false;
$('#search-filters-toggle').setAttribute('aria-expanded', String(expanded)); selectMailUi('#search-filters-toggle').setAttribute('aria-expanded', String(expanded));
}; };
$('#clear-search-filters').onclick = () => { selectMailUi('#clear-search-filters').onclick = () => {
$('#filter-folder').value = ''; selectMailUi('#filter-folder').value = '';
$('#filter-sender').value = ''; selectMailUi('#filter-sender').value = '';
$('#filter-subject').value = ''; selectMailUi('#filter-subject').value = '';
$('#filter-after').value = ''; selectMailUi('#filter-after').value = '';
$('#filter-before').value = ''; selectMailUi('#filter-before').value = '';
$('#filter-attachments').checked = false; selectMailUi('#filter-attachments').checked = false;
$('#search').value = ''; selectMailUi('#search').value = '';
activeFolder = folderBeforeSearch || activeFolder; rendererState.activeFolder = mailFeatureState.folderBeforeSearch || rendererState.activeFolder;
folderBeforeSearch = null; mailFeatureState.folderBeforeSearch = null;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder)); selectAllMailUi('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === rendererState.activeFolder));
$('#sidebar-title').textContent = activeFolder; selectMailUi('#sidebar-title').textContent = rendererState.activeFolder;
$('#crumb-current').textContent = activeFolder; selectMailUi('#crumb-current').textContent = rendererState.activeFolder;
query = ''; rendererState.query = '';
renderList(); appShell.renderList();
mailPageOffset = 0; mailFeatureState.pageOffset = 0;
void syncMailbox(false, { offset: 0 }); void syncMailbox(false, { offset: 0 });
}; };
for (const selector of searchControls) { for (const selector of searchControls) {
$(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => { selectMailUi(selector).addEventListener(selector === '#search' ? 'input' : 'change', () => {
if (selector === '#filter-folder' && $('#filter-folder').value) { if (selector === '#filter-folder' && selectMailUi('#filter-folder').value) {
if (!folderBeforeSearch) folderBeforeSearch = activeFolder; if (!mailFeatureState.folderBeforeSearch) mailFeatureState.folderBeforeSearch = rendererState.activeFolder;
activeFolder = $('#filter-folder').value; rendererState.activeFolder = selectMailUi('#filter-folder').value;
$$('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === activeFolder)); selectAllMailUi('.folder').forEach(button => button.classList.toggle('active', button.dataset.folder === rendererState.activeFolder));
$('#sidebar-title').textContent = activeFolder; selectMailUi('#sidebar-title').textContent = rendererState.activeFolder;
$('#crumb-current').textContent = activeFolder; selectMailUi('#crumb-current').textContent = rendererState.activeFolder;
} }
clearTimeout(searchTimer); clearTimeout(searchTimer);
searchTimer = setTimeout(() => { searchTimer = setTimeout(() => {
mailPageOffset = 0; mailFeatureState.pageOffset = 0;
void syncMailbox(false, { offset: 0 }); void syncMailbox(false, { offset: 0 });
}, selector === '#search' ? 350 : 0); }, selector === '#search' ? 350 : 0);
}); });
@@ -668,74 +770,75 @@ if (window.daybreakMail) {
console.error('Could not read app version:', error); console.error('Could not read app version:', error);
}); });
window.daybreakMail.onSyncUpdate(update => { window.daybreakMail.onSyncUpdate(update => {
if (update.accountId !== connectedMailAccount?.id) return; if (update.accountId !== mailFeatureState.connectedAccount?.id) return;
if (update.error) { if (update.error) {
toast(update.error); toastMailUi(update.error);
return; return;
} }
if (update.newCount || (update.foldersChanged || []).length) { if (update.newCount || (update.foldersChanged || []).length) {
if (document.visibilityState === 'visible') { if (document.visibilityState === 'visible') {
syncMailbox(false, update.newCount ? { offset: 0 } : {}); syncMailbox(false, update.newCount ? { offset: 0 } : {});
} }
else mailboxRefreshPending = true; else mailFeatureState.refreshPending = true;
} }
}); });
document.addEventListener('visibilitychange', () => { document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && mailboxRefreshPending) { if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
mailboxRefreshPending = false; mailFeatureState.refreshPending = false;
syncMailbox(false, { offset: 0 }); syncMailbox(false, { offset: 0 });
} }
}); });
window.addEventListener('focus', () => { window.addEventListener('focus', () => {
if (connectedMailAccount) syncMailbox(false); if (mailFeatureState.connectedAccount) syncMailbox(false);
}); });
window.addEventListener('online', () => { window.addEventListener('online', () => {
if (connectedMailAccount) syncMailbox(false, { offset: 0 }); if (mailFeatureState.connectedAccount) syncMailbox(false, { offset: 0 });
}); });
setInterval(() => { setInterval(() => {
if (connectedMailAccount && document.visibilityState === 'visible' && activeView === 'mail') { if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
syncMailbox(false); syncMailbox(false);
} }
}, 60 * 1000); }, 60 * 1000);
$('#account-settings').addEventListener('click', openMailAccount); selectMailUi('#account-settings').addEventListener('click', openMailAccount);
$('#account-settings').addEventListener('keydown', event => { selectMailUi('#account-settings').addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); } if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openMailAccount(); }
}); });
$('#settings-button').onclick = () => openPreferences(); selectMailUi('#refresh').onclick = () => syncMailbox(true);
$('#refresh').onclick = () => syncMailbox(true); selectMailUi('#add-folder').addEventListener('click', createMailFolder);
$('#add-folder').addEventListener('click', createMailFolder); selectAllMailUi('.folder').forEach(button => button.addEventListener('click', () => {
$$('.folder').forEach(button => button.addEventListener('click', () => { if (selectMailUi('#filter-folder').value) {
if ($('#filter-folder').value) { selectMailUi('#filter-folder').value = '';
$('#filter-folder').value = ''; mailFeatureState.folderBeforeSearch = null;
folderBeforeSearch = null;
} }
if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) { if (['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Drafts'].includes(button.dataset.folder)) {
mailPageOffset = 0; mailFeatureState.pageOffset = 0;
syncMailbox(false, { offset: 0 }); syncMailbox(false, { offset: 0 });
} }
})); }));
$('#previous-page').onclick = () => { selectMailUi('#previous-page').onclick = () => {
if (mailPageOffset <= 0) return; if (mailFeatureState.pageOffset <= 0) return;
mailPageOffset = Math.max(0, mailPageOffset - 20); mailFeatureState.pageOffset = Math.max(0, mailFeatureState.pageOffset - 20);
syncMailbox(false, { offset: mailPageOffset }); syncMailbox(false, { offset: mailFeatureState.pageOffset });
}; };
$('#next-page').onclick = () => { selectMailUi('#next-page').onclick = () => {
if (mailPageOffset + 20 >= mailTotal) return; if (mailFeatureState.pageOffset + 20 >= mailFeatureState.total) return;
mailPageOffset += 20; mailFeatureState.pageOffset += 20;
syncMailbox(false, { offset: mailPageOffset }); syncMailbox(false, { offset: mailFeatureState.pageOffset });
}; };
$('#load-more').onclick = () => syncMailbox(false, { append: true }); selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true });
document.addEventListener('click', async event => { document.addEventListener('click', async event => {
const sendButton = event.target.closest('#send'); const sendButton = event.target.closest('#send');
if (!sendButton || !connectedMailAccount) return; if (!sendButton || !mailFeatureState.connectedAccount) return;
event.preventDefault(); event.preventDefault();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
const recipient = $('#compose-to').value.trim(); const recipient = selectMailUi('#compose-to').value.trim();
if (!recipient) { $('#compose-to').focus(); toast('Add a recipient to send your message'); return; } if (!recipient) { selectMailUi('#compose-to').focus(); toastMailUi('Add a recipient to send your message'); return; }
sendButton.disabled = true; sendButton.disabled = true;
sendButton.textContent = 'Sending…'; sendButton.textContent = 'Sending…';
try { try {
const pgp = window.pgpPrepareSend ? await window.pgpPrepareSend(recipient, $('#compose-cc').value) : null; const pgp = window.epMailFeatures.pgp?.prepareSend
? await window.epMailFeatures.pgp.prepareSend(recipient, selectMailUi('#compose-cc').value)
: null;
if (pgp === false) { if (pgp === false) {
sendButton.disabled = false; sendButton.disabled = false;
sendButton.textContent = 'Send ↗'; sendButton.textContent = 'Send ↗';
@@ -743,44 +846,69 @@ if (window.daybreakMail) {
} }
const result = await window.daybreakMail.send({ const result = await window.daybreakMail.send({
to: recipient, to: recipient,
cc: $('#compose-cc').value, cc: selectMailUi('#compose-cc').value,
subject: $('#compose-subject').value.trim(), subject: selectMailUi('#compose-subject').value.trim(),
text: $('#compose-body').value, text: selectMailUi('#compose-body').value,
attachments: $('#modal-root .compose-modal')?._composeAttachments || [], attachments: selectMailUi('#modal-root .compose-modal')?._composeAttachments || [],
displayName: connectedMailAccount.displayName || profileSettings.name, displayName: mailFeatureState.connectedAccount.displayName || window.epMailFeatures.productivity?.profileName || '',
...(pgp ? { pgp } : {}) ...(pgp ? { pgp } : {})
}); });
if (result.failed) { if (result.failed) {
sendButton.disabled = false; sendButton.disabled = false;
sendButton.textContent = 'Send ↗'; sendButton.textContent = 'Send ↗';
toast(result.message || 'Message could not be encrypted'); toastMailUi(result.message || 'Message could not be encrypted');
return; return;
} }
if (result.queued) { if (result.queued) {
const draftId = $('#modal-root .compose-modal')?.dataset.draftId; const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId); if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = ''; selectMailUi('#modal-root').innerHTML = '';
toast('Offline: message queued and will send when connected'); toastMailUi('Offline: message queued and will send when connected');
if (activeFolder === 'Drafts') void syncMailbox(false); if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
return; return;
} }
const draftId = $('#modal-root .compose-modal')?.dataset.draftId; const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
if (draftId) await window.daybreakMail.deleteDraft(draftId); if (draftId) await window.daybreakMail.deleteDraft(draftId);
$('#modal-root').innerHTML = ''; selectMailUi('#modal-root').innerHTML = '';
toast(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved'); toastMailUi(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
if (activeFolder === 'Sent') syncMailbox(false, { offset: 0 }); if (rendererState.activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
if (activeFolder === 'Drafts') void syncMailbox(false); if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
} catch (error) { } catch (error) {
sendButton.disabled = false; sendButton.disabled = false;
sendButton.textContent = 'Send ↗'; sendButton.textContent = 'Send ↗';
toast(error.message || 'Message could not be sent'); toastMailUi(error.message || 'Message could not be sent');
} }
}, true); }, true);
window.daybreakMail.getAccount().then(account => { window.daybreakMail.getAccount().then(account => {
if (!account) return; if (!account) return;
connectedMailAccount = account; mailFeatureState.connectedAccount = account;
updateAccountCard(account); updateAccountCard(account);
syncMailbox(false); syncMailbox(false);
}).catch(() => {}); }).catch(() => {});
} }
const mailUiApi = window.epMailFeatures.modules.createMailUiApi({
state: window.epMailState,
getConnectedAccount: () => mailFeatureState.connectedAccount,
setConnectedAccount: account => { mailFeatureState.connectedAccount = account; },
setPageOffset: offset => { mailFeatureState.pageOffset = offset; },
syncMailbox,
updateAccountCard,
getRenderList: () => appShell.renderList,
getOpenMessage: () => appShell.openMessage,
getShowCompose: () => appShell.showCompose,
baseRenderList: appShell.baseRenderList,
emptyReader: appShell.emptyReader,
openMailAccount,
select: selectMailUi,
selectAll: selectAllMailUi,
toast: toastMailUi,
escapeHtml: escapeMailUi,
getApplyTheme: () => appShell.applyTheme,
setRenderList: renderer => appShell.wrapRenderList(() => renderer),
setOpenMessage: renderer => appShell.wrapOpenMessage(() => renderer),
setShowCompose: renderer => appShell.wrapShowCompose(() => renderer)
});
window.epMailFeatures.mail = mailUiApi;
})();
+11 -4
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.4.4", "version": "0.5.12",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.4.4", "version": "0.5.12",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
@@ -14,8 +14,9 @@
"imapflow": "2.2.1", "imapflow": "2.2.1",
"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",
+11 -4
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.4.4", "version": "0.5.12",
"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",
@@ -25,6 +25,7 @@
"android:sync": "npm run build:android-web && cap sync android", "android:sync": "npm run build:android-web && cap sync android",
"android:open": "npm run android:sync && cap open android", "android:open": "npm run android:sync && cap open android",
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs", "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:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1" "build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
}, },
"devDependencies": { "devDependencies": {
@@ -40,8 +41,12 @@
"files": [ "files": [
"index.html", "index.html",
"platform-bridge.js", "platform-bridge.js",
"platform-bridge-loader.js",
"styles.css", "styles.css",
"branding.css", "branding.css",
"renderer-state.js",
"mail-content-security.js",
"renderer-mail-api.js",
"app.js", "app.js",
"mail-ui.js", "mail-ui.js",
"productivity.js", "productivity.js",
@@ -89,7 +94,8 @@
}, },
"allowScripts": { "allowScripts": {
"electron@44.5.1": true, "electron@44.5.1": true,
"electron-winstaller@5.4.0": true "electron-winstaller@5.4.0": true,
"esbuild@0.28.2": true
}, },
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
@@ -98,7 +104,8 @@
"imapflow": "2.2.1", "imapflow": "2.2.1",
"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"
} }
} }
+69 -39
View File
@@ -1,4 +1,10 @@
(() => {
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store. // Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
const pgpMailUi = window.epMailFeatures.mail;
const selectPgpMailUi = pgpMailUi.select;
const selectAllPgpMailUi = pgpMailUi.selectAll;
const toastPgpMailUi = pgpMailUi.toast;
const escapePgpMailUi = pgpMailUi.escapeHtml;
const pgpApi = () => window.daybreakMail?.pgp; const pgpApi = () => window.daybreakMail?.pgp;
function pgpAskPassphrase(title, detail) { function pgpAskPassphrase(title, detail) {
@@ -38,10 +44,10 @@ function pgpSignatureHtml(signatures, encrypted) {
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.'); if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
if (signature.status === 'valid') { if (signature.status === 'valid') {
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok'; const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${esc(signature.email || 'a known key')}</strong><span>${esc(trust)} · ${esc(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`; return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
} }
if (signature.status === 'unknown-key') { if (signature.status === 'unknown-key') {
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${esc(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`; return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
} }
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`; return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
}).join(''); }).join('');
@@ -52,14 +58,14 @@ async function pgpAddAttachedKey(key) {
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return; if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
try { try {
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' }); const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts'); toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
} catch (error) { } catch (error) {
toast(error.message || 'Could not add the key'); toastPgpMailUi(error.message || 'Could not add the key');
} }
} }
function pgpRenderReaderState(message) { function pgpRenderReaderState(message) {
const reader = $('#reader-pane'); const reader = selectPgpMailUi('#reader-pane');
const header = reader.querySelector('.reader-header'); const header = reader.querySelector('.reader-header');
if (!header) return; if (!header) return;
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
@@ -68,15 +74,21 @@ function pgpRenderReaderState(message) {
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`; html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
} else if (message.encrypted) { } else if (message.encrypted) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true); html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.signed && Array.isArray(message.pgpSignatures)) {
html = pgpSignatureHtml(message.pgpSignatures, false);
} else if (message.signed && message.pgpVerifyFailed) {
html = `<section class="pgp-status pgp-warn" role="status"><strong>Could not check the OpenPGP signature</strong><span>${escapePgpMailUi(message.pgpVerifyFailed)}</span></section>`;
} else if (message.signed) {
html = '<section class="pgp-status pgp-warn" role="status"><strong>Checking OpenPGP signature…</strong><span>Do not rely on this message until verification completes.</span></section>';
} else if (message.pgpSignatures) { } else if (message.pgpSignatures) {
html = pgpSignatureHtml(message.pgpSignatures, false); html = pgpSignatureHtml(message.pgpSignatures, false);
} }
const keys = message.pgpResult?.attachedKeys || []; const keys = message.pgpResult?.attachedKeys || [];
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${esc(key.emails.join(', ') || 'unknown address')} · ${esc(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join('')); header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
reader.querySelectorAll('[data-pgp-key]').forEach(button => { reader.querySelectorAll('[data-pgp-key]').forEach(button => {
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]); button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
}); });
const unlock = $('#pgp-unlock'); const unlock = selectPgpMailUi('#pgp-unlock');
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
} }
@@ -87,7 +99,7 @@ async function pgpUnlockMessage(message, interactive) {
try { try {
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase }); result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
} catch (error) { } catch (error) {
toast(error.message || 'Could not open this message'); toastPgpMailUi(error.message || 'Could not open this message');
return; return;
} }
if (result.ok) { if (result.ok) {
@@ -95,7 +107,7 @@ async function pgpUnlockMessage(message, interactive) {
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys } snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
}); });
if (activeMessage === message.id) openMessage(message.id); if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
return; return;
} }
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') { if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
@@ -104,54 +116,67 @@ async function pgpUnlockMessage(message, interactive) {
if (passphrase === null) return; if (passphrase === null) return;
continue; continue;
} }
const text = $('#pgp-banner-text'); const text = selectPgpMailUi('#pgp-banner-text');
if (text) text.textContent = result.message; if (text) text.textContent = result.message;
else toast(result.message); else toastPgpMailUi(result.message);
return; return;
} }
} }
if (typeof openMessage === 'function') { async function pgpVerifyMessage(message) {
const baseOpenMessage = openMessage; try {
openMessage = function (id) { const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid });
if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.';
else {
message.pgpSignatures = result.signatures || [];
message.pgpVerifyFailed = null;
}
} catch (error) {
message.pgpVerifyFailed = error.message || 'The signature could not be checked.';
}
if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message);
}
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
baseOpenMessage(id); baseOpenMessage(id);
const message = messages.find(item => item.id === id); const message = pgpMailUi.state.messages.find(item => item.id === id);
if (!message || !pgpApi()) return; if (!message || !pgpApi()) return;
pgpRenderReaderState(message); pgpRenderReaderState(message);
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
message.pgpAutoTried = true; message.pgpAutoTried = true;
void pgpUnlockMessage(message, false); void pgpUnlockMessage(message, false);
} }
}; if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) {
message.pgpVerifyTried = true;
void pgpVerifyMessage(message);
} }
});
// Compose: encrypt/sign options. // Compose: encrypt/sign options.
if (typeof showCompose === 'function') { pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
const baseShowCompose = showCompose;
showCompose = function (reply, forward = false) {
baseShowCompose(reply, forward); baseShowCompose(reply, forward);
const footer = $('#modal-root .compose-footer'); const footer = selectPgpMailUi('#modal-root .compose-footer');
if (!footer || !pgpApi()) return; if (!footer || !pgpApi()) return;
const box = document.createElement('div'); const box = document.createElement('div');
box.className = 'pgp-compose'; box.className = 'pgp-compose';
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`; box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
footer.prepend(box); footer.prepend(box);
let touched = false; let touched = false;
const encrypt = $('#pgp-encrypt'); const encrypt = selectPgpMailUi('#pgp-encrypt');
const sign = $('#pgp-sign'); const sign = selectPgpMailUi('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
if (touched) encrypt.dataset.touched = '1'; if (touched) encrypt.dataset.touched = '1';
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; }); encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
let timer = null; let timer = null;
const refresh = async () => { const refresh = async () => {
const to = $('#compose-to')?.value || ''; const to = selectPgpMailUi('#compose-to')?.value || '';
const cc = $('#compose-cc')?.value || ''; const cc = selectPgpMailUi('#compose-cc')?.value || '';
const hint = $('#pgp-hint'); const hint = selectPgpMailUi('#pgp-hint');
if (!hint) return; if (!hint) return;
if (!to.trim()) { hint.textContent = ''; return; } if (!to.trim()) { hint.textContent = ''; return; }
try { try {
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked }); const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
if (!$('#pgp-hint')) return; if (!selectPgpMailUi('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`; if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
else { else {
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients'; hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
@@ -160,23 +185,25 @@ if (typeof showCompose === 'function') {
} catch { hint.textContent = ''; } } catch { hint.textContent = ''; }
}; };
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); }; const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule)); ['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
sign.addEventListener('change', schedule); sign.addEventListener('change', schedule);
schedule(); schedule();
}; });
}
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options. // Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
window.pgpPrepareSend = async function pgpPrepareSend(to, cc) { async function prepareSend(to, cc) {
if (!pgpApi()) return null; if (!pgpApi()) return null;
let encrypt = Boolean($('#pgp-encrypt')?.checked); const plaintextFallback = () => pgpApi().platform === 'android'
const sign = Boolean($('#pgp-sign')?.checked); ? { encrypt: false, sign: false, plaintextFallback: true }
if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null; : null;
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
const status = await pgpApi().checkSend({ to, cc, sign }); const status = await pgpApi().checkSend({ to, cc, sign });
// The default-on update is debounced, so a quick send could skip encryption even though keys exist. // The default-on update is debounced, so a quick send could skip encryption even though keys exist.
if (!encrypt && !status.missing.length && status.recipients.length && $('#pgp-encrypt')?.dataset.touched !== '1') { if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) { if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return null; if (!sign) return plaintextFallback();
} else return false; } else return false;
} }
if (!encrypt && !sign) return null; if (!encrypt && !sign) return null;
@@ -184,15 +211,18 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`); const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
if (!sendPlain) return false; if (!sendPlain) return false;
encrypt = false; encrypt = false;
if (!sign) return null; if (!sign) return plaintextFallback();
} }
let passphrase = null; let passphrase = null;
if (sign) { if (sign) {
if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; } if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
if (!status.signer.unlocked) { if (!status.signer.unlocked) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`); passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false; if (passphrase === null) return false;
} }
} }
return { encrypt, sign, passphrase }; return { encrypt, sign, passphrase };
}; }
window.epMailFeatures.pgp = Object.freeze({ prepareSend });
})();
+81 -65
View File
@@ -1,11 +1,41 @@
(() => {
// Encryption key management (desktop). Hidden where the platform has no key store yet. // Encryption key management (desktop). Hidden where the platform has no key store yet.
const pgpKeyMailUi = window.epMailFeatures.mail;
const selectPgpKeyUi = pgpKeyMailUi.select;
const selectAllPgpKeyUi = pgpKeyMailUi.selectAll;
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
const toastPgpKeyUi = pgpKeyMailUi.toast;
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); } function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
async function saveAndroidPgpExport(label, value) {
if (window.daybreakMail?.pgp?.platform !== 'android' || typeof value !== 'string') return value;
const warning = /private|revocation/i.test(label) ? ' This contains secret key material; keep it private.' : '';
if (!confirm(`Copy this ${label.toLowerCase()} to the clipboard?${warning}`)) return { canceled: true };
if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(value);
else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true };
return { saved: true };
}
function openEncryptionKeys() { function openEncryptionKeys() {
const root = $('#modal-root'); const root = selectPgpKeyUi('#modal-root');
const account = connectedMailAccount || {}; const account = window.epMailFeatures.mail.connectedAccount || {};
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
const serverSettings = androidPgp
? '<h3 class="pgp-heading">Public key servers</h3><p class="account-note">Key-server lookup and publication are disabled in Android testing. Import a public key directly and compare its fingerprint with the owner.</p><div hidden><div id="pgp-server-list"></div><input id="pgp-search-email"><button id="pgp-find-key"></button><div id="pgp-found-keys"></div><select id="pgp-publish-server"></select><input id="pgp-server-name"><input id="pgp-server-url"><select id="pgp-server-protocol"></select><button id="pgp-add-server"></button></div>'
: `<h3 class="pgp-heading">Public key servers</h3>
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
<div class="pgp-actions"><button class="discard" id="pgp-find-key">Search all enabled servers</button></div>
<div id="pgp-found-keys" class="attachment-list"></div>
<label class="compose-line"><span>Publish to one server</span><select id="pgp-publish-server"></select></label>
<p class="account-note">Publishing targets only the selected enabled server. ep-mail names the destination and asks for native confirmation before uploading.</p>
<h4 class="pgp-heading">Add a custom HTTPS server</h4>
<label class="compose-line"><span>Name</span><input id="pgp-server-name" maxlength="60" placeholder="My key server"></label>
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"> root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
<p class="account-note">OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered. Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p> <p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
<div id="pgp-key-list" class="attachment-list">Loading keys…</div> <div id="pgp-key-list" class="attachment-list">Loading keys…</div>
<h3 class="pgp-heading">Change a key passphrase</h3> <h3 class="pgp-heading">Change a key passphrase</h3>
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label> <label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
@@ -15,26 +45,14 @@ function openEncryptionKeys() {
<h3 class="pgp-heading">Contact public keys</h3> <h3 class="pgp-heading">Contact public keys</h3>
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div> <div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div> <div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
<h3 class="pgp-heading">Public key servers</h3> ${serverSettings}
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${esc(account.email || '')}"></label>
<div class="pgp-actions"><button class="discard" id="pgp-find-key">Search all enabled servers</button></div>
<div id="pgp-found-keys" class="attachment-list"></div>
<label class="compose-line"><span>Publish to one server</span><select id="pgp-publish-server"></select></label>
<p class="account-note">Publishing targets only the selected enabled server. ep-mail names the destination and asks for native confirmation before uploading.</p>
<h4 class="pgp-heading">Add a custom HTTPS server</h4>
<label class="compose-line"><span>Name</span><input id="pgp-server-name" maxlength="60" placeholder="My key server"></label>
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>
<h3 class="pgp-heading">Passphrase memory</h3> <h3 class="pgp-heading">Passphrase memory</h3>
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label> <label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div> <div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p> <p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
<h3 class="pgp-heading">Create a key</h3> <h3 class="pgp-heading">Create a key</h3>
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label> <label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${escapePgpKeyUi(account.displayName || '')}"></label>
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${esc(account.email || '')}"></label> <label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label> <label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div> <div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div>
<p class="account-note" id="pgp-status" role="status"></p> <p class="account-note" id="pgp-status" role="status"></p>
@@ -42,13 +60,13 @@ function openEncryptionKeys() {
const close = () => { root.innerHTML = ''; }; const close = () => { root.innerHTML = ''; };
root.querySelector('.modal-close').onclick = close; root.querySelector('.modal-close').onclick = close;
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const status = message => { $('#pgp-status').textContent = message; }; const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
const passphraseField = () => $('#pgp-passphrase'); const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
let keyServers = []; let keyServers = [];
const selectedPublishServer = () => keyServers.find(server => server.id === $('#pgp-publish-server').value && server.enabled); const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
const updatePublishButtons = () => { const updatePublishButtons = () => {
const server = selectedPublishServer(); const server = selectedPublishServer();
$$('.pgp-publish').forEach(button => { selectAllPgpKeyUi('.pgp-publish').forEach(button => {
button.disabled = !server; button.disabled = !server;
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…'; button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
}); });
@@ -60,7 +78,7 @@ function openEncryptionKeys() {
}; };
async function render() { async function render() {
const list = $('#pgp-key-list'); const list = selectPgpKeyUi('#pgp-key-list');
let keys = []; let keys = [];
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; } try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
list.replaceChildren(); list.replaceChildren();
@@ -86,21 +104,21 @@ function openEncryptionKeys() {
changePassphrase.className = 'discard'; changePassphrase.className = 'discard';
changePassphrase.textContent = 'Change passphrase…'; changePassphrase.textContent = 'Change passphrase…';
changePassphrase.onclick = async () => { changePassphrase.onclick = async () => {
const currentPassphrase = $('#pgp-change-current-passphrase').value; const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
if (!currentPassphrase) { if (!currentPassphrase) {
status('Enter the current passphrase for this key.'); status('Enter the current passphrase for this key.');
$('#pgp-change-current-passphrase').focus(); selectPgpKeyUi('#pgp-change-current-passphrase').focus();
return; return;
} }
const newPassphrase = $('#pgp-new-passphrase').value; const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
if (newPassphrase.length < 8) { if (newPassphrase.length < 8) {
status('Use a new passphrase of at least 8 characters.'); status('Use a new passphrase of at least 8 characters.');
$('#pgp-new-passphrase').focus(); selectPgpKeyUi('#pgp-new-passphrase').focus();
return; return;
} }
if (newPassphrase !== $('#pgp-confirm-passphrase').value) { if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
status('The new passphrases do not match.'); status('The new passphrases do not match.');
$('#pgp-confirm-passphrase').focus(); selectPgpKeyUi('#pgp-confirm-passphrase').focus();
return; return;
} }
changePassphrase.disabled = true; changePassphrase.disabled = true;
@@ -110,12 +128,12 @@ function openEncryptionKeys() {
currentPassphrase, currentPassphrase,
newPassphrase newPassphrase
}); });
$('#pgp-change-current-passphrase').value = ''; selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
status(`Passphrase changed for ${key.email || key.fingerprint}.`); status(`Passphrase changed for ${key.email || key.fingerprint}.`);
} catch (error) { status(error.message || 'Could not change the key passphrase.'); } } catch (error) { status(error.message || 'Could not change the key passphrase.'); }
finally { finally {
$('#pgp-new-passphrase').value = ''; selectPgpKeyUi('#pgp-new-passphrase').value = '';
$('#pgp-confirm-passphrase').value = ''; selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
changePassphrase.disabled = false; changePassphrase.disabled = false;
} }
}; };
@@ -134,7 +152,7 @@ function openEncryptionKeys() {
button.onclick = async () => { button.onclick = async () => {
if (secret && !passphraseField().value) { needPassphrase(); return; } if (secret && !passphraseField().value) { needPassphrase(); return; }
try { try {
const result = await run(); const result = await saveAndroidPgpExport(label, await run());
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : ''); status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
} catch (error) { status(error.message || 'That action failed.'); } } catch (error) { status(error.message || 'That action failed.'); }
}; };
@@ -164,30 +182,30 @@ function openEncryptionKeys() {
updatePublishButtons(); updatePublishButtons();
} }
$('#pgp-generate').onclick = async () => { selectPgpKeyUi('#pgp-generate').onclick = async () => {
const button = $('#pgp-generate'); const button = selectPgpKeyUi('#pgp-generate');
button.disabled = true; button.disabled = true;
status('Creating key…'); status('Creating key…');
try { try {
await window.daybreakMail.pgp.generate({ await window.daybreakMail.pgp.generate({
name: $('#pgp-name').value, email: $('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null name: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
}); });
status('Key created. Export your private key and revocation certificate now and keep them safe.'); status('Key created. Export your private key and revocation certificate now and keep them safe.');
await render(); await render();
} catch (error) { status(error.message || 'Could not create the key.'); } } catch (error) { status(error.message || 'Could not create the key.'); }
button.disabled = false; button.disabled = false;
}; };
$('#pgp-import').onclick = async () => { selectPgpKeyUi('#pgp-import').onclick = async () => {
const passphrase = needPassphrase(); const passphrase = needPassphrase();
if (!passphrase) return; if (!passphrase) return;
try { try {
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null }); const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
status(result.canceled ? '' : 'Key imported.'); status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.');
await render(); await render();
} catch (error) { status(error.message || 'Could not import the key.'); } } catch (error) { status(error.message || 'Could not import the key.'); }
}; };
async function renderContacts() { async function renderContacts() {
const list = $('#pgp-contact-list'); const list = selectPgpKeyUi('#pgp-contact-list');
let contacts = []; let contacts = [];
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; } try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
list.replaceChildren(); list.replaceChildren();
@@ -235,7 +253,7 @@ function openEncryptionKeys() {
button.className = 'discard'; button.className = 'discard';
button.textContent = label; button.textContent = label;
button.onclick = async () => { button.onclick = async () => {
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); } try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); }
catch (error) { status(error.message || 'That action failed.'); } catch (error) { status(error.message || 'That action failed.'); }
}; };
row.append(button); row.append(button);
@@ -244,7 +262,7 @@ function openEncryptionKeys() {
}); });
} }
$('#pgp-add-contact').onclick = async () => { selectPgpKeyUi('#pgp-add-contact').onclick = async () => {
try { try {
const result = await window.daybreakMail.pgp.addContact({}); const result = await window.daybreakMail.pgp.addContact({});
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.'); if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
@@ -252,8 +270,8 @@ function openEncryptionKeys() {
} catch (error) { status(error.message || 'Could not import the key.'); } } catch (error) { status(error.message || 'Could not import the key.'); }
}; };
async function renderKeyServers() { async function renderKeyServers() {
const list = $('#pgp-server-list'); const list = selectPgpKeyUi('#pgp-server-list');
const selector = $('#pgp-publish-server'); const selector = selectPgpKeyUi('#pgp-publish-server');
const selectedId = selector.value; const selectedId = selector.value;
try { keyServers = await window.daybreakMail.pgp.keyServers(); } try { keyServers = await window.daybreakMail.pgp.keyServers(); }
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; } catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
@@ -321,14 +339,14 @@ function openEncryptionKeys() {
list.append(row); list.append(row);
}); });
} }
$('#pgp-find-key').onclick = async () => { selectPgpKeyUi('#pgp-find-key').onclick = async () => {
const button = $('#pgp-find-key'); const button = selectPgpKeyUi('#pgp-find-key');
const results = $('#pgp-found-keys'); const results = selectPgpKeyUi('#pgp-found-keys');
button.disabled = true; button.disabled = true;
results.textContent = 'Searching…'; results.textContent = 'Searching…';
try { try {
const found = await window.daybreakMail.pgp.findKey({ const found = await window.daybreakMail.pgp.findKey({
email: $('#pgp-search-email').value email: selectPgpKeyUi('#pgp-search-email').value
}); });
results.replaceChildren(); results.replaceChildren();
found.keys.forEach(key => { found.keys.forEach(key => {
@@ -374,39 +392,37 @@ function openEncryptionKeys() {
status(error.message || 'Could not search the key server.'); status(error.message || 'Could not search the key server.');
} finally { button.disabled = false; } } finally { button.disabled = false; }
}; };
$('#pgp-add-server').onclick = async () => { selectPgpKeyUi('#pgp-add-server').onclick = async () => {
const button = $('#pgp-add-server'); const button = selectPgpKeyUi('#pgp-add-server');
button.disabled = true; button.disabled = true;
try { try {
const result = await window.daybreakMail.pgp.addKeyServer({ const result = await window.daybreakMail.pgp.addKeyServer({
name: $('#pgp-server-name').value, name: selectPgpKeyUi('#pgp-server-name').value,
url: $('#pgp-server-url').value, url: selectPgpKeyUi('#pgp-server-url').value,
protocol: $('#pgp-server-protocol').value protocol: selectPgpKeyUi('#pgp-server-protocol').value
}); });
if (result.canceled) return; if (result.canceled) return;
$('#pgp-server-name').value = ''; selectPgpKeyUi('#pgp-server-name').value = '';
$('#pgp-server-url').value = ''; selectPgpKeyUi('#pgp-server-url').value = '';
await renderKeyServers(); await renderKeyServers();
status('Custom key server added.'); status('Custom key server added.');
} catch (error) { status(error.message || 'Could not add the key server.'); } } catch (error) { status(error.message || 'Could not add the key server.'); }
finally { button.disabled = false; } finally { button.disabled = false; }
}; };
window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {}); window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
$('#pgp-save-cache').onclick = async () => { selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number($('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); } try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number(selectPgpKeyUi('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
catch (error) { status(error.message || 'Could not save the setting.'); } catch (error) { status(error.message || 'Could not save the setting.'); }
}; };
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); }; selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
void renderKeyServers(); if (!androidPgp) void renderKeyServers();
void renderContacts(); void renderContacts();
void render(); void render();
} }
if (typeof openPreferences === 'function') { window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences(); baseOpenPreferences();
const fields = $('#modal-root .compose-fields'); const fields = selectPgpKeyUi('#modal-root .compose-fields');
if (!fields || !pgpAvailable()) return; if (!fields || !pgpAvailable()) return;
const button = document.createElement('button'); const button = document.createElement('button');
button.type = 'button'; button.type = 'button';
@@ -415,5 +431,5 @@ if (typeof openPreferences === 'function') {
button.textContent = 'Encryption keys…'; button.textContent = 'Encryption keys…';
button.onclick = openEncryptionKeys; button.onclick = openEncryptionKeys;
fields.append(button); fields.append(button);
}; });
} })();
+5
View File
@@ -0,0 +1,5 @@
(() => {
// Electron's preload already provides the desktop bridge; avoid parsing the Capacitor bundle there.
if (window.daybreakMail) return;
document.write('<script src="platform-bridge.js"><\/script>');
})();
+10177 -26
View File
File diff suppressed because one or more lines are too long
+88 -28
View File
@@ -1,4 +1,10 @@
(() => {
// Persistent profile, calendar and contact tools, plus actions for the mail UI. // Persistent profile, calendar and contact tools, plus actions for the mail UI.
const productivityMailUi = window.epMailFeatures.mail;
const selectProductivityUi = productivityMailUi.select;
const selectAllProductivityUi = productivityMailUi.selectAll;
const toastProductivityUi = productivityMailUi.toast;
const escapeProductivityUi = productivityMailUi.escapeHtml;
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' }; const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } }; const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value)); const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
@@ -11,39 +17,93 @@ productWrite(productKeys.contacts, savedContacts);
let savedEvents = productRead(productKeys.events, []); let savedEvents = productRead(productKeys.events, []);
let customLabels = productRead(productKeys.labels, []); let customLabels = productRead(productKeys.labels, []);
let snoozedIds = productRead(productKeys.snoozed, []); let snoozedIds = productRead(productKeys.snoozed, []);
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=$('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=$('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (connectedMailAccount) updateAccountCard(connectedMailAccount); } function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=selectProductivityUi('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=selectProductivityUi('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (productivityMailUi.connectedAccount) productivityMailUi.updateAccountCard(productivityMailUi.connectedAccount); }
function openAccountSettings() { function openAccountSettings() {
const root=$('#modal-root'); const root=selectProductivityUi('#modal-root');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${esc(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`; root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
const close=()=>root.innerHTML=''; const close=()=>root.innerHTML='';
$$('.modal-close').forEach(button=>button.onclick=close); selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
$('#save-profile').onclick=()=>{const name=$('#profile-name').value.trim();if(!name){toast('Enter your display name');return}setProfileName(name);close();toast('Account settings saved')}; selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
$('#profile-name').focus(); selectProductivityUi('#profile-name').focus();
} }
function openPreferences() { async function openPreferences() {
const root=$('#modal-root'); const root=selectProductivityUi('#modal-root');
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join(''); const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`; const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled?window.daybreakMail:null;
let notificationPrivacy={showDetails:false};
let appLockSettings={enabled:false,deviceSecure:false};
if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}}
if(appLockBridge){try{appLockSettings=await appLockBridge.getAppLockSettings()}catch(error){toastProductivityUi(error.message||'Could not load app-lock settings');return}}
const notificationSetting=notificationBridge?`<label class="compose-line"><span>Show sender and subject in notifications</span><input id="show-notification-details" type="checkbox"${notificationPrivacy.showDetails?' checked':''}></label><p class="account-note">Off by default. Android still hides private details from lock-screen previews.</p>`:'';
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><p class="account-note">Requires a secure Android screen lock. Mail sync continues in the background; unlock with your device PIN, pattern, or password when you return.</p>`:'';
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
const close=()=>root.innerHTML=''; const close=()=>root.innerHTML='';
$$('.modal-close').forEach(button=>button.onclick=close); selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
$('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
$('#save-appearance').onclick=()=>{applyTheme($('#theme-select').value);close();toast('Appearance saved')}; selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge)await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked);productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}};
$('#theme-select').focus(); selectProductivityUi('#theme-select').focus();
} }
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=$('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${esc(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${esc(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${esc(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${esc(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${esc(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; $$('.modal-close').forEach(b=>b.onclick=close); $('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; $('#save-event').onclick=async()=>{const title=$('#event-name').value.trim(),date=$('#event-date').value;if(!title||!date){toast('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:$('#event-time').value,with:$('#event-people').value.trim(),place:$('#event-place').value.trim(),notes:$('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast(edit?'Event updated':'Event added')}; if(edit) $('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toast('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toast('Event removed')}; $('#event-name').focus(); } function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${esc(e.time?`${e.time} `:'')}${esc(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);$('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${esc(e.title)}</strong><small>${esc(e.time||'All day')}${e.with?` · with ${esc(e.with)}`:''}${e.place?` · ${esc(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;$('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));$('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};$('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};$('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};$('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}} function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${esc(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${esc(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${esc(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';$$('.modal-close').forEach(b=>b.onclick=close);$('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};$('#save-contact').onclick=async()=>{const name=$('#contact-name').value.trim(),email=$('#contact-email').value.trim();if(!name||!email){toast('Add a name and email');return}const item={...(existing||{}),name,email,note:$('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toast('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast(existing?'Contact updated':'Contact saved')};if(existing)$('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toast('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toast('Contact removed')};$('#contact-name').focus()} function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${esc(c.color)}">${esc(c.initials)}</div><div><strong>${esc(c.name)}</strong><span>${esc(c.email)}</span><small>${esc(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${esc(c.name)}">···</button><button class="contact-email" data-email="${esc(c.email)}" aria-label="Email ${esc(c.name)}">↗</button></article>`).join('');$('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;$('#add-contact').onclick=()=>showContact();$('#contact-search').oninput=e=>$$('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));$('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)showCompose({email:email.dataset.email,subject:'',date:''})};$('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toast('Contact removed')}}} function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}}
function accountRuleLabels(){return [...new Set((connectedMailAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
function renderLabels(){const box=$('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${esc(label)}"><i class="label-dot dot-blue"></i>${esc(label)}</button>`).join('');$$('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));activeFolder=b.dataset.label;$('#sidebar-title').textContent=activeFolder;$('#crumb-current').textContent=activeFolder;renderList()})} function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})}
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toast('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toast('Label added')} function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
function messageAction(message,action){if(connectedMailAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toast('Offline: action queued and will sync when connected');return result})}return Promise.resolve()} function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
async function actOnSelected(action){const selected=messages.filter(m=>selectedIds.has(m.id));if(!selected.length){toast('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);selectedIds.clear();renderList();if(action==='archive'||action==='delete')$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toast(e.message||'Could not update messages')}} async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();$$('.profile-button').forEach(b=>b.onclick=openAccountSettings);$('#settings-button').onclick=openPreferences;$('#add-label').onclick=addCustomLabel;$('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')openMailAccount();else if(choice?.toLowerCase()==='refresh')syncMailbox(true)};$('.help-button').onclick=()=>{const root=$('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';$$('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};$('#select-all').onclick=()=>{const rows=$$('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>selectedIds.has(id));ids.forEach(id=>all?selectedIds.delete(id):selectedIds.add(id));renderList()};$('#archive-selected').onclick=()=>actOnSelected('archive');$('#delete-selected').onclick=()=>actOnSelected('delete');$('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=messages.find(x=>x.id===activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;renderList();toast('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toast('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;renderList();toast('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=messages.find(x=>x.id===activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){renderList();openMessage(m.id)}else{renderList();$('#reader-pane').innerHTML=emptyReader();toast(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toast(x.message));return}const star=e.target.closest('.star');if(star){const m=messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;renderList()}).catch(x=>toast(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=messages.find(x=>x.id===Number(row.dataset.id));if(m&&connectedMailAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});$('#load-more').textContent='Load more ↓';}); document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh” to sync, or “account” to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toast(`Labeled ${label}`);renderList()} function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
const baseMessageRenderer=renderList; productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
renderList=function(){if(activeFolder==='Drafts'){$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';$('#start-draft').onclick=()=>showCompose();$('#reader-pane').innerHTML=emptyReader();return}if(activeFolder==='Snoozed'||['Design','Travel','Personal',...customLabels,...accountRuleLabels()].includes(activeFolder)){const folder=activeFolder,original=messages.slice(),keep=messages.filter(m=>folder==='Snoozed'?Boolean(m.snoozedUntil):(m.tags||[]).includes(folder));messages.splice(0,messages.length,...keep);activeFolder='Inbox';baseMessageRenderer();activeFolder=folder;messages.splice(0,messages.length,...original);if(!keep.length)$('#message-list').innerHTML='<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';return}baseMessageRenderer()}; const state = productivityMailUi.state;
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=messages.find(item=>item.id===activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toast('This message has no downloadable attachment');return}if(!message?.uid||!window.daybreakMail?.saveAttachment){toast('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:activeFolder,filename}).then(result=>{if(result.saved)toast('Attachment saved')}).catch(error=>toast(error.message||'Could not save attachment'))},true); if (state.activeFolder === 'Drafts') {
selectProductivityUi('#message-list').innerHTML = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No saved drafts</h3><p>Compose a message to get started.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
selectProductivityUi('#start-draft').onclick = () => productivityMailUi.showCompose();
selectProductivityUi('#reader-pane').innerHTML = productivityMailUi.emptyReader();
return;
}
if (state.activeFolder === 'Snoozed' || ['Design', 'Travel', 'Personal', ...customLabels, ...accountRuleLabels()].includes(state.activeFolder)) {
const folder = state.activeFolder;
const original = state.messages.slice();
const keep = state.messages.filter(message => folder === 'Snoozed' ? Boolean(message.snoozedUntil) : (message.tags || []).includes(folder));
state.messages.splice(0, state.messages.length, ...keep);
state.activeFolder = 'Inbox';
baseMessageRenderer();
state.activeFolder = folder;
state.messages.splice(0, state.messages.length, ...original);
if (!keep.length) selectProductivityUi('#message-list').innerHTML = '<div class="reader-empty"><div><div class="empty-icon">?</div><h3>No messages here</h3><p>Try another folder or label.</p></div></div>';
return;
}
return baseMessageRenderer();
});
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}const decrypted=message?.attachments?.find(file=>file.filename===filename&&file.contentBase64);const saving=decrypted&&window.daybreakMail?.savePgpAttachment?window.daybreakMail.savePgpAttachment(decrypted):message?.uid&&window.daybreakMail?.saveAttachment?window.daybreakMail.saveAttachment({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,filename}):null;if(!saving){toastProductivityUi('Attachment download is available for connected mailbox messages');return}saving.then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
window.epMailFeatures.productivity = Object.freeze({
get events() { return savedEvents; },
set events(value) { savedEvents = value; },
get contacts() { return savedContacts; },
set contacts(value) { savedContacts = value; },
get profileName() { return profileSettings.name; },
productKeys,
productWrite,
renderCalendar,
renderContacts,
showEvent,
showContact,
addMessageLabel,
setProfileName,
openAccountSettings,
get openPreferences() { return openPreferences; },
select: selectProductivityUi,
selectAll: selectAllProductivityUi,
toast: toastProductivityUi,
escapeHtml: escapeProductivityUi,
wrapOpenPreferences(decorator) {
openPreferences = decorator(openPreferences);
}
});
})();
+57
View File
@@ -0,0 +1,57 @@
(function installMailUiApiFactory(root) {
function createMailUiApi({
state,
getConnectedAccount,
setConnectedAccount,
setPageOffset,
syncMailbox,
updateAccountCard,
getRenderList,
getOpenMessage,
getShowCompose,
baseRenderList,
emptyReader,
openMailAccount,
select,
selectAll,
toast,
escapeHtml,
getApplyTheme,
setRenderList,
setOpenMessage,
setShowCompose
}) {
return Object.freeze({
state,
get connectedAccount() { return getConnectedAccount(); },
set connectedAccount(account) { setConnectedAccount(account); },
setPageOffset,
syncMailbox,
updateAccountCard,
get renderList() { return getRenderList(); },
get openMessage() { return getOpenMessage(); },
get showCompose() { return getShowCompose(); },
baseRenderList,
emptyReader,
openMailAccount,
select,
selectAll,
toast,
escapeHtml,
get applyTheme() { return getApplyTheme(); },
wrapRenderList(decorator) { setRenderList(decorator(getRenderList())); },
wrapOpenMessage(decorator) { setOpenMessage(decorator(getOpenMessage())); },
wrapShowCompose(decorator) { setShowCompose(decorator(getShowCompose())); }
});
}
if (typeof module === 'object' && module.exports) {
module.exports = { createMailUiApi };
} else {
root.epMailFeatures = root.epMailFeatures || {};
Object.defineProperty(root.epMailFeatures, 'modules', {
value: Object.freeze({ createMailUiApi }),
enumerable: false
});
}
})(typeof window === 'undefined' ? globalThis : window);
+27
View File
@@ -0,0 +1,27 @@
(function installRendererState(root, createState) {
if (typeof module === 'object' && module.exports) {
module.exports = { createRendererState: createState };
return;
}
createState(root);
})(typeof window === 'undefined' ? globalThis : window, function createRendererState(root) {
const state = {
messages: [],
contacts: [],
activeMessage: 1,
activeFolder: 'Inbox',
activeView: 'mail',
query: '',
toastTimer: null,
selectedIds: new Set()
};
Object.defineProperty(root, 'epMailState', {
value: state,
enumerable: false,
configurable: false,
writable: false
});
return state;
});
+26 -2
View File
@@ -1,10 +1,15 @@
import { Capacitor, registerPlugin } from '@capacitor/core'; import { Capacitor, registerPlugin } from '@capacitor/core';
import { createAndroidPgp } from './android-pgp.js';
const EpMail = registerPlugin('EpMail'); const EpMail = registerPlugin('EpMail');
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
window.daybreakMail = { const daybreakMail = {
getAppVersion: () => EpMail.getAppVersion().then(result => result.version), getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }),
getAppLockSettings: () => EpMail.getAppLockSettings(),
setAppLockEnabled: enabled => EpMail.setAppLockEnabled({ enabled }),
getAccount: () => EpMail.getAccount(), getAccount: () => EpMail.getAccount(),
listAccounts: () => EpMail.listAccounts(), listAccounts: () => EpMail.listAccounts(),
selectAccount: id => EpMail.selectAccount({ id }), selectAccount: id => EpMail.selectAccount({ id }),
@@ -25,7 +30,24 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
previewAttachment: details => EpMail.previewAttachment(details), previewAttachment: details => EpMail.previewAttachment(details),
saveAttachment: details => EpMail.saveAttachment(details), saveAttachment: details => EpMail.saveAttachment(details),
openExternal: url => EpMail.openExternal({ url }), openExternal: url => EpMail.openExternal({ url }),
send: message => EpMail.send(message), send: async message => {
if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) {
if (message?.pgp?.plaintextFallback) {
const { pgp: _options, ...plainMessage } = message;
return EpMail.send({ ...plainMessage, pgpRequested: true });
}
return EpMail.send(message);
}
try {
const { rawBase64, to, from } = await daybreakMail.pgp.buildOutgoing(message);
const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message;
return await EpMail.send({ ...headers, rawBase64, envelope: { from, to }, text: '', attachments: [] });
} catch (error) {
return { failed: true, code: error.code || 'PGP_ERROR', message: error.message || 'Could not encrypt this message.' };
}
},
pgpGetMessageSource: details => EpMail.pgpGetMessageSource(details),
savePgpAttachment: details => EpMail.savePgpAttachment(details),
disconnect: id => EpMail.removeAccount({ id }), disconnect: id => EpMail.removeAccount({ id }),
davList: () => EpMail.davList(), davList: () => EpMail.davList(),
davConnect: config => EpMail.davConnect(config), davConnect: config => EpMail.davConnect(config),
@@ -37,4 +59,6 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
davSaveContact: contact => EpMail.davSaveContact(contact), davSaveContact: contact => EpMail.davSaveContact(contact),
davDeleteContact: remote => EpMail.davDeleteContact(remote) davDeleteContact: remote => EpMail.davDeleteContact(remote)
}; };
daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount() });
window.daybreakMail = daybreakMail;
} }
+578
View File
@@ -0,0 +1,578 @@
import * as openpgp from 'openpgp';
const MAX_KEY_LENGTH = 200000;
const MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
const TRUST = ['unknown', 'trusted', 'verified'];
const encoder = new TextEncoder();
const decoder = new TextDecoder();
function parseAddresses(value) {
return String(value || '').split(',').map(part => {
const text = part.trim();
if (!text) return null;
const match = /^(.*?)\s*<([^<>]+)>$/.exec(text);
const address = (match?.[2] || text).trim().toLowerCase();
const name = (match?.[1] || '').replace(/^"|"$/g, '').trim();
if (!/^[^\s@<>(),;]+@[^\s@<>(),;]+\.[^\s@<>(),;]+$/.test(address)) {
throw new Error(`"${text || 'recipient'}" is not a valid email address.`);
}
return { address, name };
}).filter(Boolean);
}
function emailsOf(key) {
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
}
function splitEntity(value) {
const text = typeof value === 'string' ? value : decoder.decode(value);
const normalized = text.replace(/\r?\n/g, '\r\n');
const split = normalized.indexOf('\r\n\r\n');
if (split < 0) throw new Error('Malformed MIME message.');
const headerText = normalized.slice(0, split);
const body = normalized.slice(split + 4);
const headers = {};
let current = '';
for (const line of headerText.split('\r\n')) {
if (/^[ \t]/.test(line) && current) headers[current] += ` ${line.trim()}`;
else {
const colon = line.indexOf(':');
if (colon > 0) {
current = line.slice(0, colon).trim().toLowerCase();
headers[current] = line.slice(colon + 1).trim();
}
}
}
return { headers, body };
}
function parameter(value, name) {
const match = new RegExp(`(?:^|;)\\s*${name}\\s*=\\s*(?:"([^"]+)"|([^;\\s]+))`, 'i').exec(value || '');
return match?.[1] || match?.[2] || '';
}
function decodePart(body, transferEncoding) {
const value = body.replace(/\r\n--[^\r\n]*$/, '').replace(/\r\n$/, '');
if (/base64/i.test(transferEncoding || '')) {
const compact = value.replace(/[\r\n\t ]/g, '');
const binary = atob(compact);
return Uint8Array.from(binary, char => char.charCodeAt(0));
}
if (/quoted-printable/i.test(transferEncoding || '')) {
const bytes = [];
for (let index = 0; index < value.length; index += 1) {
if (value[index] === '=' && value[index + 1] === '\r' && value[index + 2] === '\n') { index += 2; continue; }
if (value[index] === '=' && /^[0-9a-f]{2}$/i.test(value.slice(index + 1, index + 3))) {
bytes.push(parseInt(value.slice(index + 1, index + 3), 16));
index += 2;
} else bytes.push(value.charCodeAt(index) & 255);
}
return Uint8Array.from(bytes);
}
return encoder.encode(value);
}
function splitMultipart(body, boundary) {
if (!boundary || boundary.length > 200) return [];
const mark = `--${boundary}`;
return body.split(mark).slice(1).filter(part => !part.startsWith('--'))
.map(part => part.replace(/^\r?\n/, '').replace(/\r?\n$/, ''))
.filter(part => part.trim());
}
function parseInnerMime(bytes) {
const result = { body: '', html: '', attachments: [] };
const visit = (source, depth = 0) => {
if (depth > 8) return;
const entity = splitEntity(source);
const type = entity.headers['content-type'] || 'text/plain; charset=utf-8';
const transfer = entity.headers['content-transfer-encoding'] || '';
const disposition = entity.headers['content-disposition'] || '';
const boundary = parameter(type, 'boundary');
if (/^multipart\//i.test(type) && boundary) {
for (const part of splitMultipart(entity.body, boundary)) visit(part, depth + 1);
return;
}
const data = decodePart(entity.body, transfer);
const filename = parameter(disposition, 'filename') || parameter(type, 'name');
if (filename || /^attachment/i.test(disposition)) {
if (result.attachments.length < 50 && data.length <= 25 * 1024 * 1024) {
let binary = '';
for (let index = 0; index < data.length; index += 0x8000) {
binary += String.fromCharCode(...data.subarray(index, index + 0x8000));
}
result.attachments.push({
filename: (filename || 'attachment').replace(/[\\/\r\n\u0000]/g, '').slice(0, 255) || 'attachment',
contentType: type.split(';')[0].trim() || 'application/octet-stream',
size: data.length,
contentBase64: btoa(binary)
});
}
return;
}
const text = decoder.decode(data);
if (/^text\/html/i.test(type) && !result.html) result.html = text.slice(0, 100000);
else if (/^text\/plain/i.test(type) && !result.body) result.body = text.slice(0, 500000);
};
visit(bytes);
return result;
}
async function attachedPublicKeys(attachments) {
const found = [];
for (const file of attachments || []) {
const type = String(file.contentType || '').toLowerCase();
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue;
try {
const binary = atob(file.contentBase64);
const armoredKey = decoder.decode(Uint8Array.from(binary, char => char.charCodeAt(0))).trim();
if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) ||
/-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue;
const key = await openpgp.readKey({ armoredKey });
await key.getPrimaryUser();
found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
if (found.length === 5) break;
} catch { /* ignore malformed, expired or non-public key attachments */ }
}
return found;
}
function randomBoundary() {
const bytes = crypto.getRandomValues(new Uint8Array(18));
return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`;
}
function safeHeader(value, max = 900) {
return String(value || '').replace(/[\r\n\u0000]+/g, ' ').trim().slice(0, max);
}
function formatAddress(entry) {
const address = entry.address;
const name = safeHeader(entry.name, 100).replace(/["\\]/g, ' ');
return name ? `${encodeHeader(name)} <${address}>` : address;
}
function encodeHeader(value) {
const clean = safeHeader(value, 998);
if (/^[\x20-\x7e]*$/.test(clean)) return clean;
return `=?UTF-8?B?${toBase64(encoder.encode(clean))}?=`;
}
function mimeInner(text, attachments) {
const files = Array.isArray(attachments) ? attachments : [];
if (files.length > 50 || files.reduce((total, file) => total + String(file?.contentBase64 || '').length, 0) > 36_000_000) {
throw new Error('The encrypted message attachments exceed the Android testing size limit.');
}
if (!files.length) {
const bytes = encoder.encode(String(text || ''));
let binary = '';
for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
const base64 = btoa(binary).replace(/.{1,76}/g, '$&\r\n').trim();
return `Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${base64}\r\n`;
}
const mark = randomBoundary();
const parts = [`--${mark}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n${String(text || '').replace(/\r?\n/g, '\r\n')}\r\n`];
for (const file of files) {
const filename = safeHeader(file.filename || 'attachment', 180).replace(/["\\]/g, '_') || 'attachment';
const type = String(file.contentType || 'application/octet-stream').toLowerCase();
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(type)) throw new Error(`The content type for ${filename} is invalid.`);
const base64 = String(file.contentBase64 || '').replace(/\s/g, '');
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(base64)) throw new Error(`The contents of ${filename} are invalid.`);
parts.push(`--${mark}\r\nContent-Type: ${type}; name="${filename}"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename="${filename}"\r\n\r\n${base64.replace(/.{1,76}/g, '$&\r\n').trim()}\r\n`);
}
parts.push(`--${mark}--\r\n`);
return `Content-Type: multipart/mixed; boundary="${mark}"\r\n\r\n${parts.join('')}`;
}
function toBase64(bytes) {
let binary = '';
for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
return btoa(binary);
}
function bytesToLatin1(bytes) {
let text = '';
for (let index = 0; index < bytes.length; index += 0x8000) {
text += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return text;
}
function splitSignedMime(source, boundary) {
if (!boundary || boundary.length > 200) return null;
const text = bytesToLatin1(source);
const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
const marks = [...text.matchAll(delimiter)];
if (marks.length < 3) return null;
const contentAfter = mark => {
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
return lineEnd < 0 ? text.length : lineEnd + 1;
};
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n');
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!signature) return null;
return { signed: Uint8Array.from(signed, char => char.charCodeAt(0) & 255), signature };
}
function senderFrom(headers) {
const value = String(headers.from || '');
return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || '').toLowerCase();
}
function invalidSignature() {
return { status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null,
matchesSender: false, keyChanged: false };
}
async function signatureStatuses(signatures, verification, sender) {
const results = [];
for (const signature of signatures || []) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = verification.find(candidate => candidate.key.getKeys()
.some(key => key.getKeyID().toHex().toUpperCase() === keyId));
let status = 'valid';
try { await signature.verified; }
catch { status = known ? 'invalid' : 'unknown-key'; }
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const matchesSender = Boolean(sender && keyEmails.includes(sender));
const changed = Boolean(sender && verification.some(candidate =>
!candidate.entry.own && candidate.entry.emails?.includes(sender) &&
candidate.entry.fingerprint !== known?.entry.fingerprint));
results.push({
status,
keyId,
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {})
});
}
return results;
}
export function createAndroidPgp({ EpMail, getAccount }) {
let storePromise;
const passphrases = new Map();
let cacheMinutes = 10;
async function store() {
if (!storePromise) storePromise = EpMail.pgpLoadStore().then(value => {
const savedMinutes = Number(value?.settings?.cacheMinutes);
if (Number.isFinite(savedMinutes) && savedMinutes >= 0 && savedMinutes <= 1440) cacheMinutes = Math.round(savedMinutes);
return value;
}).catch(error => { storePromise = null; throw error; });
return storePromise.then(value => JSON.parse(JSON.stringify(value)));
}
async function persist(value) {
await EpMail.pgpSaveStore({ store: value });
storePromise = Promise.resolve(JSON.parse(JSON.stringify(value)));
}
function cache(fingerprint, passphrase) {
if (!cacheMinutes) { passphrases.delete(fingerprint); return; }
passphrases.set(fingerprint, { passphrase, expires: Date.now() + cacheMinutes * 60000 });
}
function cached(fingerprint) {
const item = passphrases.get(fingerprint);
if (!item) return null;
if (item.expires <= Date.now()) { passphrases.delete(fingerprint); return null; }
return item.passphrase;
}
function clear(fingerprint) { if (fingerprint) passphrases.delete(fingerprint); else passphrases.clear(); }
function publicInfo(entry) {
return { fingerprint: entry.fingerprint, name: entry.name, email: entry.email, accountId: entry.accountId || null,
createdAt: entry.createdAt, algorithm: entry.algorithm, hasRevocationCertificate: Boolean(entry.revocationCertificate) };
}
async function verificationKeys(data) {
const output = [];
for (const entry of [...data.contacts, ...data.keys.map(key => ({ ...key, emails: [String(key.email).toLowerCase()], trust: 'verified', own: true }))]) {
try { output.push({ entry, key: await openpgp.readKey({ armoredKey: entry.publicKey }) }); } catch { /* malformed records are ignored, never trusted */ }
}
return output;
}
async function addContact({ armoredKey, source = 'import' }) {
const armored = String(armoredKey || '').trim();
if (!armored || armored.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('Import a valid public key (maximum 200 KB).');
const key = await openpgp.readKey({ armoredKey: armored }).catch(() => { throw new Error('That is not a valid OpenPGP public key.'); });
await key.getPrimaryUser().catch(() => { throw new Error('That key is expired, revoked or has no valid user ID.'); });
const fingerprint = key.getFingerprint().toUpperCase();
const emails = emailsOf(key);
const data = await store();
if (data.keys.some(entry => entry.fingerprint === fingerprint)) throw new Error('That is one of your own keys.');
if (data.contacts.some(entry => entry.fingerprint === fingerprint)) throw new Error('That public key is already in your contacts.');
const keyChangedFrom = data.contacts.filter(entry => entry.emails.some(email => emails.includes(email))).map(entry => entry.fingerprint);
if (keyChangedFrom.length && !confirm(`A different public key is already stored for ${emails.join(', ')}.\n\nNew fingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nExisting fingerprint(s):\n${keyChangedFrom.map(value => value.match(/.{1,4}/g).join(' ')).join('\n')}\n\nAdd the new key as an unverified key? Compare fingerprints with the owner before trusting it.`)) {
return { canceled: true, keyChangedFrom };
}
const user = await key.getPrimaryUser();
data.contacts.push({ fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown',
source: ['import', 'message', 'paste'].includes(source) ? source : 'import', addedAt: Date.now(), publicKey: key.armor() });
await persist(data);
return { contact: { fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source, addedAt: Date.now() }, keyChangedFrom };
}
async function resolveRecipients(addresses) {
const data = await store();
const pool = [
...data.contacts.map(entry => ({ ...entry, own: false })),
...data.keys.map(entry => ({ ...entry, emails: [String(entry.email).toLowerCase()], trust: 'verified', own: true }))
];
const resolved = [];
const missing = [];
for (const address of addresses) {
const candidates = pool.filter(entry => entry.emails.includes(address)).sort((a, b) => TRUST.indexOf(b.trust) - TRUST.indexOf(a.trust) || b.addedAt - a.addedAt);
let found = null;
for (const candidate of candidates) {
try { const key = await openpgp.readKey({ armoredKey: candidate.publicKey }); await key.getEncryptionKey(); found = { address, key, fingerprint: candidate.fingerprint, trust: candidate.trust }; break; } catch { /* try next usable key */ }
}
if (found) resolved.push(found); else missing.push(address);
}
return { keys: resolved, missing };
}
async function unlock(fingerprint, passphrase) {
const entry = (await store()).keys.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
try { return await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: entry.privateKey }), passphrase }); }
catch { throw new Error('The passphrase is incorrect.'); }
}
async function signerFor(account, passphrase) {
const data = await store();
const entry = data.keys.find(item => item.email.toLowerCase() === String(account.email).toLowerCase());
if (!entry) throw Object.assign(new Error('Create or import an encryption key for this address first.'), { code: 'NO_SIGNING_KEY' });
const secret = passphrase || cached(entry.fingerprint);
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email} to sign this message.`), { code: 'PASSPHRASE_REQUIRED', fingerprint: entry.fingerprint, email: entry.email });
try { const key = await unlock(entry.fingerprint, secret); cache(entry.fingerprint, secret); return { key, entry }; }
catch { clear(entry.fingerprint); throw Object.assign(new Error('The passphrase is incorrect.'), { code: 'BAD_PASSPHRASE', fingerprint: entry.fingerprint, email: entry.email }); }
}
async function buildOutgoing(message) {
const account = await getAccount();
if (!account?.email) throw new Error('Add a mail account before encrypting messages.');
const to = parseAddresses(message.to);
const cc = parseAddresses(message.cc);
const everyone = [...to, ...cc];
if (!to.length) throw new Error('Add at least one recipient.');
const from = { name: safeHeader(account.displayName || message.displayName || account.email, 100), address: account.email };
const pgp = message.pgp || {};
const data = await store();
let signer = null;
if (pgp.sign) signer = await signerFor(account, pgp.passphrase || null);
const recipientKeys = pgp.encrypt ? await resolveRecipients(everyone.map(item => item.address)) : { keys: [], missing: [] };
if (pgp.encrypt && recipientKeys.missing.length) {
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(', ')}.`), { code: 'NO_RECIPIENT_KEY', missing: recipientKeys.missing });
}
let inner = mimeInner(`${String(message.text || '').slice(0, 500000)}${account.signature ? `\n\n${String(account.signature).slice(0, 5000)}` : ''}`, message.attachments || []);
const headers = [
`From: ${formatAddress(from)}`,
`To: ${to.map(formatAddress).join(', ')}`,
...(cc.length ? [`Cc: ${cc.map(formatAddress).join(', ')}`] : []),
`Subject: ${encodeHeader(message.subject || '(no subject)')}`,
`Date: ${new Date().toUTCString().replace('GMT', '+0000')}`,
`Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`,
'MIME-Version: 1.0'
];
let contentType;
let body;
const boundary = randomBoundary();
if (pgp.encrypt) {
const own = data.keys.find(entry => entry.email.toLowerCase() === account.email.toLowerCase());
const encryptionKeys = [...recipientKeys.keys.map(item => item.key)];
if (own) encryptionKeys.push(await openpgp.readKey({ armoredKey: own.publicKey }));
if (signer && !encryptionKeys.some(key => key.getFingerprint().toUpperCase() === signer.entry.fingerprint)) encryptionKeys.push(await openpgp.readKey({ armoredKey: signer.entry.publicKey }));
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ binary: encoder.encode(inner) }),
encryptionKeys,
signingKeys: signer?.key,
format: 'armored'
});
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`;
body = `--${boundary}\r\nContent-Type: application/pgp-encrypted\r\nContent-Description: PGP/MIME version identification\r\n\r\nVersion: 1\r\n--${boundary}\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\nContent-Description: OpenPGP encrypted message\r\nContent-Disposition: inline; filename="encrypted.asc"\r\n\r\n${String(encrypted).replace(/\r?\n/g, '\r\n')}\r\n--${boundary}--\r\n`;
} else {
if (!pgp.sign || !signer) throw new Error('Choose encryption or signing for this message.');
const signedBytes = encoder.encode(inner.replace(/\r?\n/g, '\r\n'));
const signature = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signer.key, detached: true, format: 'armored' });
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${boundary}"`;
body = `--${boundary}\r\n${decoder.decode(signedBytes)}\r\n--${boundary}\r\nContent-Type: application/pgp-signature; name="signature.asc"\r\nContent-Description: OpenPGP digital signature\r\nContent-Disposition: attachment; filename="signature.asc"\r\n\r\n${String(signature).replace(/\r?\n/g, '\r\n')}\r\n--${boundary}--\r\n`;
}
const raw = encoder.encode(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`);
if (raw.byteLength > MAX_MESSAGE_BYTES) throw new Error('This encrypted message is too large to send.');
return { rawBase64: toBase64(raw), to: everyone.map(item => item.address), from: account.email };
}
async function decryptMessage({ folder = 'Inbox', uid, passphrase = null }) {
try {
const source = await EpMail.pgpGetMessageSource({ folder, uid });
const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0));
if (raw.byteLength > MAX_MESSAGE_BYTES) return { failed: true, code: 'TOO_LARGE', message: 'This encrypted message is too large to open.' };
const text = decoder.decode(raw);
const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(text)?.[0];
if (!armor) return { failed: true, code: 'CORRUPT', message: 'The encrypted part of this message is missing or damaged.' };
const message = await openpgp.readMessage({ armoredMessage: armor }).catch(() => null);
if (!message) return { failed: true, code: 'CORRUPT', message: 'The encrypted part of this message is damaged.' };
const wanted = new Set(message.getEncryptionKeyIDs().map(item => item.toHex().toUpperCase()));
const data = await store();
const candidates = [];
for (const entry of data.keys) {
const key = await openpgp.readKey({ armoredKey: entry.publicKey }).catch(() => null);
if (key?.getKeys().some(item => wanted.has(item.getKeyID().toHex().toUpperCase()))) candidates.push(entry);
}
if (!candidates.length) return { failed: true, code: 'NO_KEY', message: 'None of your keys can decrypt this message.' };
let secret = passphrase;
let selected = candidates[0];
if (!secret) {
selected = candidates.find(entry => cached(entry.fingerprint)) || selected;
secret = cached(selected.fingerprint);
}
if (!secret) return { failed: true, code: 'PASSPHRASE_REQUIRED', fingerprint: selected.fingerprint, email: selected.email, message: 'Enter your key passphrase to read this message.' };
let privateKey;
try { privateKey = await unlock(selected.fingerprint, secret); }
catch { clear(selected.fingerprint); return { failed: true, code: 'BAD_PASSPHRASE', fingerprint: selected.fingerprint, email: selected.email, message: 'The passphrase is incorrect.' }; }
cache(selected.fingerprint, secret);
const verify = await verificationKeys(data);
let decrypted;
try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); }
catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; }
const content = parseInnerMime(decrypted.data);
const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
const attachedKeys = await attachedPublicKeys(content.attachments);
return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html,
links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null,
size: content.attachments[0]?.size || '', signatures, attachedKeys };
} catch (error) {
return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' };
}
}
async function verifyMessage({ folder = 'Inbox', uid }) {
try {
const source = await EpMail.pgpGetMessageSource({ folder, uid });
const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0));
if (raw.byteLength > MAX_MESSAGE_BYTES) {
return { failed: true, code: 'TOO_LARGE', message: 'This signed message is too large to verify.' };
}
const entity = splitEntity(raw);
const contentType = entity.headers['content-type'] || '';
const sender = senderFrom(entity.headers);
const data = await store();
const verification = await verificationKeys(data);
if (/^multipart\/signed/i.test(contentType) &&
parameter(contentType, 'protocol').toLowerCase() === 'application/pgp-signature') {
const parts = splitSignedMime(raw, parameter(contentType, 'boundary'));
if (!parts) return { signatures: [invalidSignature()] };
try {
const result = await openpgp.verify({
message: await openpgp.createMessage({ binary: parts.signed }),
signature: await openpgp.readSignature({ armoredSignature: parts.signature }),
verificationKeys: verification.map(item => item.key)
});
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch { return { signatures: [invalidSignature()] }; }
}
const body = decoder.decode(decodePart(entity.body, entity.headers['content-transfer-encoding']));
const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0];
if (!armored) return { signatures: [] };
try {
const message = await openpgp.readCleartextMessage({ cleartextMessage: armored });
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch { return { signatures: [invalidSignature()] }; }
} catch (error) {
return { failed: true, code: error.code || 'VERIFY_ERROR', message: error.message || 'Could not verify this message.' };
}
}
const api = {
platform: 'android',
async list() { return (await store()).keys.map(publicInfo); },
async generate({ name, email, passphrase, accountId = null }) {
const cleanEmail = String(email || '').trim().toLowerCase();
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.');
const generated = await openpgp.generateKey({ type: 'ecc', curve: 'curve25519Legacy', userIDs: [{ name: safeHeader(name, 100), email: cleanEmail }], passphrase, format: 'armored' });
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
const data = await store();
if (data.keys.some(item => item.fingerprint === key.getFingerprint().toUpperCase())) throw new Error('That key is already in your keyring.');
const entry = { fingerprint: key.getFingerprint().toUpperCase(), name: safeHeader(name, 100), email: cleanEmail, accountId,
createdAt: Date.now(), algorithm: 'Curve25519', privateKey: generated.privateKey, publicKey: generated.publicKey,
revocationCertificate: generated.revocationCertificate };
data.keys.push(entry);
await persist(data);
return { key: publicInfo(entry), revocationCertificate: generated.revocationCertificate };
},
async importKey({ armoredKey, passphrase, accountId = null }) {
if (!armoredKey) armoredKey = prompt('Paste an ASCII-armored OpenPGP private key (up to 200 KB):') || '';
const armored = String(armoredKey).trim();
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.');
const parsed = await openpgp.readPrivateKey({ armoredKey: armored }).catch(() => { throw new Error('That is not a valid OpenPGP private key.'); });
const protectedKey = parsed.isDecrypted() ? await openpgp.encryptKey({ privateKey: parsed, passphrase }) : parsed;
if (!parsed.isDecrypted()) await openpgp.decryptKey({ privateKey: parsed, passphrase }).catch(() => { throw new Error('The passphrase is incorrect.'); });
const publicKey = protectedKey.toPublic();
const user = await protectedKey.getPrimaryUser().catch(() => null);
const entry = { fingerprint: protectedKey.getFingerprint().toUpperCase(), name: user?.user?.userID?.name || '',
email: user?.user?.userID?.email || '', accountId, createdAt: protectedKey.getCreationTime().getTime(),
algorithm: protectedKey.getAlgorithmInfo().algorithm, privateKey: protectedKey.armor(), publicKey: publicKey.armor(), revocationCertificate: null };
const data = await store();
if (data.keys.some(item => item.fingerprint === entry.fingerprint)) throw new Error('That key is already in your keyring.');
data.keys.push(entry); await persist(data); return { key: publicInfo(entry) };
},
async exportPublic(fingerprint) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); return entry.publicKey; },
async exportPrivate(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(fingerprint, passphrase); return entry.privateKey; },
async exportRevocation(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry?.revocationCertificate) throw new Error('No revocation certificate is stored for this key.'); await unlock(fingerprint, passphrase); return entry.revocationCertificate; },
async changePassphrase({ fingerprint, currentPassphrase, newPassphrase }) {
if (String(newPassphrase || '').length < 8) throw new Error('Use a new passphrase of at least 8 characters.');
const data = await store(); const entry = data.keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.');
const secret = await unlock(fingerprint, currentPassphrase); const protectedKey = await openpgp.encryptKey({ privateKey: secret, passphrase: newPassphrase });
entry.privateKey = protectedKey.armor(); await persist(data); clear(fingerprint); return { changed: true };
},
async remove(fingerprint, passphrase) { const data = await store(); const entry = data.keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(fingerprint, passphrase); data.keys = data.keys.filter(item => item.fingerprint !== fingerprint); await persist(data); clear(fingerprint); return { removed: true }; },
async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); },
async addContact(input = {}) {
const armoredKey = input.armoredKey || prompt('Paste an ASCII-armored OpenPGP public key (up to 200 KB):') || '';
return addContact({ ...input, armoredKey });
},
async setTrust(fingerprint, trust) {
if (!TRUST.includes(trust)) throw new Error('Unknown trust level.');
const data = await store(); const contact = data.contacts.find(item => item.fingerprint === fingerprint); if (!contact) throw new Error('That contact key was not found.');
if (TRUST.indexOf(trust) > TRUST.indexOf(contact.trust) && !confirm(`Mark ${contact.emails.join(', ')} as ${trust}?\n\nFingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nOnly continue if you checked this fingerprint with the owner.`)) throw new Error('Trust change cancelled.');
contact.trust = trust; await persist(data); return { ...contact };
},
async removeContact(fingerprint) { const data = await store(); if (!data.contacts.some(item => item.fingerprint === fingerprint)) throw new Error('That contact key was not found.'); data.contacts = data.contacts.filter(item => item.fingerprint !== fingerprint); await persist(data); return { removed: true }; },
async exportContact(fingerprint) { const entry = (await store()).contacts.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That contact key was not found.'); return entry.publicKey; },
async checkSend({ to, cc, sign = false }) {
const addresses = [...parseAddresses(to || ''), ...parseAddresses(cc || '')].map(item => item.address);
const { keys, missing } = await resolveRecipients(addresses);
const account = await getAccount();
const entry = sign ? (await store()).keys.find(item => item.email.toLowerCase() === String(account?.email || '').toLowerCase()) : null;
return { recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })), missing,
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null };
},
decryptMessage,
verifyMessage,
async getSettings() { const data = await store(); return { cacheMinutes }; },
async setSettings({ cacheMinutes: value }) {
const number = Number(value);
if (!Number.isFinite(number) || number < 0 || number > 1440) throw new Error('Choose between 0 and 1440 minutes.');
const data = await store();
cacheMinutes = Math.round(number);
data.settings = { ...(data.settings || {}), cacheMinutes };
await persist(data);
if (!cacheMinutes) clear();
return { cacheMinutes };
},
async forgetPassphrases() { clear(); return { cleared: true }; },
async keyServers() { return []; },
async findKey() { throw new Error('Key-server lookup is not included in Android testing. Import a public key directly.'); },
async addKeyServer() { throw new Error('Key-server support is not included in Android testing.'); },
async removeKeyServer() { throw new Error('Key-server support is not included in Android testing.'); },
async setKeyServerEnabled() { throw new Error('Key-server support is not included in Android testing.'); },
async publishKey() { throw new Error('Key-server support is not included in Android testing.'); },
clearPassphrases: clear,
buildOutgoing
};
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') clear(); });
return api;
}
+11 -1
View File
@@ -1,5 +1,6 @@
const { spawnSync } = require('node:child_process'); const { spawnSync } = require('node:child_process');
const path = require('node:path'); const path = require('node:path');
const fs = require('node:fs');
const androidDir = path.resolve(__dirname, '..', 'android'); const androidDir = path.resolve(__dirname, '..', 'android');
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew'; const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
@@ -12,6 +13,15 @@ const result = spawnSync(gradleWrapper, ['assembleDebug'], {
if (result.error) { if (result.error) {
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`); console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
process.exitCode = 1; process.exitCode = 1;
} else if (result.status !== 0) {
process.exitCode = result.status || 1;
} else { } else {
process.exitCode = result.status ?? 1; const root = path.resolve(__dirname, '..');
const { version } = require(path.join(root, 'package.json'));
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'debug', 'app-debug.apk');
const releaseDir = path.join(root, 'release');
const target = path.join(releaseDir, `ep-mail ${version}-debug.apk`);
fs.mkdirSync(releaseDir, { recursive: true });
fs.copyFileSync(apk, target);
console.log(`Debug APK copied to ${target}`);
} }
+47
View File
@@ -0,0 +1,47 @@
const { spawnSync } = require('node:child_process');
const path = require('node:path');
const fs = require('node:fs');
const requiredSigningVariables = [
'EP_MAIL_ANDROID_STORE_FILE',
'EP_MAIL_ANDROID_STORE_PASSWORD',
'EP_MAIL_ANDROID_KEY_ALIAS',
'EP_MAIL_ANDROID_KEY_PASSWORD'
];
const missing = requiredSigningVariables.filter(name => !process.env[name]);
if (missing.length) {
console.error(`Signed Android release requires these environment variables: ${missing.join(', ')}`);
process.exitCode = 1;
} else if (!path.isAbsolute(process.env.EP_MAIL_ANDROID_STORE_FILE)) {
console.error('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.');
process.exitCode = 1;
} else {
const androidDir = path.resolve(__dirname, '..', 'android');
const gradleWrapper = process.platform === 'win32' ? 'gradlew.bat' : './gradlew';
const result = spawnSync(gradleWrapper, ['assembleRelease'], {
cwd: androidDir,
stdio: 'inherit',
shell: process.platform === 'win32'
});
if (result.error) {
console.error(`Could not start the Android Gradle wrapper: ${result.error.message}`);
process.exitCode = 1;
} else if (result.status !== 0) {
process.exitCode = result.status || 1;
} else {
const root = path.resolve(__dirname, '..');
const { version } = require(path.join(root, 'package.json'));
const apk = path.join(androidDir, 'app', 'build', 'outputs', 'apk', 'release', 'app-release.apk');
const releaseDir = path.join(root, 'release');
const target = path.join(releaseDir, `ep-mail ${version}.apk`);
if (!fs.existsSync(apk)) {
console.error(`Gradle did not produce the expected release APK: ${apk}`);
process.exitCode = 1;
} else {
fs.mkdirSync(releaseDir, { recursive: true });
fs.copyFileSync(apk, target);
console.log(`Signed release APK copied to ${target}`);
}
}
}
+4
View File
@@ -8,6 +8,10 @@ const assets = [
'index.html', 'index.html',
'styles.css', 'styles.css',
'branding.css', 'branding.css',
'platform-bridge-loader.js',
'renderer-state.js',
'mail-content-security.js',
'renderer-mail-api.js',
'app.js', 'app.js',
'mail-ui.js', 'mail-ui.js',
'productivity.js', 'productivity.js',
+4 -4
View File
@@ -1,5 +1,5 @@
const CACHE='ep-mail-v8'; const CACHE='ep-mail-v19';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))}); self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
+26 -21
View File
@@ -1,14 +1,20 @@
(() => {
// Configurable keyboard shortcuts for common mail actions. // Configurable keyboard shortcuts for common mail actions.
const shortcutMailUi = window.epMailFeatures.mail;
const shortcutProductivityUi = window.epMailFeatures.productivity;
const selectShortcutUi = shortcutMailUi.select;
const toastShortcutUi = shortcutMailUi.toast;
const escapeShortcutUi = shortcutMailUi.escapeHtml;
const shortcutStorageKey = 'daybreak-shortcuts'; const shortcutStorageKey = 'daybreak-shortcuts';
const shortcutActions = [ const shortcutActions = [
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() }, { id: 'compose', label: 'Compose', fallback: 'c', run: () => selectShortcutUi('#compose')?.click() },
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() }, { id: 'search', label: 'Search', fallback: '/', run: () => selectShortcutUi('#search')?.focus() },
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() }, { id: 'refresh', label: 'Refresh', fallback: 'r', run: () => selectShortcutUi('#refresh')?.click() },
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() }, { id: 'archive', label: 'Archive message', fallback: 'e', run: () => selectShortcutUi('#reader-archive')?.click() },
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() }, { id: 'delete', label: 'Delete message', fallback: '#', run: () => selectShortcutUi('#reader-delete')?.click() },
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() }, { id: 'star', label: 'Star message', fallback: 's', run: () => selectShortcutUi('#reader-star')?.click() },
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() }, { id: 'reply', label: 'Reply', fallback: 'a', run: () => selectShortcutUi('#reply')?.click() },
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() }, { id: 'forward', label: 'Forward', fallback: 'f', run: () => selectShortcutUi('#forward')?.click() },
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) }, { id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) } { id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
]; ];
@@ -39,16 +45,17 @@ function eventShortcut(event) {
} }
function moveMessageSelection(step) { function moveMessageSelection(step) {
const messages = shortcutMailUi.state.messages;
if (!messages.length) return; if (!messages.length) return;
const index = messages.findIndex(message => message.id === activeMessage); const index = messages.findIndex(message => message.id === shortcutMailUi.state.activeMessage);
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))]; const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); } if (next) { shortcutMailUi.openMessage(next.id); selectShortcutUi(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
} }
document.addEventListener('keydown', event => { document.addEventListener('keydown', event => {
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return; if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
const target = event.target; const target = event.target;
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return; if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || selectShortcutUi('#modal-root')?.children.length) return;
const pressed = eventShortcut(event); const pressed = eventShortcut(event);
if (!pressed) return; if (!pressed) return;
const shortcuts = loadShortcuts(); const shortcuts = loadShortcuts();
@@ -58,18 +65,16 @@ document.addEventListener('keydown', event => {
action.run(); action.run();
}); });
if (typeof openPreferences === 'function') { shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
const baseOpenPreferences = openPreferences;
openPreferences = function () {
baseOpenPreferences(); baseOpenPreferences();
const fields = $('#modal-root .compose-fields'); const fields = selectShortcutUi('#modal-root .compose-fields');
const save = $('#save-appearance'); const save = selectShortcutUi('#save-appearance');
if (!fields || !save) return; if (!fields || !save) return;
const shortcuts = loadShortcuts(); const shortcuts = loadShortcuts();
const section = document.createElement('div'); const section = document.createElement('div');
section.className = 'shortcut-settings'; section.className = 'shortcut-settings';
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action => section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`; `<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
fields.append(section); fields.append(section);
section.addEventListener('keydown', event => { section.addEventListener('keydown', event => {
const input = event.target.closest('.shortcut-input'); const input = event.target.closest('.shortcut-input');
@@ -79,7 +84,7 @@ if (typeof openPreferences === 'function') {
const combo = eventShortcut(event); const combo = eventShortcut(event);
if (combo) input.value = combo; if (combo) input.value = combo;
}); });
$('#reset-shortcuts').onclick = () => { selectShortcutUi('#reset-shortcuts').onclick = () => {
section.querySelectorAll('.shortcut-input').forEach(input => { section.querySelectorAll('.shortcut-input').forEach(input => {
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback; input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
}); });
@@ -91,12 +96,12 @@ if (typeof openPreferences === 'function') {
for (const input of section.querySelectorAll('.shortcut-input')) { for (const input of section.querySelectorAll('.shortcut-input')) {
const value = normalizeShortcut(input.value); const value = normalizeShortcut(input.value);
const label = shortcutActions.find(action => action.id === input.dataset.action).label; const label = shortcutActions.find(action => action.id === input.dataset.action).label;
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; } if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
if (value) used.set(value, label); if (value) used.set(value, label);
values[input.dataset.action] = value; values[input.dataset.action] = value;
} }
localStorage.setItem(shortcutStorageKey, JSON.stringify(values)); localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
baseSave?.call(save, event); baseSave?.call(save, event);
}; };
}; });
} })();
+50 -47
View File
@@ -1,3 +1,7 @@
(() => {
const snoozeMailUi = window.epMailFeatures.mail;
const snoozeProductivityUi = window.epMailFeatures.productivity;
function localDateTimeValue(date) { function localDateTimeValue(date) {
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000); const local = new Date(date.getTime() - date.getTimezoneOffset() * 60000);
return local.toISOString().slice(0, 16); return local.toISOString().slice(0, 16);
@@ -12,12 +16,12 @@ function nextMorning(daysAhead) {
} }
function openSnoozeDialog(items) { function openSnoozeDialog(items) {
const eligible = items.filter(message => message?.uid && connectedMailAccount); const eligible = items.filter(message => message?.uid && snoozeMailUi.connectedAccount);
if (!eligible.length) { if (!eligible.length) {
toast('Snoozing is available for messages in a connected mailbox.'); snoozeMailUi.toast('Snoozing is available for messages in a connected mailbox.');
return; return;
} }
const root = $('#modal-root'); const root = snoozeMailUi.select('#modal-root');
const tomorrow = nextMorning(1); const tomorrow = nextMorning(1);
const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000); const laterToday = new Date(Date.now() + 3 * 60 * 60 * 1000);
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`; root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${eligible.length === 1 ? 'Snooze message' : `Snooze ${eligible.length} messages`}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">The message will be hidden in ep-mail until then; the server copy remains in place.</p><div class="snooze-options" style="display:grid;gap:8px;padding:10px 0"><button class="outline-button" data-snooze-at="${laterToday.getTime()}">In 3 hours · ${laterToday.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}</button><button class="outline-button" data-snooze-at="${tomorrow.getTime()}">Tomorrow · 9:00 AM</button><button class="outline-button" data-snooze-at="${nextMorning(7).getTime()}">Next week · 9:00 AM</button></div><label class="compose-line"><span>Custom reminder</span><input id="snooze-custom-time" type="datetime-local" value="${localDateTimeValue(tomorrow)}"></label><p id="snooze-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="snooze-custom">Set reminder</button></div></div></div>`;
@@ -29,7 +33,7 @@ function openSnoozeDialog(items) {
const schedule = async dueAt => { const schedule = async dueAt => {
if (!Number.isFinite(dueAt) || dueAt <= Date.now()) { if (!Number.isFinite(dueAt) || dueAt <= Date.now()) {
$('#snooze-status').textContent = 'Choose a reminder time in the future.'; snoozeMailUi.select('#snooze-status').textContent = 'Choose a reminder time in the future.';
return; return;
} }
const buttons = [...root.querySelectorAll('button')]; const buttons = [...root.querySelectorAll('button')];
@@ -37,7 +41,7 @@ function openSnoozeDialog(items) {
try { try {
for (const message of eligible) { for (const message of eligible) {
const sourceFolder = message.sourceFolder || const sourceFolder = message.sourceFolder ||
(['Inbox', 'Sent', 'Archive', 'Trash'].includes(activeFolder) ? activeFolder : 'Inbox'); (['Inbox', 'Sent', 'Archive', 'Trash'].includes(snoozeMailUi.state.activeFolder) ? snoozeMailUi.state.activeFolder : 'Inbox');
await window.daybreakMail.setSnooze({ await window.daybreakMail.setSnooze({
uid: message.uid, uid: message.uid,
folder: sourceFolder, folder: sourceFolder,
@@ -47,11 +51,11 @@ function openSnoozeDialog(items) {
}); });
} }
close(); close();
toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`); snoozeMailUi.toast(eligible.length === 1 ? 'Message snoozed' : `${eligible.length} messages snoozed`);
selectedIds.clear(); snoozeMailUi.state.selectedIds.clear();
await syncMailbox(false, { offset: 0 }); await snoozeMailUi.syncMailbox(false, { offset: 0 });
} catch (error) { } catch (error) {
$('#snooze-status').textContent = error.message || 'Could not set the reminder.'; snoozeMailUi.select('#snooze-status').textContent = error.message || 'Could not set the reminder.';
buttons.forEach(button => { button.disabled = false; }); buttons.forEach(button => { button.disabled = false; });
} }
}; };
@@ -59,8 +63,8 @@ function openSnoozeDialog(items) {
root.querySelectorAll('[data-snooze-at]').forEach(button => { root.querySelectorAll('[data-snooze-at]').forEach(button => {
button.onclick = () => schedule(Number(button.dataset.snoozeAt)); button.onclick = () => schedule(Number(button.dataset.snoozeAt));
}); });
$('#snooze-custom').onclick = () => schedule(new Date($('#snooze-custom-time').value).getTime()); snoozeMailUi.select('#snooze-custom').onclick = () => schedule(new Date(snoozeMailUi.select('#snooze-custom-time').value).getTime());
$('#snooze-custom-time').focus(); snoozeMailUi.select('#snooze-custom-time').focus();
} }
function unsnoozeMessage(message) { function unsnoozeMessage(message) {
@@ -70,13 +74,13 @@ function unsnoozeMessage(message) {
sourceFolder, sourceFolder,
dueAt: null dueAt: null
}).then(async () => { }).then(async () => {
toast('Message returned to its mailbox'); snoozeMailUi.toast('Message returned to its mailbox');
await syncMailbox(false, { offset: 0 }); await snoozeMailUi.syncMailbox(false, { offset: 0 });
}).catch(error => toast(error.message || 'Could not return the message')); }).catch(error => snoozeMailUi.toast(error.message || 'Could not return the message'));
} }
function showMessageActions(message) { function showMessageActions(message) {
const root = $('#modal-root'); const root = snoozeMailUi.select('#modal-root');
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`; root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Message actions</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields snooze-options" style="display:grid;gap:8px;padding-bottom:16px"><button class="outline-button" data-message-action="unread">Mark unread</button><button class="outline-button" data-message-action="snooze">Snooze</button><button class="outline-button" data-message-action="label">Add label</button><button class="outline-button" data-message-action="inbox">Move to Inbox</button></div></div></div>`;
root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; }); root.querySelectorAll('.modal-close').forEach(button => button.onclick = () => { root.innerHTML = ''; });
root.querySelector('.modal-overlay').onclick = event => { root.querySelector('.modal-overlay').onclick = event => {
@@ -84,25 +88,24 @@ function showMessageActions(message) {
}; };
} }
const renderListBeforeSnooze = renderList; snoozeMailUi.wrapRenderList(renderListBeforeSnooze => function () {
renderList = function () { if (snoozeMailUi.state.activeFolder === 'Snoozed') {
if (activeFolder === 'Snoozed') { const originalMessages = snoozeMailUi.state.messages.slice();
const originalMessages = messages.slice(); const snoozedMessages = snoozeMailUi.state.messages.filter(message => message.snoozedUntil);
const snoozedMessages = messages.filter(message => message.snoozedUntil); snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...snoozedMessages);
messages.splice(0, messages.length, ...snoozedMessages);
const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]); const originalFlags = snoozedMessages.map(message => [message, message.archived, message.deleted]);
snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; }); snoozedMessages.forEach(message => { message.archived = false; message.deleted = false; });
const folder = activeFolder; const folder = snoozeMailUi.state.activeFolder;
activeFolder = 'Inbox'; snoozeMailUi.state.activeFolder = 'Inbox';
baseMessageRenderer(); snoozeMailUi.baseRenderList();
activeFolder = folder; snoozeMailUi.state.activeFolder = folder;
originalFlags.forEach(([message, archived, deleted]) => { originalFlags.forEach(([message, archived, deleted]) => {
message.archived = archived; message.archived = archived;
message.deleted = deleted; message.deleted = deleted;
}); });
messages.splice(0, messages.length, ...originalMessages); snoozeMailUi.state.messages.splice(0, snoozeMailUi.state.messages.length, ...originalMessages);
for (const row of $$('.message')) { for (const row of snoozeMailUi.selectAll('.message')) {
const message = messages.find(item => item.id === Number(row.dataset.id)); const message = snoozeMailUi.state.messages.find(item => item.id === Number(row.dataset.id));
if (!message?.snoozedUntil) continue; if (!message?.snoozedUntil) continue;
const due = new Date(message.snoozedUntil); const due = new Date(message.snoozedUntil);
row.title = `Reminder ${due.toLocaleString()}`; row.title = `Reminder ${due.toLocaleString()}`;
@@ -111,21 +114,20 @@ renderList = function () {
} }
return; return;
} }
renderListBeforeSnooze(); return renderListBeforeSnooze();
}; });
const openMessageBeforeSnooze = openMessage; snoozeMailUi.wrapOpenMessage(openMessageBeforeSnooze => function (id) {
openMessage = function (id) {
openMessageBeforeSnooze(id); openMessageBeforeSnooze(id);
const message = messages.find(item => item.id === id); const message = snoozeMailUi.state.messages.find(item => item.id === id);
const tools = $('.reader-tools'); const tools = snoozeMailUi.select('.reader-tools');
if (!message || !tools) return; if (!message || !tools) return;
const snoozed = activeFolder === 'Snoozed'; const snoozed = snoozeMailUi.state.activeFolder === 'Snoozed';
tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`); tools.insertAdjacentHTML('afterbegin', `<button class="icon-button" id="${snoozed ? 'reader-unsnooze' : 'reader-snooze'}" title="${snoozed ? 'Return to inbox' : 'Snooze'}">${snoozed ? '↩' : '◷'}</button>`);
}; });
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
$('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>'); snoozeMailUi.select('#mark-unread').insertAdjacentHTML('afterend', '<button class="icon-button" id="snooze-selected" title="Snooze selected messages">◷</button>');
if (window.daybreakMail?.checkSnoozeReminders) { if (window.daybreakMail?.checkSnoozeReminders) {
const checkReminders = () => window.daybreakMail.checkSnoozeReminders() const checkReminders = () => window.daybreakMail.checkSnoozeReminders()
.catch(error => console.error('Could not check mail reminders:', error)); .catch(error => console.error('Could not check mail reminders:', error));
@@ -143,36 +145,37 @@ document.addEventListener('click', event => {
event.preventDefault(); event.preventDefault();
event.stopImmediatePropagation(); event.stopImmediatePropagation();
if (action) { if (action) {
const message = messages.find(item => item.id === activeMessage); const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
$('#modal-root').innerHTML = ''; snoozeMailUi.select('#modal-root').innerHTML = '';
if (!message) return; if (!message) return;
if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]); if (action.dataset.messageAction === 'snooze') openSnoozeDialog([message]);
else if (action.dataset.messageAction === 'label') addMessageLabel(message); else if (action.dataset.messageAction === 'label') snoozeProductivityUi.addMessageLabel(message);
else { else {
const type = action.dataset.messageAction; const type = action.dataset.messageAction;
messageAction(message, type).then(() => { messageAction(message, type).then(() => {
if (type === 'unread') message.unread = true; if (type === 'unread') message.unread = true;
if (type === 'inbox') message.archived = false; if (type === 'inbox') message.archived = false;
renderList(); snoozeMailUi.renderList();
toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox'); snoozeMailUi.toast(type === 'unread' ? 'Marked unread' : 'Moved to Inbox');
}).catch(error => toast(error.message || 'Could not update the message')); }).catch(error => snoozeMailUi.toast(error.message || 'Could not update the message'));
} }
return; return;
} }
if (unsnooze) { if (unsnooze) {
const message = messages.find(item => item.id === activeMessage); const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
if (message) unsnoozeMessage(message); if (message) unsnoozeMessage(message);
return; return;
} }
if (snooze?.id === 'snooze-selected') { if (snooze?.id === 'snooze-selected') {
openSnoozeDialog(messages.filter(message => selectedIds.has(message.id))); openSnoozeDialog(snoozeMailUi.state.messages.filter(message => snoozeMailUi.state.selectedIds.has(message.id)));
return; return;
} }
if (more) { if (more) {
const message = messages.find(item => item.id === activeMessage); const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
if (message) showMessageActions(message); if (message) showMessageActions(message);
return; return;
} }
const message = messages.find(item => item.id === activeMessage); const message = snoozeMailUi.state.messages.find(item => item.id === snoozeMailUi.state.activeMessage);
if (message) openSnoozeDialog([message]); if (message) openSnoozeDialog([message]);
}, true); }, true);
})();
+93 -2
View File
File diff suppressed because one or more lines are too long
+38
View File
@@ -0,0 +1,38 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { createAccountStore } = require('../desktop/account-store.cjs');
test('account store migrates a legacy single-account record and persists its generated id', async () => {
let stored = { email: 'user@example.com', password: 'secret' };
let saves = 0;
const repository = createAccountStore({
async load() { return stored; },
async save(value) { stored = value; saves += 1; }
}, { createId: () => 'migrated-account' });
assert.deepEqual(await repository.load(), {
accounts: [{ email: 'user@example.com', password: 'secret', id: 'migrated-account' }],
activeId: 'migrated-account'
});
assert.equal(saves, 1);
assert.equal(stored.activeId, 'migrated-account');
});
test('account store retains current account records without rewriting them', async () => {
const stored = { accounts: [{ id: 'account-1', email: 'user@example.com' }], activeId: 'account-1' };
let saves = 0;
const repository = createAccountStore({
async load() { return stored; },
async save() { saves += 1; }
});
assert.equal(await repository.load(), stored);
assert.equal(saves, 0);
});
test('account store distinguishes missing records from invalid store failures', async () => {
const missing = createAccountStore({ async load() { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); } });
const broken = createAccountStore({ async load() { throw new Error('decrypt failed'); } });
assert.equal(await missing.load(), null);
await assert.rejects(() => broken.load(), /decrypt failed/);
});
+160
View File
@@ -0,0 +1,160 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const vm = require('node:vm');
const esbuild = require('esbuild');
const openpgp = require('openpgp');
const { simpleParser } = require('mailparser');
const { webcrypto } = require('node:crypto');
global.crypto ||= webcrypto;
global.document ||= { addEventListener() {} };
const bundled = esbuild.buildSync({
entryPoints: [path.join(__dirname, '..', 'scripts', 'android-pgp.js')],
bundle: true,
platform: 'browser',
format: 'iife',
globalName: 'AndroidPgpInteropBundle',
write: false
}).outputFiles[0].text;
vm.runInThisContext(bundled);
const { createAndroidPgp } = global.AndroidPgpInteropBundle;
const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe']
.filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0);
const skip = gpgPath ? false : 'GnuPG is not installed';
const PASSPHRASE = 'Android GnuPG test passphrase';
function makeEndpoint(account) {
const vault = { keys: [], contacts: [], settings: {} };
let messageSource = null;
const EpMail = {
async pgpLoadStore() { return JSON.parse(JSON.stringify(vault)); },
async pgpSaveStore({ store }) { Object.assign(vault, JSON.parse(JSON.stringify(store))); return { ok: true }; },
async pgpGetMessageSource() { return messageSource; }
};
return {
api: createAndroidPgp({ EpMail, getAccount: async () => account }),
setMessage(rawBase64) { messageSource = { rawBase64 }; }
};
}
function setupGpg() {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-android-gnupg-'));
const gpg = (args, input) => {
const result = spawnSync(gpgPath, [
'--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback',
'--passphrase', PASSPHRASE, '--trust-model', 'always', ...args
], { input });
if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`);
return { out: result.stdout, err: result.stderr.toString() };
};
gpg(['--quick-generate-key', 'Gina Gnu <gina@example.test>', 'ed25519', 'cert', 'never']);
const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(
gpg(['--list-keys', '--with-colons', 'gina@example.test']).out.toString()
)?.[1];
if (!fingerprint) throw new Error('Could not find the generated GnuPG test key fingerprint.');
gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']);
gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']);
return { home, fingerprint, gpg };
}
function encryptedMime(from, to, armor) {
const boundary = 'android-gnupg-encrypted';
return Buffer.from([
`From: ${from}`,
`To: ${to}`,
'Subject: Android GnuPG interoperability',
'MIME-Version: 1.0',
`Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`,
'',
`--${boundary}`,
'Content-Type: application/pgp-encrypted',
'',
'Version: 1',
`--${boundary}`,
'Content-Type: application/octet-stream; name="encrypted.asc"',
'',
armor.trim(),
`--${boundary}--`,
''
].join('\r\n'));
}
test('Android OpenPGP PGP/MIME interoperates with GnuPG for send, read, and signature verification', { skip }, async () => {
const { home, fingerprint, gpg } = setupGpg();
try {
const android = makeEndpoint({ email: 'android@example.test', displayName: 'Android User', signature: '' });
const own = await android.api.generate({
name: 'Android User', email: 'android@example.test', passphrase: 'android key test passphrase'
});
const gpgPublic = gpg(['--armor', '--export', 'gina@example.test']).out.toString();
await android.api.addContact({ armoredKey: gpgPublic });
gpg(['--import'], Buffer.from(await android.api.exportPublic(own.key.fingerprint)));
const outgoing = await android.api.buildOutgoing({
to: 'Gina Gnu <gina@example.test>',
cc: '',
subject: 'Android to GnuPG',
text: 'Encrypted and signed from the Android OpenPGP module',
messageId: '<android-to-gnupg@example.test>',
pgp: { encrypt: true, sign: true, passphrase: 'android key test passphrase' },
attachments: []
});
const outboundText = Buffer.from(outgoing.rawBase64, 'base64').toString('utf8');
const outboundArmor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(outboundText)?.[0];
assert.ok(outboundArmor, 'Android output should contain an armored encrypted message');
const decrypted = gpg(['--decrypt'], Buffer.from(outboundArmor));
assert.match((await simpleParser(decrypted.out)).text, /Encrypted and signed from the Android OpenPGP module/);
assert.match(decrypted.err, /Good signature from/);
const incomingInner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nSigned and encrypted by GnuPG\r\n');
const incomingArmor = gpg([
'--armor', '--encrypt', '--sign', '--local-user', 'gina@example.test', '--recipient', 'android@example.test'
], incomingInner).out.toString();
android.setMessage(encryptedMime('Gina Gnu <gina@example.test>', 'android@example.test', incomingArmor).toString('base64'));
const opened = await android.api.decryptMessage({ folder: 'Inbox', uid: 11, passphrase: 'android key test passphrase' });
assert.equal(opened.ok, true, opened.message);
assert.deepEqual(opened.body, ['Signed and encrypted by GnuPG']);
assert.equal(opened.signatures[0].status, 'valid');
assert.equal(opened.signatures[0].matchesSender, true);
const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nGnuPG detached signed body';
const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.test'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim();
const signedBoundary = 'android-gnupg-signed';
const signedMime = Buffer.from([
'From: Gina Gnu <gina@example.test>',
'To: android@example.test',
'MIME-Version: 1.0',
`Content-Type: multipart/signed; protocol="application/pgp-signature"; boundary="${signedBoundary}"`,
'',
`--${signedBoundary}`,
signedPart,
`--${signedBoundary}`,
'Content-Type: application/pgp-signature',
'',
detached,
`--${signedBoundary}--`,
''
].join('\r\n'));
android.setMessage(signedMime.toString('base64'));
const signedMimeResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 12 });
assert.equal(signedMimeResult.signatures[0].status, 'valid');
assert.equal(signedMimeResult.signatures[0].matchesSender, true);
const clearSigned = gpg(['--clearsign', '--local-user', 'gina@example.test'], Buffer.from('GnuPG clear-signed body\n')).out.toString();
const clearSource = Buffer.from(
`From: Gina Gnu <gina@example.test>\r\nTo: android@example.test\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${clearSigned}\r\n`
);
android.setMessage(clearSource.toString('base64'));
const clearResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 13 });
assert.equal(clearResult.signatures[0].status, 'valid');
assert.equal(clearResult.signatures[0].matchesSender, true);
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
});
+169
View File
@@ -0,0 +1,169 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const vm = require('node:vm');
const esbuild = require('esbuild');
const { webcrypto } = require('node:crypto');
const openpgp = require('openpgp');
global.crypto ||= webcrypto;
global.document ||= { addEventListener() {} };
const bundled = esbuild.buildSync({
entryPoints: [path.join(__dirname, '..', 'scripts', 'android-pgp.js')],
bundle: true,
platform: 'browser',
format: 'iife',
globalName: 'AndroidPgpBundle',
write: false
}).outputFiles[0].text;
vm.runInThisContext(bundled);
const { createAndroidPgp } = global.AndroidPgpBundle;
function makeEndpoint(account) {
const vault = { keys: [], contacts: [], settings: {} };
let messageSource = null;
const EpMail = {
async pgpLoadStore() { return JSON.parse(JSON.stringify(vault)); },
async pgpSaveStore({ store }) { Object.assign(vault, JSON.parse(JSON.stringify(store))); return { ok: true }; },
async pgpGetMessageSource() { return messageSource; }
};
return {
api: createAndroidPgp({ EpMail, getAccount: async () => account }),
setMessage(value) { messageSource = value; },
vault
};
}
test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const thirdParty = makeEndpoint({ email: 'charlie@example.test', displayName: 'Charlie', signature: '' });
const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
const charlie = await thirdParty.api.generate({ name: 'Charlie', email: 'charlie@example.test', passphrase: 'charlie test passphrase' });
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) });
const built = await sender.api.buildOutgoing({
to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
attachments: [
{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') },
{ filename: 'charlie.asc', contentType: 'application/pgp-keys', contentBase64: Buffer.from(await thirdParty.api.exportPublic(charlie.key.fingerprint)).toString('base64') }
]
});
assert.ok(built.rawBase64);
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
assert.match(raw, /multipart\/encrypted; protocol="application\/pgp-encrypted"/i);
assert.doesNotMatch(raw, /hello from Android|private attachment/);
recipient.setMessage({ rawBase64: built.rawBase64 });
const promptRequired = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7 });
assert.equal(promptRequired.code, 'PASSPHRASE_REQUIRED');
const badPassphrase = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7, passphrase: 'wrong passphrase' });
assert.equal(badPassphrase.code, 'BAD_PASSPHRASE');
const opened = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7, passphrase: 'bob test passphrase' });
assert.equal(opened.ok, true, opened.message);
assert.deepEqual(opened.body, ['hello from Android']);
assert.equal(opened.attachments[0].filename, 'note.txt');
assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment');
assert.equal(opened.attachedKeys[0].fingerprint, charlie.key.fingerprint);
assert.deepEqual(opened.attachedKeys[0].emails, ['charlie@example.test']);
assert.equal(opened.signatures[0].status, 'valid');
await recipient.api.setSettings({ cacheMinutes: 0 });
assert.equal((await recipient.api.getSettings()).cacheMinutes, 0);
assert.equal((await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7 })).code, 'PASSPHRASE_REQUIRED');
});
test('Android OpenPGP refuses encryption when any recipient key is missing', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
await assert.rejects(sender.api.buildOutgoing({
to: 'nobody@example.test', text: 'must not escape as plaintext', pgp: { encrypt: true }, attachments: []
}), error => error.code === 'NO_RECIPIENT_KEY');
});
test('Android verifies PGP/MIME signed-only and clear-signed mail', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) });
const signedMime = await sender.api.buildOutgoing({
to: 'Bob <bob@example.test>', cc: '', subject: 'Signed note', text: 'signed MIME body',
pgp: { encrypt: false, sign: true, passphrase: 'alice test passphrase' }, attachments: []
});
recipient.setMessage({ rawBase64: signedMime.rawBase64 });
const mimeResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 8 });
assert.equal(mimeResult.signatures[0].status, 'valid');
assert.equal(mimeResult.signatures[0].matchesSender, true);
const protectedPrivateKey = await sender.api.exportPrivate(created.key.fingerprint, 'alice test passphrase');
const signingKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: protectedPrivateKey }),
passphrase: 'alice test passphrase'
});
const cleartext = await openpgp.createCleartextMessage({ text: 'clear-signed body' });
const clearSigned = await openpgp.sign({ message: cleartext, signingKeys: signingKey });
const raw = [
'From: Alice <alice@example.test>',
'To: Bob <bob@example.test>',
'Subject: Clear-signed note',
'Content-Type: text/plain; charset=utf-8',
'',
clearSigned,
''
].join('\r\n');
recipient.setMessage({ rawBase64: Buffer.from(raw).toString('base64') });
const clearResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 9 });
assert.equal(clearResult.signatures[0].status, 'valid');
assert.equal(clearResult.signatures[0].matchesSender, true);
});
test('Android marks a damaged PGP/MIME signature invalid', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) });
const signed = await sender.api.buildOutgoing({
to: 'bob@example.test', subject: 'Signed', text: 'change me',
pgp: { sign: true, passphrase: 'alice test passphrase' }, attachments: []
});
const raw = Buffer.from(signed.rawBase64, 'base64').toString('utf8');
const armor = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(raw)?.[0];
const signatureLine = armor?.split(/\r?\n/).find(line => /^[A-Za-z0-9+/]{20,}$/.test(line));
assert.ok(signatureLine, 'signed MIME output should contain an armored signature');
const tampered = raw.replace(signatureLine, `${signatureLine[0] === 'A' ? 'B' : 'A'}${signatureLine.slice(1)}`);
recipient.setMessage({ rawBase64: Buffer.from(tampered).toString('base64') });
const result = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 10 });
assert.equal(result.signatures[0].status, 'invalid');
});
test('Android rejects tampered, malformed, and oversized encrypted input', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
const built = await sender.api.buildOutgoing({
to: 'bob@example.test', subject: 'Encrypted test', text: 'tamper test',
pgp: { encrypt: true }, attachments: []
});
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(raw)?.[0];
assert.ok(armor);
const lines = armor.split(/\r?\n/);
const armorLineIndex = lines.findIndex(line => /^[A-Za-z0-9+/]{20,}$/.test(line));
assert.notEqual(armorLineIndex, -1);
lines[armorLineIndex] = `${lines[armorLineIndex][0] === 'A' ? 'B' : 'A'}${lines[armorLineIndex].slice(1)}`;
recipient.setMessage({ rawBase64: Buffer.from(raw.replace(armor, lines.join('\r\n'))).toString('base64') });
assert.equal((await recipient.api.decryptMessage({ uid: 20, passphrase: 'bob test passphrase' })).code, 'CORRUPT');
recipient.setMessage({ rawBase64: Buffer.from(
'From: Alice <alice@example.test>\r\nContent-Type: multipart/encrypted; boundary="broken"\r\n\r\nnot a valid PGP payload'
).toString('base64') });
assert.equal((await recipient.api.decryptMessage({ uid: 21, passphrase: 'bob test passphrase' })).code, 'CORRUPT');
recipient.setMessage({ rawBase64: 'A'.repeat(35_000_000) });
assert.equal((await recipient.api.decryptMessage({ uid: 22, passphrase: 'bob test passphrase' })).code, 'TOO_LARGE');
});
+120
View File
@@ -0,0 +1,120 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const root = path.resolve(__dirname, '..');
const styles = fs.readFileSync(path.join(root, 'styles.css'), 'utf8');
const mailUi = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
const app = fs.readFileSync(path.join(root, 'app.js'), 'utf8');
const transport = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailTransport.kt'), 'utf8');
const mainActivity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8');
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
const vault = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidAccountVault.kt'), 'utf8');
const androidMailService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
const androidPgpPolicy = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpPolicy.kt'), 'utf8');
const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpConfirmationGate.kt'), 'utf8');
const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8');
const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8');
const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
test('mobile layout removes desktop minimum width and provides a compact reader flow', () => {
assert.match(styles, /min-width:320px/);
assert.match(styles, /@media\(max-width:1000px\),\(max-height:500px\) and \(orientation:landscape\)/);
assert.match(styles, /@media\(max-height:500px\) and \(orientation:landscape\)/);
assert.match(styles, /overflow-wrap:anywhere;word-break:break-word/);
assert.match(styles, /\.hidden,\[hidden\]\{display:none!important\}/);
assert.match(styles, /body\.reader-open \.mail-layout \.list-pane/);
assert.match(app, /id="reader-back"/);
assert.match(app, /classList\.add\('reader-open'\)/);
assert.match(app, /\$\$\('\.folder'\)\.forEach/);
assert.match(app, /if\(!m\)\{state\.activeMessage=null;document\.body\.classList\.remove\('reader-open'\);return;\}/);
});
test('mailbox setup exposes ports and TLS modes and submits them to Android', () => {
for (const id of ['mail-account-imap-port', 'mail-account-imap-secure', 'mail-account-smtp-port', 'mail-account-smtp-secure']) {
assert.ok(mailUi.includes(`id="${id}"`), `missing account field ${id}`);
}
assert.match(mailUi, /imapPort,/);
assert.match(mailUi, /imapSecure:/);
assert.match(mailUi, /smtpPort,/);
assert.match(mailUi, /smtpSecure:/);
});
test('Android mail transport supports verified implicit TLS and required STARTTLS modes', () => {
assert.match(transport, /"imaps" else "imap"/);
assert.match(transport, /mail\.\$protocol\.starttls\.required/);
assert.match(transport, /mail\.smtp\.ssl\.enable/);
assert.match(transport, /mail\.smtp\.starttls\.required/);
assert.match(transport, /ssl\.checkserveridentity/);
});
test('Capacitor mail plugin is registered before BridgeActivity creates the bridge', () => {
assert.ok(mainActivity.indexOf('registerPlugin(EpMailPlugin.class)') < mainActivity.indexOf('super.onCreate(savedInstanceState)'));
});
test('OpenPGP.js is pinned to the exact version in the lockfile pending security review', () => {
assert.equal(packageJson.dependencies.openpgp, packageLock.packages['node_modules/openpgp'].version);
assert.match(packageJson.dependencies.openpgp, /^\d+\.\d+\.\d+$/);
});
test('Android app lock is native-enforced and requires a secure device credential', () => {
assert.match(plugin, /fun getAppLockSettings/);
assert.match(plugin, /fun setAppLockEnabled/);
assert.match(plugin, /keyguard\.isDeviceSecure/);
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
assert.match(mainActivity, /createConfirmDeviceCredentialIntent/);
assert.match(mainActivity, /android\.R\.id\.content/);
assert.match(mainActivity, /settings\.setAllowFileAccess\(false\)/);
assert.match(mainActivity, /settings\.setAllowContentAccess\(false\)/);
assert.match(mainActivity, /setJavaScriptCanOpenWindowsAutomatically\(false\)/);
assert.match(mainActivity, /MIXED_CONTENT_NEVER_ALLOW/);
assert.match(mainActivity, /setWebContentsDebuggingEnabled\(BuildConfig\.DEBUG\)/);
assert.match(mainActivity, /addFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
assert.match(mainActivity, /clearFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
assert.match(mainActivity, /createVaultRecoveryOverlay/);
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
assert.match(androidBridge, /getAppLockSettings/);
assert.match(androidBridge, /setAppLockEnabled/);
assert.match(productivity, /Lock when leaving ep-mail/);
});
test('Android OpenPGP uses the encrypted vault and queues only built MIME data', () => {
assert.match(plugin, /fun pgpLoadStore/);
assert.match(plugin, /fun pgpSaveStore/);
assert.match(plugin, /fun pgpGetMessageSource/);
assert.match(plugin, /pgpStoreChangeWarning/);
assert.match(plugin, /plaintextSendWarning/);
assert.match(plugin, /Send plaintext/);
assert.match(plugin, /showPgpConfirmation\(/);
assert.match(plugin, /onCancelled = \{ call\.reject\("OpenPGP key change cancelled\."\) \}/);
assert.match(plugin, /onConfirmed = \{ sendPrepared\(call, input\) \}/);
assert.match(plugin, /PLAINTEXT_CANCELLED/);
assert.match(androidPgpConfirmationGate, /compareAndSet\(false, true\)/);
assert.match(androidPgpPolicy, /fun storeChangeWarning/);
assert.match(androidPgpPolicy, /fun plaintextSendWarning/);
assert.match(androidPgp, /curve25519Legacy/);
assert.match(androidPgp, /multipart\/encrypted/);
assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/);
assert.match(androidPgp, /async function verifyMessage/);
assert.match(androidPgp, /readCleartextMessage/);
assert.match(androidPgp, /readSignature/);
assert.match(pgpMailUi, /message\.signed/);
assert.match(androidBridge, /buildOutgoing\(message\)/);
assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/);
assert.match(androidMailService, /validateOpenPgpMime\(message\)/);
assert.match(androidMailService, /private fun validateOpenPgpMime/);
assert.match(androidMailService, /"send" -> send\(account, data\)/);
assert.match(androidMailService, /private fun isEncryptedMessage/);
});
test('Android vault refuses to replace a missing key when encrypted data exists', () => {
assert.match(vault, /shouldCreateKey\(hasEncryptedData\)/);
assert.match(vault, /MISSING_KEY_MESSAGE/);
assert.match(mainActivity, /AndroidAccountVault\.INSTANCE\.read\(\)/);
assert.match(mainActivity, /Saved data could not be opened/);
assert.match(mainActivity, /ACTION_APPLICATION_DETAILS_SETTINGS/);
});
+47
View File
@@ -0,0 +1,47 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const root = path.resolve(__dirname, '..');
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
const androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8');
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8');
const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8');
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
test('package metadata and lockfile share one release version', () => {
assert.equal(packageLock.version, packageJson.version);
assert.equal(packageLock.packages[''].version, packageJson.version);
assert.match(packageJson.version, /^\d+\.\d+\.\d+$/);
});
test('Android version name and code derive from the canonical package version', () => {
assert.match(androidBuild, /parse\(file\("\.\.\/\.\.\/package\.json"\)\)\.version/);
assert.match(androidBuild, /versionName appVersion/);
assert.match(androidBuild, /versionCode appVersionParts\[0\] \* 10000 \+ appVersionParts\[1\] \* 100 \+ appVersionParts\[2\]/);
const parts = packageJson.version.split('.').map(Number);
const expectedCode = parts[0] * 10000 + parts[1] * 100 + parts[2];
assert.ok(Number.isSafeInteger(expectedCode) && expectedCode > 0);
assert.ok(parts[1] < 100 && parts[2] < 100, 'update the Android versionCode mapping before minor or patch reaches 100');
});
test('release scripts and desktop artifact labels use package.json version', () => {
assert.match(buildAll, /package\.json/);
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
});
test('Android debug APK is labeled as debug and release APK requires signing credentials', () => {
assert.match(androidDebugScript, /assembleDebug/);
assert.match(androidDebugScript, /ep-mail \$\{version\}-debug\.apk/);
assert.match(androidReleaseScript, /assembleRelease/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_FILE/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_STORE_PASSWORD/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_ALIAS/);
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/);
assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/);
});
+40
View File
@@ -0,0 +1,40 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { makeCalendarData, makeVcard } = require('../desktop/dav-codecs.cjs');
test('serializes calendar events with escaped values and stable injected identifiers', () => {
const data = makeCalendarData({
date: '2026-10-16',
title: 'Review, plan; follow-up',
place: 'Room A, west',
notes: 'First line\nSecond line',
_dav: { uid: 'event-1' }
}, { now: () => new Date('2026-10-16T12:34:56.000Z') });
assert.match(data, /UID:event-1\r\n/);
assert.match(data, /DTSTAMP:20261016T123456Z\r\n/);
assert.match(data, /DTSTART;VALUE=DATE:20261016\r\n/);
assert.match(data, /SUMMARY:Review\\, plan\\; follow-up\r\n/);
assert.match(data, /LOCATION:Room A\\, west\r\n/);
assert.match(data, /DESCRIPTION:First line\\nSecond line\r\n/);
});
test('serializes contacts with escaped fields and an injected identifier', () => {
const data = makeVcard({
name: 'Ada Example Lovelace',
email: 'ada@example.com',
note: 'Research, analysis; mathematics',
_dav: { uid: 'contact-1' }
});
assert.equal(data,
'BEGIN:VCARD\r\nVERSION:3.0\r\nUID:contact-1\r\nFN:Ada Example Lovelace\r\n' +
'N:Example Lovelace;Ada;;;\r\nEMAIL:ada@example.com\r\n' +
'NOTE:Research\\, analysis\\; mathematics\r\nEND:VCARD\r\n');
});
test('rejects DAV identifiers that can inject fields or escape resource paths', () => {
assert.throws(() => makeCalendarData({ date: '2026-10-16', title: 'Bad', _dav: { uid: 'good\r\nX-Evil: yes' } }), /identifier is invalid/);
assert.throws(() => makeCalendarData({ date: '2026-10-16', title: 'Bad', _dav: { uid: '../other' } }), /identifier is invalid/);
assert.throws(() => makeVcard({ name: 'Bad', email: 'x@example.test', _dav: { uid: 'x'.repeat(256) } }), /identifier is invalid/);
});
+26
View File
@@ -0,0 +1,26 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { registerDavIpcHandlers } = require('../desktop/ipc/dav.cjs');
test('registers the complete DAV IPC surface through the shared boundary', () => {
const registered = [];
registerDavIpcHandlers({
registerIpcHandler(channel, handler) { registered.push({ channel, handler }); },
readDavStore() {},
saveDavStore() {},
davPublicConfig() {},
openDavClient() {},
activeDavConfig() {},
ICAL: {},
makeCalendarData() {},
makeVcard() {},
randomUUID() {},
assertDavObjectReference() {}
});
assert.deepEqual(registered.map(item => item.channel).sort(), [
'dav:activate', 'dav:connect', 'dav:delete-contact', 'dav:delete-event',
'dav:list', 'dav:remove', 'dav:save-contact', 'dav:save-event', 'dav:sync'
]);
assert.ok(registered.every(item => typeof item.handler === 'function'));
});
+66
View File
@@ -0,0 +1,66 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { assertDavObjectReference } = require('../desktop/dav/remote-reference.cjs');
const config = { id: 'dav-1', serverUrl: 'https://dav.example.test/' };
const collection = { url: 'https://dav.example.test/calendars/user/main/', displayName: 'Main' };
const object = { url: 'https://dav.example.test/calendars/user/main/event-1.ics', etag: '"v4"' };
const remote = {
accountId: 'dav-1',
collectionUrl: collection.url,
objectUrl: object.url,
etag: object.etag
};
test('accepts a resource verified against the configured server, collection, and current ETag', () => {
const result = assertDavObjectReference({ config, remote, collections: [collection], objects: [object] });
assert.equal(result.collection, collection);
assert.equal(result.object, object);
assert.equal(result.objectUrl, object.url);
});
test('accepts a relative server-returned object URL within its verified collection', () => {
const result = assertDavObjectReference({
config,
remote: { ...remote, objectUrl: 'event-1.ics' },
collections: [collection],
objects: [{ url: 'event-1.ics', etag: '"v4"' }]
});
assert.equal(result.objectUrl, object.url);
});
test('rejects account, collection, and resource references not returned by the server', () => {
assert.throws(() => assertDavObjectReference({
config, remote: { ...remote, accountId: 'other-account' }, collections: [collection], objects: [object]
}), /does not belong/);
assert.throws(() => assertDavObjectReference({
config, remote: { ...remote, collectionUrl: 'https://dav.example.test/other/' }, collections: [collection], objects: [object]
}), /collection is not available/);
assert.throws(() => assertDavObjectReference({
config, remote: { ...remote, objectUrl: 'https://dav.example.test/calendars/user/main/unknown.ics' }, collections: [collection], objects: [object]
}), /no longer available/);
});
test('rejects cross-origin, credential-bearing, query, traversal, and out-of-collection URLs', () => {
for (const objectUrl of [
'https://attacker.example/event.ics',
'https://user:pass@dav.example.test/calendars/user/main/event-1.ics',
'https://dav.example.test/calendars/user/main/event-1.ics?redirect=1',
'../other/event.ics',
'https://dav.example.test/calendars/user/main/',
'https://dav.example.test/calendars/user/other/event.ics'
]) {
assert.throws(() => assertDavObjectReference({
config, remote: { ...remote, objectUrl }, collections: [collection], objects: [object]
}));
}
});
test('rejects stale ETags and ETags with unexpected types', () => {
assert.throws(() => assertDavObjectReference({
config, remote: { ...remote, etag: '"v3"' }, collections: [collection], objects: [object]
}), /changed on the server/);
assert.throws(() => assertDavObjectReference({
config, remote: { ...remote, etag: 4 }, collections: [collection], objects: [{ ...object, etag: undefined }]
}), /version is invalid/);
});
+97
View File
@@ -0,0 +1,97 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { hasIpcSchema, validateIpcArguments } = require('../desktop/security/ipc-arguments.cjs');
test('validates supported IPC channels and their positional argument types', () => {
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{ email: 'a@example.com' }]));
assert.doesNotThrow(() => validateIpcArguments('mail:list-oauth-providers', []));
assert.doesNotThrow(() => validateIpcArguments('mail:sync-folder', ['Inbox', 0, { hasAttachments: true }]));
assert.doesNotThrow(() => validateIpcArguments('mail:disconnect', []));
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{ to: 'a@example.com', attachments: [] }]));
assert.throws(() => validateIpcArguments('mail:connect', ['not-an-object']), /Invalid object argument/);
assert.throws(() => validateIpcArguments('mail:sync-folder', ['Inbox', 'zero']), /Invalid number argument/);
assert.throws(() => validateIpcArguments('mail:open-external', [null]), /Invalid string argument/);
assert.throws(() => validateIpcArguments('pgp:set-trust', ['fingerprint']), /Invalid argument count/);
assert.throws(() => validateIpcArguments('mail:list-accounts', ['unexpected']), /Invalid argument count/);
assert.doesNotThrow(() => validateIpcArguments('dav:sync', ['carddav']));
assert.throws(() => validateIpcArguments('dav:sync', ['contacts']), /Invalid enum/);
assert.throws(() => validateIpcArguments('mail:open-external', [`https://example.test/${'x'.repeat(2048)}`]), /too large/);
assert.throws(() => validateIpcArguments('pgp:export-public', ['A'.repeat(65)]), /too large/);
assert.throws(() => validateIpcArguments('unknown:channel', []), /Unknown IPC channel/);
});
test('bounds nested payload complexity without limiting attachment byte strings', () => {
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{
to: 'a@example.com',
attachments: [{ filename: 'large.bin', contentBase64: 'A'.repeat(1_000_001) }]
}]));
assert.throws(() => validateIpcArguments('pgp:add-contact', [{ armoredKey: 'A'.repeat(200_001) }]), /too large/);
assert.throws(() => validateIpcArguments('mail:save-draft', [{ text: 'x'.repeat(1_000_001) }]), /too large/);
let nested = { payload: 1 };
for (let index = 0; index < 21; index += 1) nested = { child: nested };
assert.throws(() => validateIpcArguments('mail:send', [nested]), /nested too deeply/);
assert.throws(() => validateIpcArguments('mail:save-draft', [{ values: Array(5001).fill('x') }]), /Too many items/);
});
test('rejects non-finite numbers, cycles, and prototype-sensitive fields', () => {
assert.throws(() => validateIpcArguments('mail:set-snooze', [{ uid: Infinity }]), /Invalid number/);
const cyclic = {};
cyclic.self = cyclic;
assert.throws(() => validateIpcArguments('mail:save-draft', [cyclic]), /Cyclic value/);
const unsafe = Object.create(null);
unsafe.constructor = 'unexpected';
assert.throws(() => validateIpcArguments('mail:save-draft', [unsafe]), /Unsafe field/);
});
test('validates channel-specific field shapes, limits, and enums', () => {
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{
email: 'user@example.test', password: 'secret', displayName: 'User',
imapHost: 'imap.example.test', smtpHost: 'smtp.example.test',
rules: [{ senderContains: 'alerts', action: 'flag', value: '' }]
}]));
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'google', displayName: 'User'
}]));
assert.doesNotThrow(() => validateIpcArguments('mail:update-account', ['account-1', {
authMethod: 'oauth2', oauthProvider: 'microsoft', reauthorizeOAuth: true
}]));
assert.throws(() => validateIpcArguments('mail:connect', [{ authMethod: 'oauth2', oauthProvider: 'other' }]), /oauthProvider/);
assert.throws(() => validateIpcArguments('mail:connect', [{
email: 'user@gmail.com', authMethod: 'oauth2', oauthProvider: 'unknown'
}]), /oauthProvider/);
assert.throws(() => validateIpcArguments('mail:connect', [{ rules: Array(51).fill({ action: 'flag' }) }]), /Invalid argument 1/);
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: '4', action: 'star' }]), /uid/);
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: 4, action: 'delete-anything' }]), /action/);
assert.throws(() => validateIpcArguments('pgp:add-key-server', [{ name: 'Keys', url: 'https://keys.example.test', protocol: 'ftp' }]), /protocol/);
assert.throws(() => validateIpcArguments('dav:save-event', [{ title: 'Event', _dav: { etag: 42 } }]), /_dav.etag/);
});
test('prevents renderer-supplied raw SMTP messages while accepting standard compose fields', () => {
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{
to: 'friend@example.test', cc: '', subject: 'Hello', text: 'Body',
attachments: [{ filename: 'note.txt', contentBase64: 'aGVsbG8=' }],
pgp: { encrypt: true, sign: false, passphrase: null }
}]));
assert.doesNotThrow(() => validateIpcArguments('pgp:decrypt-message', [{ folder: 'Inbox', uid: 4, passphrase: null }]));
assert.throws(() => validateIpcArguments('mail:send', [{ rawBase64: 'YWJj', envelope: { to: ['victim@example.test'] } }]), /Unsupported message field/);
assert.throws(() => validateIpcArguments('mail:send', [{ pgp: { encrypt: 'true' } }]), /pgp.encrypt/);
assert.throws(() => validateIpcArguments('mail:send', [{ attachments: [{ contentBase64: 123 }] }]), /contentBase64/);
});
test('every registered main-process IPC handler has a request schema', () => {
const mainPath = path.resolve(__dirname, '..', 'desktop', 'main.cjs');
const ipcDirectory = path.resolve(__dirname, '..', 'desktop', 'ipc');
const sourceFiles = [mainPath, ...fs.readdirSync(ipcDirectory)
.filter(name => name.endsWith('.cjs'))
.map(name => path.join(ipcDirectory, name))];
const channels = sourceFiles.flatMap(file => {
const source = fs.readFileSync(file, 'utf8');
return [...source.matchAll(/registerIpcHandler\('([^']+)'/g)].map(match => match[1]);
});
assert.ok(channels.length > 0);
for (const channel of channels) {
assert.equal(hasIpcSchema(channel), true, `missing IPC request schema: ${channel}`);
}
});
+44
View File
@@ -0,0 +1,44 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const { pathToFileURL } = require('node:url');
const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('../desktop/security/ipc-sender.cjs');
function eventFor(url, { subframe = false } = {}) {
const mainFrame = { url: subframe ? pathToFileURL(path.resolve('index.html')).href : url };
const senderFrame = subframe ? { url } : mainFrame;
return { sender: { mainFrame }, senderFrame };
}
test('accepts the trusted top-level application document', () => {
const expected = path.resolve('index.html');
assert.doesNotThrow(() => assertTrustedIpcSender(
eventFor(pathToFileURL(expected).href), expected
));
});
test('rejects remote, different-file, query, and hash documents', () => {
const expected = path.resolve('index.html');
for (const url of [
'https://example.com/index.html',
pathToFileURL(path.resolve('other.html')).href,
`${pathToFileURL(expected).href}?debug=1`,
`${pathToFileURL(expected).href}#fragment`
]) {
assert.throws(() => assertTrustedIpcSender(eventFor(url), expected), /application window/);
}
});
test('rejects subframes and missing sender-frame information', () => {
const expected = path.resolve('index.html');
const topUrl = pathToFileURL(expected).href;
assert.throws(() => assertTrustedIpcSender(eventFor(topUrl, { subframe: true }), expected), /application window/);
assert.throws(() => assertTrustedIpcSender({ sender: { mainFrame: {} } }, expected), /application window/);
});
test('trusted-navigation policy allows only the app document URL', () => {
const expected = path.resolve('index.html');
assert.equal(isTrustedApplicationUrl(pathToFileURL(expected).href, expected), true);
assert.equal(isTrustedApplicationUrl('https://example.com/', expected), false);
assert.equal(isTrustedApplicationUrl(`${pathToFileURL(expected).href}#route`, expected), false);
});
+72
View File
@@ -0,0 +1,72 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { createMessageActionService } = require('../desktop/mail/action-service.cjs');
function setup({ sourcePath = 'INBOX', usable = true } = {}) {
const calls = { actions: [], locks: [], released: 0, logout: 0, updates: 0 };
const store = { accounts: [{ id: 'account-1', snoozedMessages: [
{ uid: 7, folder: 'Inbox' }, { uid: 8, folder: 'Inbox' }, { uid: 7, folder: 'Sent' }
] }] };
const client = {
usable,
async connect() {},
async getMailboxLock(path) {
calls.locks.push(path);
return { release() { calls.released += 1; } };
},
async messageFlagsAdd(...args) { calls.actions.push(['flagsAdd', ...args]); },
async messageFlagsRemove(...args) { calls.actions.push(['flagsRemove', ...args]); },
async messageMove(...args) { calls.actions.push(['move', ...args]); },
async messageDelete(...args) { calls.actions.push(['delete', ...args]); },
async logout() { calls.logout += 1; }
};
const service = createMessageActionService({
imapClient() { return client; },
async folderPath(_client, folder) { return folder === 'Inbox' ? sourcePath : folder; },
async findSpecialMailbox(_client, specialUse, _fallbackNames, createName) {
calls.actions.push(['find', specialUse, createName]);
return specialUse === '\\Archive' ? 'Archive' : 'Trash';
},
async updateAccountStore(update) { calls.updates += 1; return update(store); }
});
return { service, calls, store };
}
test('applies star and unread flags with UID addressing and releases the mailbox lock', async () => {
const { service, calls } = setup();
assert.deepEqual(await service.applyMessageAction({ id: 'account-1' }, { uid: 7, action: 'star', enabled: true }), { ok: true });
assert.deepEqual(calls.actions[0], ['flagsAdd', 7, ['\\Flagged'], { uid: true }]);
assert.deepEqual(calls.locks, ['INBOX']);
assert.equal(calls.released, 1);
assert.equal(calls.logout, 1);
assert.equal(calls.updates, 0);
});
test('moves archived messages and removes their matching snooze entry', async () => {
const { service, calls, store } = setup();
await service.applyMessageAction({ id: 'account-1' }, { uid: 7, folder: 'Inbox', action: 'archive' });
assert.deepEqual(calls.actions, [
['find', '\\Archive', 'Archive'],
['move', 7, 'Archive', { uid: true }]
]);
assert.deepEqual(store.accounts[0].snoozedMessages, [{ uid: 8, folder: 'Inbox' }, { uid: 7, folder: 'Sent' }]);
assert.equal(calls.updates, 1);
assert.equal(calls.released, 1);
});
test('deleting in Trash deletes rather than attempting to move a message to itself', async () => {
const { service, calls } = setup({ sourcePath: 'Trash' });
await service.applyMessageAction({ id: 'account-1' }, { uid: 9, folder: 'Inbox', action: 'delete' });
assert.deepEqual(calls.actions, [
['find', '\\Trash', 'Trash'],
['delete', 9, { uid: true }]
]);
});
test('rejects invalid message identifiers and actions without opening IMAP', async () => {
const { service, calls } = setup();
await assert.rejects(() => service.applyMessageAction({}, { uid: 0, action: 'star' }), /could not be identified/);
await assert.rejects(() => service.applyMessageAction({}, { uid: 1, action: 'expunge' }), /not supported/);
assert.equal(calls.locks.length, 0);
assert.equal(calls.logout, 0);
});
+93
View File
@@ -0,0 +1,93 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { createAttachmentService } = require('../desktop/mail/attachment-service.cjs');
function setup({ mailboxPath = 'INBOX', item = { source: Buffer.from('message') }, attachments = [] } = {}) {
const calls = { loggedOut: 0, locksReleased: 0, saved: [], dialogOptions: [], parsedSources: [] };
const client = {
usable: true,
async connect() {},
async getMailboxLock(path) {
assert.equal(path, mailboxPath);
return { release() { calls.locksReleased += 1; } };
},
async fetchOne(uid, query, options) {
assert.equal(uid, 4);
assert.deepEqual(query, { uid: true, source: true });
assert.deepEqual(options, { uid: true });
return item;
},
async logout() { calls.loggedOut += 1; }
};
const service = createAttachmentService({
imapClient() { return client; },
async folderPath(_client, folder) { return folder === 'Missing' ? null : mailboxPath; },
async parseForAttachments(source) {
calls.parsedSources.push(source);
return { attachments };
},
async writeFile(filePath, content) { calls.saved.push({ filePath, content }); }
});
return { service, calls };
}
test('saves the requested attachment using a sanitized dialog default path', async () => {
const bytes = Buffer.from('contents');
const { service, calls } = setup({ attachments: [{ filename: 'reports/annual:2026.txt', content: bytes }] });
const result = await service.saveAttachment({ id: 'account-1' }, {
uid: 4, folder: 'Inbox', filename: 'reports/annual:2026.txt'
}, async options => {
calls.dialogOptions.push(options);
return { canceled: false, filePath: 'C:/exports/report.txt' };
});
assert.deepEqual(result, { saved: true });
assert.deepEqual(calls.dialogOptions, [{ defaultPath: 'reports_annual_2026.txt' }]);
assert.equal(calls.saved[0].filePath, 'C:/exports/report.txt');
assert.deepEqual(calls.saved[0].content, bytes);
assert.equal(calls.locksReleased, 1);
assert.equal(calls.loggedOut, 1);
});
test('cancellation does not write attachment bytes and save falls back to the first attachment', async () => {
const { service, calls } = setup({ attachments: [{ filename: 'first.txt', content: Buffer.from('first') }] });
const result = await service.saveAttachment({ id: 'account-1' }, { uid: 4 }, async options => {
calls.dialogOptions.push(options);
return { canceled: true };
});
assert.deepEqual(result, { canceled: true });
assert.deepEqual(calls.dialogOptions, [{ defaultPath: 'first.txt' }]);
assert.equal(calls.saved.length, 0);
});
test('previews supported image and text attachments with explicit size bounds', async () => {
const imageBytes = Buffer.from([1, 2, 3]);
const imageService = setup({ attachments: [{ filename: 'image.png', contentType: 'image/png', content: imageBytes }] }).service;
assert.deepEqual(await imageService.previewAttachment({}, { uid: 4, filename: 'image.png' }), {
kind: 'image', dataUrl: `data:image/png;base64,${imageBytes.toString('base64')}`
});
const largeImage = setup({ attachments: [{ filename: 'large.png', contentType: 'image/png', content: Buffer.alloc(5 * 1048576 + 1) }] }).service;
assert.deepEqual(await largeImage.previewAttachment({}, { uid: 4, filename: 'large.png' }), {
kind: 'none', reason: 'This image is too large to preview. Download it instead.'
});
const textBytes = Buffer.from('hello');
const textService = setup({ attachments: [{ filename: 'note.txt', contentType: 'text/plain; charset=utf-8', content: textBytes }] }).service;
assert.deepEqual(await textService.previewAttachment({}, { uid: 4, filename: 'note.txt' }), {
kind: 'text', text: 'hello', truncated: false
});
});
test('rejects invalid identifiers, missing messages, folders, and attachment names', async () => {
const { service, calls } = setup({ item: null });
await assert.rejects(() => service.previewAttachment({}, { uid: 0 }), /could not be identified/);
await assert.rejects(() => service.previewAttachment({}, { uid: 4 }), /no longer available/);
assert.equal(calls.loggedOut, 1);
const missingFolder = setup().service;
await assert.rejects(() => missingFolder.previewAttachment({}, { uid: 4, folder: 'Missing' }), /folder could not be found/);
const noAttachment = setup().service;
await assert.rejects(() => noAttachment.previewAttachment({}, { uid: 4, filename: 'unknown.txt' }), /No attachment/);
});
+79
View File
@@ -0,0 +1,79 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { createMailContentSecurity } = require('../mail-content-security.js');
test('exposes an immutable mail-content security API', () => {
const api = createMailContentSecurity({});
assert.equal(Object.isFrozen(api), true);
assert.equal(typeof api.safeRemoteImageUrl, 'function');
assert.equal(typeof api.sanitizeMailHtml, 'function');
});
test('allows only bounded HTTPS remote image URLs without embedded credentials', () => {
const { safeRemoteImageUrl } = createMailContentSecurity({});
assert.equal(safeRemoteImageUrl('https://images.example.test/pixel.png'), 'https://images.example.test/pixel.png');
assert.equal(safeRemoteImageUrl('HTTPs://images.example.test/pixel.png'), 'https://images.example.test/pixel.png');
assert.equal(safeRemoteImageUrl('http://images.example.test/pixel.png'), null);
assert.equal(safeRemoteImageUrl('data:image/png;base64,AAAA'), null);
assert.equal(safeRemoteImageUrl('https://user:pass@images.example.test/pixel.png'), null);
assert.equal(safeRemoteImageUrl(`https://images.example.test/${'x'.repeat(2050)}`), null);
assert.equal(safeRemoteImageUrl('not a URL'), null);
assert.equal(safeRemoteImageUrl(null), null);
});
test('sanitizes parsed mail DOM and keeps approved remote images inert', () => {
let parsedHtml = '';
const createElement = (localName, attributes = {}, childNodes = []) => {
const values = new Map(Object.entries(attributes));
const element = {
nodeType: 1,
localName,
childNodes,
parentNode: null,
get attributes() { return [...values].map(([name, value]) => ({ name, value })); },
getAttribute(name) { return values.get(name) ?? null; },
setAttribute(name, value) { values.set(name, String(value)); },
removeAttribute(name) { values.delete(name); },
remove() {
if (this.parentNode) this.parentNode.childNodes.splice(this.parentNode.childNodes.indexOf(this), 1);
},
get innerHTML() {
const attributes = [...values].map(([name, value]) => ` ${name}="${value}"`).join('');
if (this.localName === 'img') return `<img${attributes}>`;
const contents = childNodes.map(child => child.nodeType === 3 ? child.textContent : child.innerHTML).join('');
return `<${this.localName}${attributes}>${contents}</${this.localName}>`;
}
};
for (const child of childNodes) child.parentNode = element;
return element;
};
const body = {
childNodes: [],
get innerHTML() { return this.childNodes.map(child => child.innerHTML).join(''); }
};
const browserRoot = {
Node: { ELEMENT_NODE: 1, TEXT_NODE: 3 },
DOMParser: class {
parseFromString(html) {
parsedHtml = html;
const url = html.match(/data-remote-src="([^"]+)"/)?.[1] || '';
body.childNodes = [
createElement('script', {}, [{ nodeType: 3, textContent: 'alert(1)' }]),
createElement('p', { onclick: 'alert(2)' }, [{ nodeType: 3, textContent: 'Hello' }]),
createElement('img', { src: url, 'data-remote-src': url, alt: 'pixel', onerror: 'alert(3)' })
];
body.childNodes.forEach(child => { child.parentNode = body; });
return { body };
}
}
};
const { html, remoteImageCount } = createMailContentSecurity(browserRoot).sanitizeMailHtml(
'<p onclick="alert(2)">Hello</p><script>alert(1)</script><img src="https://images.example.test/pixel.png" onerror="alert(3)"><a href="javascript:alert(4)">link</a>'
);
assert.doesNotMatch(parsedHtml, /<script\b|\shref\s*=|\ssrc\s*=/i);
assert.match(parsedHtml, /<img data-remote-src="https:\/\/images\.example\.test\/pixel\.png">/);
assert.equal(remoteImageCount, 1);
assert.equal(html, '<p>Hello</p><img data-remote-src="https://images.example.test/pixel.png" alt="pixel">');
assert.doesNotMatch(html, /onclick|onerror|javascript:|<script/);
});

Some files were not shown because too many files have changed in this diff Show More