Compare commits

...
29 Commits
Author SHA1 Message Date
thuttuandCopilot 93ff651e9d Fix Android OpenPGP message ID handling
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 22:20:51 +02:00
thuttuandCopilot 96c7b6966b Improve Android OpenPGP, drafts and release builds
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 22:11:05 +02:00
thuttuandCopilot d0e2ce26bc Enable OpenPGP key servers on Android, add keys.eternityproject.fi, allow removing built-in servers
- Android: key-server lookup, publish, add/remove/enable via native HTTP
- Built-in servers can be removed; keys.eternityproject.fi (VKS) added as a default
- Fix Settings additions (Encryption keys, shortcuts) missing on Android due to async preferences
- Fix compose footer so Send is visible on small screens
- Bump version to 0.5.22

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-17 20:53:54 +02:00
thuttu 4ec578b072 FIX send message button in compose message window 2026-11-17 20:22:14 +02:00
thuttuandCopilot 8a798fec6b Upgrade Android build tooling for 0.5.20
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-09 22:17:55 +02:00
thuttuandCopilot 5b8aafe22c Improve Android mailbox navigation and pagination
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-09 22:07:20 +02:00
thuttu 89c45fcf63 FIX feature to scroll down in imap folder to load more mails 2026-11-09 21:11:00 +02:00
thuttu d7b6e31518 Add feature to scroll down in imap folder to load more mails, and speedup of imap folder change 2026-11-09 20:42:31 +02:00
thuttu b14209a5ae IMAP Folder speedup tuning 2026-11-09 20:11:31 +02:00
thuttu d0b26db9ee Performance tuning of opening IMAP mailbox and Fix mailbox logic so it wont auto open first mail 2026-11-09 19:39:42 +02:00
thuttu 78989f7b56 Security review and fix issues 2026-11-03 23:57:48 +02:00
thuttu 5f456e64d0 Android security implementation Phase 0-3 finalization part 1 2026-11-03 23:45:20 +02:00
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
148 changed files with 43167 additions and 15129 deletions
+1
View File
@@ -0,0 +1 @@
scripts/build-linux-wsl.sh text eol=lf
+3
View File
@@ -0,0 +1,3 @@
{
"java.configuration.updateBuildConfiguration": "interactive"
}
+103
View File
@@ -0,0 +1,103 @@
# 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, configurable app locking, `FLAG_SECURE` from backgrounding, account-removal disclosure, explicit full local-data deletion, and fail-closed missing-key recovery are implemented. Vault lifecycle and automated device/lifecycle tests remain open.
- **Phase 2 — Android OpenPGP:** The experimental implementation now includes optional authentication-bound biometric/device-credential release of PGP passphrases, with passphrase fallback and invalidation recovery. It is not security-reviewed or release-complete.
- **Phase 3 — WebView/bridge:** CSP, navigation, sanitizer, and plugin-surface regression checks are automated; 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 sends when keys exist or encryption was requested; every renderer-produced raw MIME send also requires a native confirmation because the native layer cannot cryptographically verify its encryption. 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, app-lock delay policy, app-owned Downloads selection, Android OpenPGP policy decisions, unverified-recipient confirmation, raw-MIME native warning policy, one-shot confirmation callbacks, bounded preview reads, and the missing-vault-key policy have Android unit tests. The latest run passed all 162 Node tests and all 26 Android unit tests; debug APK assembly and the release-manifest processing task also succeeded. The Android PGP module's Node-harness tests cover encrypted-message flows, passphrase-verified biometric unlock, invalidation error propagation, and manual passphrase recovery; they do not exercise Android Keystore prompts or OS-level invalidation. The app lock was previously exercised on an emulator with a device PIN, including background lock/unlock and screenshot obscuring; the new delay choices still need device lifecycle testing. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were previously exercised on an emulator; actual dialog automation remains open. 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. Device testing of vault-corruption/key-loss recovery, biometric enrollment invalidation, invalid-certificate integration, production-signed APK review, and automated instrumentation of native 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/biometric dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric invalidation tests; invalid-certificate integration tests; production-signed APK/manifest review; app-lock process-recreation testing; 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.
- [x] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation says downloaded attachment files and global OpenPGP keys are retained.
- [~] A separate native-confirmed full-data wipe removes vault contents, account and PGP Keystore keys, app-owned Downloads attachments, WebView data, service-worker registrations/caches, and renderer local settings. It is distinct from account removal; Android storage-failure and end-to-end deletion tests remain open.
- [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` as soon as the app leaves the foreground. Users may choose immediate, 30-second, 1-minute, or 5-minute locking; the default is immediate. Background sync continues and the setting is off unless enabled. Emulator testing of the new delays, automated lifecycle/process-recreation tests, 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 in that store. Optional PGP passphrase release is separately encrypted by an authentication-bound Android Keystore key; biometric/device-credential invalidation clears the wrapper and falls back to the original passphrase. Device-level invalidation/recovery tests and automated at-rest checks remain open.
- [x] Optional biometric/device-credential release of PGP key access is available per key; the default remains passphrase-only, and 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). Trust elevation and replacement are guarded; encryption to keys not fingerprint-verified now requires an explicit per-send confirmation showing the recipient and full fingerprint. Automated native 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; every raw MIME send now requires native confirmation because the native layer cannot cryptographically verify renderer-produced encryption. The native send path also 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. Source-level CSP checks are automated; verify generated release assets and behavior 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. Automated checks cover CSP, manifest permissions, external URL constraints, DAV redirects, and selected bridge methods; a complete method-by-method plugin review remains open.
- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. Text/image previews use bounded stream reads, while attachment downloads stream to app storage. 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.
+108 -108
View File
@@ -1,119 +1,119 @@
# Architecture
This project has a layered architecture: a desktop Electron shell, a browser-rendered mail interface, platform-specific storage and sync adapters, and a separate Android Capacitor wrapper. The design keeps user state and credentials in the OS keyring, pushes IMAP/SMTP work into the main process, and exposes only a narrow IPC surface to the renderer.
## 1. Runtime layout
### Desktop shell
- `desktop/main.cjs` is the privileged process.
- 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.
# Architecture
This project has a layered architecture: a desktop Electron shell, a browser-rendered mail interface, platform-specific storage and sync adapters, and a separate Android Capacitor wrapper. The design keeps user state and credentials in the OS keyring, pushes IMAP/SMTP work into the main process, and exposes only a narrow IPC surface to the renderer.
## 1. Runtime layout
### Desktop shell
- `desktop/main.cjs` is the privileged process.
- 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.
- `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 canonical web assets in the repository root; `www/` is generated for Capacitor:
- `index.html` defines the classic-script bootstrap order. `renderer-state.js` exposes shared state as `window.epMailState` without legacy unnamespaced aliases.
- `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.
### Android client
The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.config.json`).
- The same browser UI runs inside the Android app.
- Native Android services handle background sync, notification behavior, and secure storage.
- The desktop and Android implementations intentionally share the same mail and account model so the feature surface stays aligned.
## 2. Core responsibilities
### Mail and account state
The main process owns the canonical account model and persists it in an encrypted store:
### Android client
The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.config.json`).
- The same browser UI runs inside the Android app.
- Native Android services handle background sync, notification behavior, and secure storage.
- The desktop and Android implementations intentionally share the same mail and account model so the feature surface stays aligned.
## 2. Core responsibilities
### Mail and account state
The main process owns the canonical account model and persists it in an encrypted store:
- `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.
- `pgp-keys.enc` stores OpenPGP keys and trust data.
All three stores are wrapped with Electron `safeStorage` where available. Linux checks explicitly reject the insecure `basic_text` backend before credentials or keys are persisted.
### Mail sync pipeline
The desktop app follows a background sync model:
1. The renderer asks the main process for a folder sync or inbox refresh.
2. The main process opens an IMAP connection and fetches only the requested subset or page.
3. Sync results are written back into the account state and sent to the renderer via IPC (`mail:sync-update`).
4. Periodic background sync and IDLE watchers reduce polling and keep new-mail notifications timely.
A generation counter invalidates stale sync jobs when accounts are edited or removed, and concurrent syncs are prevented to avoid overlapping IMAP traffic.
### Message send path
The send flow is also centralized in the main process:
- the renderer calls the desktop `mail:send` IPC or the Android `EpMail.send` plugin with message fields and selected attachment bytes
- the native send path resolves the account, checks sender settings, builds multipart MIME, and on desktop applies OpenPGP encryption/signing to the body and attachments before sending
- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable; local draft attachments are persisted with draft content
The renderer sends file bytes rather than local paths. OpenPGP messages are encrypted before offline queueing so the outbox contains ciphertext instead of plaintext message or attachment content.
## 3. Security boundary
The current architecture takes a strict trust split:
- renderer: UI, user interaction, local conveniences
- main process: network access, cryptographic operations, permission prompts, OS secure storage
This boundary is important for encryption and safety checks:
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
- `pgp-keys.enc` stores OpenPGP keys and trust data.
All three stores are wrapped with Electron `safeStorage` where available. Linux checks explicitly reject the insecure `basic_text` backend before credentials or keys are persisted.
### Mail sync pipeline
The desktop app follows a background sync model:
1. The renderer asks the main process for a folder sync or inbox refresh.
2. The main process opens an IMAP connection and fetches only the requested subset or page.
3. Sync results are written back into the account state and sent to the renderer via IPC (`mail:sync-update`).
4. Periodic background sync and IDLE watchers reduce polling and keep new-mail notifications timely.
A generation counter invalidates stale sync jobs when accounts are edited or removed, and concurrent syncs are prevented to avoid overlapping IMAP traffic.
### Message send path
The send flow is also centralized in the main process:
- the renderer calls the desktop `mail:send` IPC or the Android `EpMail.send` plugin with message fields and selected attachment bytes
- the native send path resolves the account, checks sender settings, builds multipart MIME, and on desktop applies OpenPGP encryption/signing to the body and attachments before sending
- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable; local draft attachments are persisted with draft content
The renderer sends file bytes rather than local paths. OpenPGP messages are encrypted before offline queueing so the outbox contains ciphertext instead of plaintext message or attachment content.
## 3. Security boundary
The current architecture takes a strict trust split:
- renderer: UI, user interaction, local conveniences
- main process: network access, cryptographic operations, permission prompts, OS secure storage
This boundary is important for encryption and safety checks:
- 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.
- Send-time downgrade checks happen in the main process rather than only in UI logic.
- External links open only after a native confirmation dialog.
- Incoming HTML is sanitized in the renderer before insertion. HTTPS image URLs are kept in inert data attributes; only a per-message user action assigns image sources, and reopening the message resets that approval. HTTP images are rejected to preserve Android's cleartext-traffic protection. The CSP allows HTTPS images; scripts, frames, forms, and remote connections remain blocked.
- Credentials and private keys are stored with the OS keyring, not in plain JSON files.
## 4. OpenPGP subsystem
The OpenPGP implementation is split into focused modules:
- `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-keyservers.cjs` implements bounded HTTPS lookup and publication for VKS and HKP-compatible servers.
- 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.
- External links open only after a native confirmation dialog.
- Incoming HTML is sanitized in the renderer before insertion. HTTPS image URLs are kept in inert data attributes; only a per-message user action assigns image sources, and reopening the message resets that approval. HTTP images are rejected to preserve Android's cleartext-traffic protection. The CSP allows HTTPS images; scripts, frames, forms, and remote connections remain blocked.
- Credentials and private keys are stored with the OS keyring, not in plain JSON files.
## 4. OpenPGP subsystem
The OpenPGP implementation is split into focused modules:
- `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-keyservers.cjs` implements bounded HTTPS lookup and publication for VKS and HKP-compatible servers.
- `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.
Key-server enablement is persisted in encrypted OpenPGP settings; all servers default to disabled, including custom servers already configured by older versions. The main process enforces enabled status for both lookup and publication. A lookup queries all enabled servers, reports partial failures, and merges duplicate fingerprints while retaining source names. The user chooses one enabled server as the publication target. Custom HTTPS endpoints require a native confirmation when added; redirects and oversized responses are rejected. Returned keys are validated and remain untrusted until the user verifies their fingerprints out of band. Publishing sends only public key material and requires a native confirmation naming the destination for each publication.
## 5. Data flow patterns
- Account setup and edits flow from the UI into IPC, then into the encrypted main-process storage.
- Mail content is fetched by the native mail service and passed to the renderer as plain text, bounded HTML alternatives, links, and attachment metadata. HTML is allowlist-sanitized before display; HTTPS image requests remain inert until explicitly enabled for the current message view.
- Attachments, decrypted bodies, and external links are all checked before user-visible actions are allowed.
- Search, folder listing, and draft operations reuse the same account model across both desktop and Android versions.
## 6. Release and packaging model
The project packages multiple platforms from the same codebase:
- `npm run dist:win` for Windows installer/portable builds
- `npm run dist:linux` for Linux AppImage and Debian builds
- Android builds via Capacitor (`npm run android:apk`)
The app version is managed through package metadata and the Electron build config in `package.json`.
## 7. Key architectural principles
- Keep privileged operations in the main process.
- Keep security rules in trusted code rather than the UI.
- Store secrets in OS-backed secure storage whenever the platform supports it.
- Share the same account and sync model between desktop and Android where possible.
- Treat mail encryption and secure key handling as first-class product features, not optional extras.
This architecture is intentionally built for a mail client that must handle privacy-sensitive data, background sync, and cross-platform parity without exposing the network or crypto stack to the renderer.
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.
Key-server enablement is persisted in encrypted OpenPGP settings; all servers default to disabled, including custom servers already configured by older versions. The main process enforces enabled status for both lookup and publication. A lookup queries all enabled servers, reports partial failures, and merges duplicate fingerprints while retaining source names. The user chooses one enabled server as the publication target. Custom HTTPS endpoints require a native confirmation when added; redirects and oversized responses are rejected. Returned keys are validated and remain untrusted until the user verifies their fingerprints out of band. Publishing sends only public key material and requires a native confirmation naming the destination for each publication.
## 5. Data flow patterns
- Account setup and edits flow from the UI into IPC, then into the encrypted main-process storage.
- Mail content is fetched by the native mail service and passed to the renderer as plain text, bounded HTML alternatives, links, and attachment metadata. HTML is allowlist-sanitized before display; HTTPS image requests remain inert until explicitly enabled for the current message view.
- Attachments, decrypted bodies, and external links are all checked before user-visible actions are allowed.
- Search, folder listing, and draft operations reuse the same account model across both desktop and Android versions.
## 6. Release and packaging model
The project packages multiple platforms from the same codebase:
- `npm run dist:win` for Windows installer/portable builds
- `npm run dist:linux` for Linux AppImage and Debian builds
- Android builds via Capacitor (`npm run android:apk`)
The app version is managed through package metadata and the Electron build config in `package.json`.
## 7. Key architectural principles
- Keep privileged operations in the main process.
- Keep security rules in trusted code rather than the UI.
- Store secrets in OS-backed secure storage whenever the platform supports it.
- Share the same account and sync model between desktop and Android where possible.
- Treat mail encryption and secure key handling as first-class product features, not optional extras.
This architecture is intentionally built for a mail client that must handle privacy-sensitive data, background sync, and cross-platform parity without exposing the network or crypto stack to the renderer.
+101 -101
View File
@@ -1,101 +1,101 @@
# Encryption plan: OpenPGP mail encryption for ep-mail
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android OpenPGP support and an independent human security review are still open. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
| Option | Pros | Cons |
|---|---|---|
| **OpenPGP** | Interoperates with Thunderbird, Proton, Mailvelope, GnuPG and K-9/OpenKeychain. No certificate authority needed. | Key verification is manual. |
| S/MIME | Native in Outlook and Apple Mail. | Needs CA-issued certificates; poor fit for personal accounts. |
Decision: OpenPGP only for v1; S/MIME may follow later.
- Library: [OpenPGP.js](https://github.com/openpgpjs/openpgpjs) (`openpgp`), pure JS, usable in Electron and the Android WebView.
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used.
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
- Out of scope for v1: Autocrypt headers and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
## 2. Key handling
**Private keys**
- One or more keys per account; never stored unprotected and never sent anywhere.
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4).
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk.
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
**Public keys**
- Per-account contact keyring: address, fingerprint, trust level, source.
- Sources: file import, attached to received mail, key-server lookup, and own key attached to outgoing mail.
- Trust: trust on first use, shown with the fingerprint, plus an explicit "verified" state after out-of-band comparison. Warn loudly when a known contact's key changes.
## 3. User experience
- Compose: lock toggle, on by default when every recipient has a key. Never silently downgrade; offer to send unencrypted or cancel.
- Reader: status line such as "Encrypted and signed by X (verified)" or a warning for bad/unknown signatures.
- Message list: lock icon for encrypted mail.
- Settings: **Encryption keys** (Phase 1) for create, import, export, delete.
- Interactions: search and rules cannot read encrypted bodies (subject/sender stay plaintext); do not cache decrypted bodies; run link warnings and attachment previews only after decryption; encrypt the Sent copy to the sender's own key too.
## 4. Threat model and limits
- Protects content from the mail server and network observers.
- Does not protect metadata (sender, recipients, subject, timestamps).
- A compromised device, or a stolen key plus passphrase, defeats it.
- Losing the key means losing access to old encrypted mail; backups are the user's responsibility.
## 5. Phases
| Phase | Scope | Status |
|---|---|---|
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) |
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open |
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
| 6 | Docs, security review, release | Docs and release done; independent review open |
## 6. Phase 1 implementation notes
- [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/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).
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
## 7. Phases 2–5 implementation notes
- [desktop/pgp-mail.cjs](./desktop/pgp-mail.cjs): detects PGP/MIME and inline PGP, decrypts, verifies signatures (inside encrypted mail, `multipart/signed` and cleartext), builds encrypted/signed PGP/MIME messages, and keeps an in-memory passphrase cache.
- [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.
- 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.
- 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.
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
- Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP).
- Limits: subjects and headers are not encrypted; drafts are stored unencrypted; opening encrypted attachments requires the passphrase to be remembered (see Settings → Encryption keys).
## 8. Risks
- Android WebView performance with large attachments (may need native handling).
- Key loss (backup flow, revocation certificate).
- User confusion about trust; keep states simple: unknown, trusted, verified.
- Decrypted HTML must not leak through remote content; blocking remote images by default should land first.
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
## 9. Public key servers (desktop)
The desktop Settings → Encryption keys view can search and publish through:
- **keys.openpgp.org** using its [VKS API](https://keys.openpgp.org/about/api/). Email lookup only returns keys whose email addresses have been verified. After an upload, ep-mail requests verification for the key's primary email address and reports whether verification is pending or already complete.
- **keys.mailvelope.com** using HKP over HTTPS as documented by the [Mailvelope key server](https://github.com/mailvelope/keyserver#hkp-api). The server sends its own email-verification message after accepting a key upload.
- **Custom servers** using an explicitly selected HKP or VKS protocol and an HTTPS base URL. Custom server configuration is saved with the encrypted OpenPGP settings.
All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification.
Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is not included because Android OpenPGP support is not implemented.
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
# Encryption plan: OpenPGP mail encryption for ep-mail
Status: **Desktop implementation is complete; an experimental Android Phase 2 path is available for local testing only.** It now includes per-key authentication-bound biometric/device-credential passphrase release, with passphrase fallback. Native confirmation prompts are implemented, but actual Android biometric/device testing, automated bypass testing, on-device interoperability, independent security review, and release assurance remain open. Do not use the Android test path for sensitive mail. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for details. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
| Option | Pros | Cons |
|---|---|---|
| **OpenPGP** | Interoperates with Thunderbird, Proton, Mailvelope, GnuPG and K-9/OpenKeychain. No certificate authority needed. | Key verification is manual. |
| S/MIME | Native in Outlook and Apple Mail. | Needs CA-issued certificates; poor fit for personal accounts. |
Decision: OpenPGP only for v1; S/MIME may follow later.
- Library: [OpenPGP.js](https://github.com/openpgpjs/openpgpjs) (`openpgp`), pure JS, usable in Electron and the Android WebView.
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used.
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
- Out of scope for v1: Autocrypt headers and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
## 2. Key handling
**Private keys**
- One or more keys per account; never stored unprotected and never sent anywhere.
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
- Android test implementation: private keys remain passphrase-protected inside the Keystore-encrypted vault. An optional per-key Android Keystore authentication-bound wrapper can release a cached PGP passphrase after biometric/device-credential authentication. This wrapper and its invalidation recovery have not been independently reviewed or fully device-tested; passphrase entry remains the fallback.
- Desktop passphrases are cached in memory for a configurable time, then cleared. Android never stores plaintext passphrases; its optional experimental biometric feature persists only the authentication-bound Keystore ciphertext. Both paths need platform-specific expiry/invalidation assurance before security claims.
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
**Public keys**
- Per-account contact keyring: address, fingerprint, trust level, source.
- Sources: file import, attached to received mail, key-server lookup, and own key attached to outgoing mail.
- Trust: trust on first use, shown with the fingerprint, plus an explicit "verified" state after out-of-band comparison. Warn loudly when a known contact's key changes.
## 3. User experience
- Compose: lock toggle, on by default when every recipient has a key. Never silently downgrade; offer to send unencrypted or cancel.
- Reader: status line such as "Encrypted and signed by X (verified)" or a warning for bad/unknown signatures.
- Message list: lock icon for encrypted mail.
- Settings: **Encryption keys** (Phase 1) for create, import, export, delete.
- Interactions: search and rules cannot read encrypted bodies (subject/sender stay plaintext); do not cache decrypted bodies; run link warnings and attachment previews only after decryption; encrypt the Sent copy to the sender's own key too.
## 4. Threat model and limits
- Protects content from the mail server and network observers.
- Does not protect metadata (sender, recipients, subject, timestamps).
- A compromised device, or a stolen key plus passphrase, defeats it.
- Losing the key means losing access to old encrypted mail; backups are the user's responsibility.
## 5. Phases
| Phase | Scope | Status |
|---|---|---|
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) |
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android test path implemented, review/device assurance open |
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
| 6 | Docs, security review, release | Docs and release done; independent review open |
## 6. Phase 1 implementation notes
- [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/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`.
- [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)).
## 7. Phases 2–5 implementation notes
- [desktop/pgp-mail.cjs](./desktop/pgp-mail.cjs): detects PGP/MIME and inline PGP, decrypts, verifies signatures (inside encrypted mail, `multipart/signed` and cleartext), builds encrypted/signed PGP/MIME messages, and keeps an in-memory passphrase cache.
- [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.
- 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'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.
- 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).
- Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP).
- Limits: subjects and headers are not encrypted; drafts are stored unencrypted; opening encrypted attachments requires the passphrase to be remembered (see Settings → Encryption keys).
## 8. Risks
- Android WebView performance with large attachments (may need native handling).
- Key loss (backup flow, revocation certificate).
- User confusion about trust; keep states simple: unknown, trusted, verified.
- Decrypted HTML must not leak through remote content; blocking remote images by default should land first.
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
## 9. Public key servers (desktop)
The desktop Settings → Encryption keys view can search and publish through:
- **keys.openpgp.org** using its [VKS API](https://keys.openpgp.org/about/api/). Email lookup only returns keys whose email addresses have been verified. After an upload, ep-mail requests verification for the key's primary email address and reports whether verification is pending or already complete.
- **keys.mailvelope.com** using HKP over HTTPS as documented by the [Mailvelope key server](https://github.com/mailvelope/keyserver#hkp-api). The server sends its own email-verification message after accepting a key upload.
- **Custom servers** using an explicitly selected HKP or VKS protocol and an HTTPS base URL. Custom server configuration is saved with the encrypted OpenPGP settings.
All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification.
Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is intentionally disabled in the experimental Android scope.
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
+43 -29
View File
@@ -1,42 +1,56 @@
# ep-mail
An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, snooze reminders, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
# ep-mail
An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and EP themes. It includes an inbox, message reader, search, starring, snooze reminders, archive and trash actions, compose/reply/forward, contacts, and a month calendar.
## Desktop app
The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
On Windows, `npm run build` runs `scripts\build.ps1`, building the Android debug APK and Windows portable executable. For all targets, run `npm run build:all`: it also builds the Windows installer and uses the default WSL distribution to build the Linux AppImage and Debian package. To select a distribution, run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-all.ps1 -WslDistribution Ubuntu`. WSL needs Linux Node.js, npm and tar, plus the usual Electron packaging prerequisites and network access to install the locked dependencies. Linux builds use a temporary Linux filesystem workspace, then copy both packages into `release\`. Both build scripts preserve the legacy `ep-mail <version>.apk` copy of the debug APK; it is **not a signed release APK** and will overwrite a same-named signed APK. Use `npm run android:release-apk` afterwards when a signed release is needed.
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
### 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.
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
## Android app
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
npm install
npm run android:apk
```
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
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.
For Android OpenPGP testing, transfer a passphrase-protected, ASCII-armored private key (`.asc`) securely to the device. In **Settings → Encryption keys**, enter its passphrase, select **Import private key from file…**, and choose the file (maximum 200,000 bytes). The file picker is unavailable while app lock is enabled because leaving the app can reset the import; paste the key instead, or temporarily disable app lock and re-enable it after importing. Compare the imported fingerprint with the original, then remove the transferred file and clear the clipboard if used. Keep a separate secure backup of the key and its revocation certificate.
Android builds use the Gradle wrapper and Android Gradle Plugin 9.4.0. Capacitor's generated modules are aligned to that plugin version during the build; the legacy Android DSL and external Kotlin plugin remain enabled for compatibility and must be migrated before upgrading to AGP 10.
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
On Android, previously cached folder messages appear while the mailbox refreshes; a folder without cached messages still needs to load from the server. Folder discovery and message actions run separately from cached-folder loading. The app stays in the message list until you select a message; returning to the list does not automatically reopen the newest message.
## Android app
While reading a message on Android, swipe in from the screen edge using the system Back gesture, or use the Back button in the reader, to return to the same position in the message list.
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:
In connected IMAP folders, scrolling to the end of the message list loads the next page automatically. The **Load more** button remains available as a manual fallback. On Android, background refreshes wait while you browse down the list so they do not replace older messages; return to the top or press Refresh to apply pending updates.
```sh
npm install
npm run android:apk
```
After upgrading from an older Android build, close and reopen ep-mail once if it still shows the previous interface. This lets the updated offline app shell take control without clearing account data.
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.
## Run on Windows or Linux
Install Python 3, open a terminal in this folder, and run:
```sh
python -m http.server 8000
```
On Windows, `py -m http.server 8000` is also available on many Python installations. Visit `http://localhost:8000` in a current browser. Use the browser's **Install app** option to add ep-mail as a standalone desktop app. The service worker caches the app shell for offline use after the first visit.
## 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`.
## Run on Windows or Linux
Install Python 3, open a terminal in this folder, and run:
```sh
python -m http.server 8000
```
On Windows, `py -m http.server 8000` is also available on many Python installations. Visit `http://localhost:8000` in a current browser. Use the browser's **Install app** option to add ep-mail as a standalone desktop app. The service worker caches the app shell for offline use after the first visit.
## 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 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`.
+2 -2
View File
@@ -171,7 +171,7 @@ IPC modules should validate and translate renderer requests, then call services.
- 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.4.39`; Android derives `versionName 0.4.39` and `versionCode 439`. OAuth2 desktop support is in this source version; the artifact still needs to be built and verified.
- 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
@@ -212,7 +212,7 @@ IPC modules should validate and translate renderer requests, then call services.
- 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.4.39` uses configurable OAuth client IDs, PKCE, encrypted token persistence, and provider-fixed mail endpoints.
- 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.
+59 -49
View File
@@ -1,67 +1,77 @@
# Security review: OpenPGP encryption
# Security review: OpenPGP encryption
Date: 2026-10-08
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.
> **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
- `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust
- `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache
## Scope
- `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust
- `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache
- `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`, and the `window.epMailFeatures.pgp.prepareSend` feature hook used by `mail-ui.js`.
- 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.
## Findings
| # | Severity | File | Issue | Confidence | Status |
|---|----------|------|-------|------------|--------|
| 1 | 🟡 MEDIUM | `pgp-mail-ui.js`, `mail-ui.js` | Encrypt-by-default is applied after a 300 ms debounced key lookup. Sending before it finished skipped the key check and sent the message unencrypted. | 9/10 | Fixed |
| 2 | 🟡 MEDIUM | `desktop/preload.cjs`, `desktop/main.cjs`, `desktop/pgp-keystore.cjs` | A compromised renderer could add a public key for a recipient's address and call `pgp:set-trust` to mark it verified. Recipient key selection prefers higher trust, so later mail could be encrypted to the attacker's key. The confirmation existed only in the renderer UI. | 8/10 | Fixed |
No critical or high severity issues were reported.
## Fixes applied
- 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.
## Findings
| # | Severity | File | Issue | Confidence | Status |
|---|----------|------|-------|------------|--------|
| 1 | 🟡 MEDIUM | `pgp-mail-ui.js`, `mail-ui.js` | Encrypt-by-default is applied after a 300 ms debounced key lookup. Sending before it finished skipped the key check and sent the message unencrypted. | 9/10 | Fixed |
| 2 | 🟡 MEDIUM | `desktop/preload.cjs`, `desktop/main.cjs`, `desktop/pgp-keystore.cjs` | A compromised renderer could add a public key for a recipient's address and call `pgp:set-trust` to mark it verified. Recipient key selection prefers higher trust, so later mail could be encrypted to the attacker's key. The confirmation existed only in the renderer UI. | 8/10 | Fixed |
No critical or high severity issues were reported.
## Fixes applied
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 at the original review time
- `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests).
- `node --check` on the edited files.
- The fixes were not exercised in the running app.
- `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests).
- `node --check` on the edited files.
- The fixes were not exercised in the running app.
## 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. This was still open at the time; see the later review pass below.
- Run `npm audit` and pin the OpenPGP.js version.
- Re-run the GnuPG interoperability tests after dependency updates.
- Android has no encryption support yet, so it was not reviewed.
## Second review pass (2026-10-09)
Fresh review of the same scope after the first round of fixes. Tests: 20 passed, 0 failed. No code was changed in this pass.
| # | Severity | File | Issue | Confidence | Status |
|---|----------|------|-------|------------|--------|
| 3 | 🟡 MEDIUM | `desktop/pgp-keystore.cjs`, `desktop/main.cjs` | `pgp:add-contact` adds a key for an address that already has one without a main-process confirmation. At equal trust the newest key wins recipient selection, so an added key can take over outgoing encryption. The trust dialog does not cover replacement. | 9/10 | Fixed |
| 4 | 🟡 MEDIUM | `desktop/main.cjs`, `desktop/preload.cjs` | The send-time downgrade check exists only in the renderer. `mail:send` sends plaintext when `pgp` is omitted, so a compromised renderer can bypass the warning. | 9/10 | Fixed |
| 5 | 🟡 MEDIUM | `desktop/main.cjs` | `safeStorage` is used without checking the backend. On Linux the `basic_text` backend uses a hardcoded password, so a copied store would expose account credentials and mail data. PGP private keys stay protected by their own passphrases. | 8/10 | Fixed |
- Run `npm audit` and pin the OpenPGP.js version.
- Re-run the GnuPG interoperability tests after dependency updates.
- Android has no encryption support yet, so it was not reviewed.
## Second review pass (2026-10-09)
Fresh review of the same scope after the first round of fixes. Tests: 20 passed, 0 failed. No code was changed in this pass.
| # | Severity | File | Issue | Confidence | Status |
|---|----------|------|-------|------------|--------|
| 3 | 🟡 MEDIUM | `desktop/pgp-keystore.cjs`, `desktop/main.cjs` | `pgp:add-contact` adds a key for an address that already has one without a main-process confirmation. At equal trust the newest key wins recipient selection, so an added key can take over outgoing encryption. The trust dialog does not cover replacement. | 9/10 | Fixed |
| 4 | 🟡 MEDIUM | `desktop/main.cjs`, `desktop/preload.cjs` | The send-time downgrade check exists only in the renderer. `mail:send` sends plaintext when `pgp` is omitted, so a compromised renderer can bypass the warning. | 9/10 | Fixed |
| 5 | 🟡 MEDIUM | `desktop/main.cjs` | `safeStorage` is used without checking the backend. On Linux the `basic_text` backend uses a hardcoded password, so a copied store would expose account credentials and mail data. PGP private keys stay protected by their own passphrases. | 8/10 | Fixed |
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.
- #4: the main process checks recipient keys before allowing a plaintext send and shows a trusted confirmation dialog.
- #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.
- #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, dependency audit and OpenPGP.js version pinning remain outstanding. GnuPG interoperability tests are in the current test suite and should be rerun after dependency changes.
- Android has no OpenPGP implementation and is outside the reviewed desktop scope.
- 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.
+85 -67
View File
@@ -1,77 +1,95 @@
# TODO
## Product identity
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
- [x] Fix the ep-mail logo not appearing in the Windows taskbar.
- [x] Add Android support for the mail app.
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
- [x] Show the app version after **ep-mail** in the window title.
## Mail workflow
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
# TODO
## Product identity
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
- [x] Fix the ep-mail logo not appearing in the Windows taskbar.
- [x] Add Android support for the mail app.
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
- [x] Show the app version after **ep-mail** in the window title.
## Mail workflow
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
- [ ] Add a configurable Undo Send delay and scheduled sending.
- [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] 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.
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
- [x] Add per-account signatures, notification preferences, and sync settings.
- [x] Add the ability to create IMAP folders from the app.
- [x] Block remote images by default and let users load them per message on desktop and Android/Web.
## Mail security
- [x] Add desktop support for encrypting and decrypting mail with OpenPGP (PGP/MIME). Android support remains open; 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 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 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
- [ ] Phase 4 (Android): add Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
- [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 6: documentation and release.
- [x] Manual interoperability check with Thunderbird.
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
- [x] Add per-account signatures, notification preferences, and sync settings.
- [x] Add the ability to create IMAP folders from the app.
- [x] Block remote images by default and let users load them per message on desktop and Android/Web.
## Mail security
- [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 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 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
- [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption.
- [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.
- [x] Add optional per-key Android biometric/device-credential passphrase release with passphrase fallback.
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review.
- [ ] Android follow-up: device-test biometric prompt/key invalidation recovery, full vault lifecycle/recovery, remaining parity/device interoperability, and dependency advisory remediation.
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
- [x] Phase 6: documentation and release.
- [x] Manual interoperability check with Thunderbird.
- [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)).
- [ ] Complete an independent human security review of the encryption code before expanding OpenPGP support to Android.
- [ ] Complete an independent human security review of 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.
## Appearance and settings
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
- [x] Make **EP Wasteland** the default theme for new users.
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
- [x] Keep the display name in Account Settings and make it available while adding a mailbox.
- [ ] 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 process/lifecycle tests and decide whether to add biometric unlock to the separate app lock (PGP per-key biometric release is implemented experimentally).
## Appearance and settings
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
- [x] Make **EP Wasteland** the default theme for new users.
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
- [x] Keep the display name in Account Settings and make it available while adding a mailbox.
## 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.
- [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] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
- [ ] Add push mail support.
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
- [x] Add new mail notifications.
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
- [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
- [x] Display name must be set per account.
- [x] Remove the display name initials from the bottom-left corner.
- [x] Add the ability to delete draft mails.
- [x] Fix IMAP folder creation, which does not work.
- [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] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
- [ ] Add push mail support.
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
- [x] Add new mail notifications.
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
- [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
- [x] Display name must be set per account.
- [x] Remove the display name initials from the bottom-left corner.
- [x] Add the ability to delete draft mails.
- [x] Fix IMAP folder creation, which does not work.
- [ ] Improve sidebar usability so all folders fit or can be reached by scrolling; consider collapsing less-used sections.
- [ ] 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 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] Add desktop public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKP over HTTPS), and user-defined HTTPS HKP/VKS servers. Servers are disabled until selected; lookup checks all enabled servers, and publishing requires one explicitly selected destination. Discovered keys remain unverified until fingerprint verification.
- [x] Add the ability to attach multiple files to outgoing mails on desktop and Android/Web, persist them in local drafts, and include them within desktop OpenPGP protection.
- [x] Fix security review findings: confirm key replacement in the main process, enforce the plaintext-send check in the main process, and handle the Linux safeStorage basic_text backend. See SECURITY_REVIEW.md.
- [x] Add the ability to change the passphrase of an encryption key on desktop.
- [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] 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] Add desktop public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKP over HTTPS), and user-defined HTTPS HKP/VKS servers. Servers are disabled until selected; lookup checks all enabled servers, and publishing requires one explicitly selected destination. Discovered keys remain unverified until fingerprint verification.
- [x] Add the ability to attach multiple files to outgoing mails on desktop and Android/Web, persist them in local drafts, and include them within desktop OpenPGP protection.
- [x] Fix security review findings: confirm key replacement in the main process, enforce the plaintext-send check in the main process, and handle the Linux safeStorage basic_text backend. See SECURITY_REVIEW.md.
- [x] Add the ability to change the passphrase of an encryption key on desktop.
+20 -20
View File
@@ -3,29 +3,29 @@ const accountMailUi = window.epMailFeatures.mail;
const accountDavUi = window.epMailFeatures.dav;
async function openAccountManager(){
const root=accountMailUi.select('#modal-root');
try{
const data=await window.daybreakMail.listAccounts();
const accounts=data.accounts||[];
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>`;
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 root=accountMailUi.select('#modal-root');
try{
const data=await window.daybreakMail.listAccounts();
const accounts=data.accounts||[];
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>`;
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-mail-account').onclick=()=>{close();accountMailUi.openMailAccount()};
root.onclick=async event=>{
const switchButton=event.target.closest('[data-switch-account]');
root.onclick=async event=>{
const switchButton=event.target.closest('[data-switch-account]');
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();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)accountMailUi.openMailAccount(account);return}
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;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){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);
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?\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){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('keydown',event=>{const card=event.target.closest('#account-settings');if(!card||!['Enter',' '].includes(event.key))return;event.preventDefault();event.stopImmediatePropagation();openAccountManager()},true);
})();
+101 -101
View File
@@ -1,101 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2 -2
View File
@@ -1,2 +1,2 @@
/build/*
!/build/.npmkeep
/build/*
!/build/.npmkeep
+104 -78
View File
@@ -1,78 +1,104 @@
apply plugin: 'com.android.application'
apply plugin: 'org.jetbrains.kotlin.android'
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
android {
namespace = "studio.daybreak.mail"
compileSdk = rootProject.ext.compileSdkVersion
buildFeatures {
buildConfig true
}
packaging {
resources {
pickFirsts += "META-INF/NOTICE.md"
pickFirsts += "META-INF/LICENSE.md"
}
}
defaultConfig {
applicationId "studio.daybreak.mail"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2]
versionName appVersion
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
kotlinOptions {
jvmTarget = '21'
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
implementation 'com.sun.mail:android-mail:1.6.7'
implementation 'com.sun.mail:android-activation:1.6.7'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'androidx.work:work-runtime-ktx:2.10.1'
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
apply plugin: 'com.android.application'
apply plugin: 'org.jetbrains.kotlin.android'
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
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 {
namespace = "studio.daybreak.mail"
compileSdk = rootProject.ext.compileSdkVersion
buildFeatures {
buildConfig true
}
if (hasCompleteReleaseSigning) {
signingConfigs {
release {
storeFile file(releaseStoreFile)
storePassword releaseStorePassword
keyAlias releaseKeyAlias
keyPassword releaseKeyPassword
}
}
}
packaging {
resources {
pickFirsts += "META-INF/NOTICE.md"
pickFirsts += "META-INF/LICENSE.md"
}
}
defaultConfig {
applicationId "studio.daybreak.mail"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2]
versionName appVersion
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
if (hasCompleteReleaseSigning) signingConfig signingConfigs.release
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
kotlinOptions {
jvmTarget = '21'
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation 'androidx.biometric:biometric:1.1.0'
implementation project(':capacitor-android')
implementation 'com.sun.mail:android-mail:1.6.7'
implementation 'com.sun.mail:android-activation:1.6.7'
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'androidx.work:work-runtime-ktx:2.10.1'
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
+21 -21
View File
@@ -1,21 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -1,26 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
+40 -47
View File
@@ -1,48 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<application
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MailIdleService"
android:exported="false"
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>
</manifest>
android:dataExtractionRules="@xml/data_extraction_rules"
android:usesCleartextTraffic="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MailIdleService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,11 @@
package studio.daybreak.mail
internal object AndroidAppLockPolicy {
val allowedDelaySeconds = setOf(0, 30, 60, 300)
fun requireValidDelay(seconds: Int) {
require(seconds in allowedDelaySeconds) {
"Choose a supported app-lock delay."
}
}
}
@@ -1,443 +1,437 @@
package studio.daybreak.mail
import android.util.Base64
import org.json.JSONArray
import org.json.JSONObject
import org.w3c.dom.Element
import java.io.ByteArrayInputStream
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.Locale
import java.util.UUID
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit
import javax.xml.parsers.DocumentBuilderFactory
internal object AndroidDavService {
package studio.daybreak.mail
import android.util.Base64
import org.json.JSONArray
import org.json.JSONObject
import org.w3c.dom.Element
import java.io.ByteArrayInputStream
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.Locale
import java.util.UUID
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import java.util.concurrent.TimeUnit
import javax.xml.parsers.DocumentBuilderFactory
internal object AndroidDavService {
private val httpClient = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.followRedirects(false)
.followSslRedirects(false)
.build()
fun list(): JSONObject {
val store = AndroidAccountVault.read()
return JSONObject()
.put("caldav", AndroidAccountVault.publicDavAccounts("caldav"))
.put("carddav", AndroidAccountVault.publicDavAccounts("carddav"))
.put("activeCaldavId", store.optString("activeCaldavId"))
.put("activeCarddavId", store.optString("activeCarddavId"))
fun list(): JSONObject {
val store = AndroidAccountVault.read()
return JSONObject()
.put("caldav", AndroidAccountVault.publicDavAccounts("caldav"))
.put("carddav", AndroidAccountVault.publicDavAccounts("carddav"))
.put("activeCaldavId", store.optString("activeCaldavId"))
.put("activeCarddavId", store.optString("activeCarddavId"))
}
fun connect(input: JSONObject): JSONObject {
val type = type(input.optString("type"))
val serverUrl = input.optString("serverUrl").trim()
val username = input.optString("username").trim()
val password = input.optString("password")
val url = DavUrlPolicy.parseServerUrl(serverUrl)
require(username.isNotBlank() && password.isNotBlank()) { "Enter the DAV username and password." }
val collections = discoverCollections(url.toString(), username, password, type)
require(collections.length() > 0) {
"No ${if (type == "caldav") "calendars" else "address books"} were found on this server."
}
val account = JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", type)
.put("serverUrl", url.toString())
.put("username", username)
.put("password", password)
.put("collections", collections)
val saved = AndroidAccountVault.putDavAccount(type, account)
val publicConfig = publicDav(saved)
return JSONObject()
.put("config", publicConfig)
.put("collections", collections)
.put("accounts", list())
}
fun activate(typeInput: String, id: String): JSONObject {
val type = type(typeInput)
val config = AndroidAccountVault.activeDav(type, id)
?: throw IllegalStateException("That DAV account could not be found.")
val store = AndroidAccountVault.read()
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", config.optString("id"))
AndroidAccountVault.write(store)
return JSONObject().put("id", config.optString("id"))
}
fun remove(typeInput: String, id: String): JSONObject =
AndroidAccountVault.removeDavAccount(type(typeInput), id)
fun sync(typeInput: String): JSONObject {
val type = type(typeInput)
val account = AndroidAccountVault.activeDav(type)
?: throw IllegalStateException("Connect a ${if (type == "caldav") "CalDAV" else "CardDAV"} server first.")
val collectionKey = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val collections = account.optJSONArray("collections") ?: JSONArray()
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
val objects = listObjects(account, collection, type)
for (obj in objects) {
val href = obj.optString("href")
val data = obj.optString("data")
if (data.isBlank()) continue
if (type == "caldav") parseCalendar(data, account, collection, obj).forEach(result::put)
else parseContacts(data, account, collection, obj).forEach(result::put)
}
}
return JSONObject().put("items", result).put("account", publicDav(account))
.put("collectionType", collectionKey)
}
fun saveEvent(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable calendar was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.ics"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val data = calendarData(input, uid)
val response = request(account, target, "PUT", data, mapOf("Content-Type" to "text/calendar; charset=utf-8"))
require(response.code in 200..299) { "The calendar server rejected the event (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteEvent(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId"))
?: throw IllegalStateException("That calendar account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The calendar server rejected the deletion (${response.code})." }
}
fun saveContact(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable address book was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.vcf"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val response = request(account, target, "PUT", vcardData(input, uid), mapOf("Content-Type" to "text/vcard; charset=utf-8"))
require(response.code in 200..299) { "The address book server rejected the contact (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteContact(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId"))
?: throw IllegalStateException("That address book account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The address book server rejected the deletion (${response.code})." }
}
private data class HttpResult(val code: Int, val body: ByteArray, val headers: Map<String, String>)
private fun request(
account: JSONObject,
address: String,
method: String,
body: String?,
headers: Map<String, String> = emptyMap()
): HttpResult {
DavUrlPolicy.requireSameOrigin(account.optString("serverUrl"), address)
val requestBody = body?.toRequestBody(headers["Content-Type"]?.toMediaTypeOrNull())
val builder = Request.Builder()
.url(address)
.header("Authorization", basicAuth(account))
.header("User-Agent", "ep-mail-Android")
for ((key, value) in headers) builder.header(key, value)
builder.method(method, requestBody)
httpClient.newCall(builder.build()).execute().use { response ->
val bytes = response.body?.bytes() ?: ByteArray(0)
val responseHeaders = response.headers.toMultimap().mapValues { (_, values) -> values.firstOrNull().orEmpty() }
return HttpResult(response.code, bytes, responseHeaders)
}
}
private fun discoverCollections(serverUrl: String, username: String, password: String, type: String): JSONArray {
val base = JSONObject().put("serverUrl", serverUrl).put("username", username).put("password", password)
val setName = if (type == "caldav") "calendar-home-set" else "addressbook-home-set"
val rootResponse = request(base, serverUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
require(rootResponse.code in 200..299 || rootResponse.code == 207) {
"Could not access the DAV server (${rootResponse.code})."
}
val rootDocument = parseXml(rootResponse.body)
var homeUrl = findHref(rootDocument, setName)?.let { resolveUrl(serverUrl, it) }
if (homeUrl == null) {
val principal = findHref(rootDocument, "current-user-principal")
if (principal != null) {
val principalUrl = resolveUrl(serverUrl, principal)
val principalResponse = request(base, principalUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
if (principalResponse.code in 200..299 || principalResponse.code == 207) {
homeUrl = findHref(parseXml(principalResponse.body), setName)?.let { resolveUrl(principalUrl, it) }
}
}
}
val collectionUrl = homeUrl ?: serverUrl
val response = request(base, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not discover DAV collections (${response.code})."
}
val document = parseXml(response.body)
val requiredType = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val responses = document.getElementsByTagNameNS("*", "response")
for (index in 0 until responses.length) {
val responseElement = responses.item(index) as? Element ?: continue
val href = childText(responseElement, "href") ?: continue
if (responseElement.getElementsByTagNameNS("*", requiredType).length == 0) continue
val resolved = resolveUrl(collectionUrl, href)
val displayName = textContent(responseElement, "displayname").orEmpty().ifBlank { resolved }
result.put(JSONObject().put("url", resolved).put("name", displayName))
}
return result
}
private fun listObjects(account: JSONObject, collection: JSONObject, type: String): List<JSONObject> {
val collectionUrl = collection.optString("url")
val response = request(account, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not read DAV collection ${collection.optString("name")} (${response.code})."
}
val document = parseXml(response.body)
val responses = document.getElementsByTagNameNS("*", "response")
val result = ArrayList<JSONObject>()
for (index in 0 until responses.length) {
val element = responses.item(index) as? Element ?: continue
val href = childText(element, "href") ?: continue
val objectUrl = resolveUrl(collectionUrl, href)
if (objectUrl.trimEnd('/') == collectionUrl.trimEnd('/')) continue
val data = if (type == "caldav") textContent(element, "calendar-data") else textContent(element, "address-data")
val content = if (!data.isNullOrBlank()) data else {
val fetched = request(account, objectUrl, "GET", null)
if (fetched.code !in 200..299) continue
String(fetched.body, StandardCharsets.UTF_8)
}
result.add(JSONObject()
.put("href", objectUrl)
.put("etag", textContent(element, "getetag").orEmpty())
.put("data", content))
}
return result
}
private fun parseCalendar(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val unfolded = unfold(data)
return Regex("BEGIN:VEVENT(.*?)END:VEVENT", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
.findAll(unfolded).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val uid = fields["UID"].orEmpty().ifBlank { UUID.randomUUID().toString() }
val (date, time) = parseDate(fields["DTSTART"].orEmpty()) ?: return@mapNotNull null
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("title", unescape(fields["SUMMARY"].orEmpty()).ifBlank { "(no title)" })
.put("date", date)
.put("time", time)
.put("with", Regex("(?im)^ATTENDEE[^:]*:(?:mailto:)?([^\\r\\n]+)").findAll(block)
.map { it.groupValues[1].trim() }.joinToString(", "))
.put("place", unescape(fields["LOCATION"].orEmpty()))
.put("notes", unescape(fields["DESCRIPTION"].orEmpty()))
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun parseContacts(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val cards = Regex("BEGIN:VCARD(.*?)END:VCARD", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
return cards.findAll(unfold(data)).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val name = unescape(fields["FN"].orEmpty()).trim()
if (name.isBlank()) return@mapNotNull null
val uid = fields["UID"].orEmpty()
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("name", name)
.put("email", unescape(fields["EMAIL"].orEmpty()))
.put("note", unescape(fields["NOTE"].orEmpty()))
.put("initials", name.split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.toString() }
.joinToString("").take(2).uppercase(Locale.getDefault()))
.put("color", "#dce9dd")
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun calendarData(event: JSONObject, uid: String): String {
val date = event.optString("date").replace("-", "")
val time = event.optString("time")
val start = if (time.isBlank()) "DTSTART;VALUE=DATE:$date" else "DTSTART;TZID=UTC:${date}T${time.replace(":", "")}00"
val end = if (time.isBlank()) "" else {
val parts = time.split(":")
val mins = (parts.getOrNull(0)?.toIntOrNull() ?: 0) * 60 + (parts.getOrNull(1)?.toIntOrNull() ?: 0) + 60
val endTime = "%04d%02d00".format(Locale.ROOT, (mins / 60) % 24, mins % 60)
"DTEND;TZID=UTC:${date}T$endTime\r\n"
}
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${escape(uid)}\r\nDTSTAMP:${utcNow()}\r\n$start\r\n$end${property("SUMMARY", event.optString("title"))}${property("LOCATION", event.optString("place"))}${property("DESCRIPTION", event.optString("notes"))}END:VEVENT\r\nEND:VCALENDAR\r\n"
}
private fun vcardData(contact: JSONObject, uid: String): String {
val name = contact.optString("name").trim().split(Regex("\\s+"))
val first = name.firstOrNull().orEmpty()
val last = name.drop(1).joinToString(" ")
return "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${escape(uid)}\r\nFN:${escape(contact.optString("name"))}\r\nN:${escape(last)};${escape(first)};;;\r\nEMAIL:${escape(contact.optString("email"))}\r\n${if (contact.optString("note").isNotBlank()) "NOTE:${escape(contact.optString("note"))}\r\n" else ""}END:VCARD\r\n"
}
private fun propfindBody(homeSet: String) = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:current-user-principal/><d:displayname/><c:$homeSet/><a:$homeSet/></d:prop>
</d:propfind>""".trimIndent()
private fun collectionBody() = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:resourcetype/><d:displayname/><d:getetag/><c:calendar-data/><a:address-data/></d:prop>
</d:propfind>""".trimIndent()
private fun parseXml(bytes: ByteArray): org.w3c.dom.Document {
val factory = DocumentBuilderFactory.newInstance().apply {
isNamespaceAware = true
isXIncludeAware = false
isExpandEntityReferences = false
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
setFeature("http://xml.org/sax/features/external-general-entities", false)
setFeature("http://xml.org/sax/features/external-parameter-entities", false)
}
return factory.newDocumentBuilder().parse(ByteArrayInputStream(bytes))
}
private fun findHref(document: org.w3c.dom.Document, propertyName: String): String? {
val elements = document.getElementsByTagNameNS("*", propertyName)
for (index in 0 until elements.length) {
val href = (elements.item(index) as? Element)?.getElementsByTagNameNS("*", "href")?.item(0)?.textContent
if (!href.isNullOrBlank()) return href.trim()
}
return null
}
private fun textContent(element: Element, propertyName: String): String? {
val nodes = element.getElementsByTagNameNS("*", propertyName)
return if (nodes.length == 0) null else nodes.item(0)?.textContent?.trim()
}
private fun childText(element: Element, childName: String): String? {
val children = element.childNodes
for (index in 0 until children.length) {
val node = children.item(index)
if (node is Element && node.localName == childName) return node.textContent.trim()
}
return null
}
private fun resolveUrl(base: String, href: String): String = URL(URL(base), href).toString()
private fun basicAuth(account: JSONObject): String {
val raw = "${account.optString("username")}:${account.optString("password")}"
return "Basic " + Base64.encodeToString(raw.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
}
private fun publicDav(account: JSONObject) = JSONObject()
.put("id", account.optString("id"))
.put("serverUrl", account.optString("serverUrl"))
.put("username", account.optString("username"))
.put("collections", account.optJSONArray("collections") ?: JSONArray())
private fun type(value: String) = when (value) {
"caldav", "carddav" -> value
else -> throw IllegalArgumentException("Choose a supported CalDAV or CardDAV account.")
}
fun connect(input: JSONObject): JSONObject {
val type = type(input.optString("type"))
val serverUrl = input.optString("serverUrl").trim()
val username = input.optString("username").trim()
val password = input.optString("password")
val url = try { URL(serverUrl) } catch (_: Exception) {
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." }
val collections = discoverCollections(url.toString(), username, password, type)
require(collections.length() > 0) {
"No ${if (type == "caldav") "calendars" else "address books"} were found on this server."
}
val account = JSONObject()
.put("id", UUID.randomUUID().toString())
.put("type", type)
.put("serverUrl", url.toString())
.put("username", username)
.put("password", password)
.put("collections", collections)
val saved = AndroidAccountVault.putDavAccount(type, account)
val publicConfig = publicDav(saved)
return JSONObject()
.put("config", publicConfig)
.put("collections", collections)
.put("accounts", list())
}
fun activate(typeInput: String, id: String): JSONObject {
val type = type(typeInput)
val config = AndroidAccountVault.activeDav(type, id)
?: throw IllegalStateException("That DAV account could not be found.")
val store = AndroidAccountVault.read()
store.put(if (type == "caldav") "activeCaldavId" else "activeCarddavId", config.optString("id"))
AndroidAccountVault.write(store)
return JSONObject().put("id", config.optString("id"))
}
fun remove(typeInput: String, id: String): JSONObject =
AndroidAccountVault.removeDavAccount(type(typeInput), id)
fun sync(typeInput: String): JSONObject {
val type = type(typeInput)
val account = AndroidAccountVault.activeDav(type)
?: throw IllegalStateException("Connect a ${if (type == "caldav") "CalDAV" else "CardDAV"} server first.")
val collectionKey = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val collections = account.optJSONArray("collections") ?: JSONArray()
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
val objects = listObjects(account, collection, type)
for (obj in objects) {
val href = obj.optString("href")
val data = obj.optString("data")
if (data.isBlank()) continue
if (type == "caldav") parseCalendar(data, account, collection, obj).forEach(result::put)
else parseContacts(data, account, collection, obj).forEach(result::put)
}
}
return JSONObject().put("items", result).put("account", publicDav(account))
.put("collectionType", collectionKey)
}
fun saveEvent(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable calendar was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.ics"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val data = calendarData(input, uid)
val response = request(account, target, "PUT", data, mapOf("Content-Type" to "text/calendar; charset=utf-8"))
require(response.code in 200..299) { "The calendar server rejected the event (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteEvent(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("caldav", remote.optString("accountId"))
?: throw IllegalStateException("That calendar account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The calendar server rejected the deletion (${response.code})." }
}
fun saveContact(input: JSONObject): JSONObject? {
val remote = input.optJSONObject("_dav") ?: JSONObject()
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId").ifBlank { null }) ?: return null
val collections = account.optJSONArray("collections") ?: JSONArray()
val collection = findCollection(collections, remote.optString("collectionUrl"))
?: throw IllegalStateException("No writable address book was found.")
val uid = remote.optString("uid").ifBlank { UUID.randomUUID().toString() }
val filename = "$uid.vcf"
val collectionUrl = collection.optString("url")
val target = remote.optString("objectUrl").ifBlank { collectionUrl.trimEnd('/') + "/" + filename }
val response = request(account, target, "PUT", vcardData(input, uid), mapOf("Content-Type" to "text/vcard; charset=utf-8"))
require(response.code in 200..299) { "The address book server rejected the contact (${response.code})." }
return JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collectionUrl)
.put("objectUrl", target)
.put("etag", response.headers["etag"] ?: remote.optString("etag"))
.put("uid", uid)
}
fun deleteContact(remote: JSONObject) {
val account = AndroidAccountVault.activeDav("carddav", remote.optString("accountId"))
?: throw IllegalStateException("That address book account could not be found.")
val url = remote.optString("objectUrl")
if (url.isBlank()) return
val response = request(account, url, "DELETE", null)
require(response.code in 200..299 || response.code == 404) { "The address book server rejected the deletion (${response.code})." }
}
private data class HttpResult(val code: Int, val body: ByteArray, val headers: Map<String, String>)
private fun request(
account: JSONObject,
address: String,
method: String,
body: String?,
headers: Map<String, String> = emptyMap()
): HttpResult {
val target = URL(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 builder = Request.Builder()
.url(address)
.header("Authorization", basicAuth(account))
.header("User-Agent", "ep-mail-Android")
for ((key, value) in headers) builder.header(key, value)
builder.method(method, requestBody)
httpClient.newCall(builder.build()).execute().use { response ->
val bytes = response.body?.bytes() ?: ByteArray(0)
val responseHeaders = response.headers.toMultimap().mapValues { (_, values) -> values.firstOrNull().orEmpty() }
return HttpResult(response.code, bytes, responseHeaders)
}
}
private fun discoverCollections(serverUrl: String, username: String, password: String, type: String): JSONArray {
val base = JSONObject().put("serverUrl", serverUrl).put("username", username).put("password", password)
val setName = if (type == "caldav") "calendar-home-set" else "addressbook-home-set"
val rootResponse = request(base, serverUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
require(rootResponse.code in 200..299 || rootResponse.code == 207) {
"Could not access the DAV server (${rootResponse.code})."
}
val rootDocument = parseXml(rootResponse.body)
var homeUrl = findHref(rootDocument, setName)?.let { resolveUrl(serverUrl, it) }
if (homeUrl == null) {
val principal = findHref(rootDocument, "current-user-principal")
if (principal != null) {
val principalUrl = resolveUrl(serverUrl, principal)
val principalResponse = request(base, principalUrl, "PROPFIND", propfindBody(setName), mapOf(
"Depth" to "0",
"Content-Type" to "application/xml; charset=utf-8"
))
if (principalResponse.code in 200..299 || principalResponse.code == 207) {
homeUrl = findHref(parseXml(principalResponse.body), setName)?.let { resolveUrl(principalUrl, it) }
}
}
}
val collectionUrl = homeUrl ?: serverUrl
val response = request(base, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not discover DAV collections (${response.code})."
}
val document = parseXml(response.body)
val requiredType = if (type == "caldav") "calendar" else "addressbook"
val result = JSONArray()
val responses = document.getElementsByTagNameNS("*", "response")
for (index in 0 until responses.length) {
val responseElement = responses.item(index) as? Element ?: continue
val href = childText(responseElement, "href") ?: continue
if (responseElement.getElementsByTagNameNS("*", requiredType).length == 0) continue
val resolved = resolveUrl(collectionUrl, href)
val displayName = textContent(responseElement, "displayname").orEmpty().ifBlank { resolved }
result.put(JSONObject().put("url", resolved).put("name", displayName))
}
return result
}
private fun listObjects(account: JSONObject, collection: JSONObject, type: String): List<JSONObject> {
val collectionUrl = collection.optString("url")
val response = request(account, collectionUrl, "PROPFIND", collectionBody(), mapOf(
"Depth" to "1",
"Content-Type" to "application/xml; charset=utf-8"
))
require(response.code in 200..299 || response.code == 207) {
"Could not read DAV collection ${collection.optString("name")} (${response.code})."
}
val document = parseXml(response.body)
val responses = document.getElementsByTagNameNS("*", "response")
val result = ArrayList<JSONObject>()
for (index in 0 until responses.length) {
val element = responses.item(index) as? Element ?: continue
val href = childText(element, "href") ?: continue
val objectUrl = resolveUrl(collectionUrl, href)
if (objectUrl.trimEnd('/') == collectionUrl.trimEnd('/')) continue
val data = if (type == "caldav") textContent(element, "calendar-data") else textContent(element, "address-data")
val content = if (!data.isNullOrBlank()) data else {
val fetched = request(account, objectUrl, "GET", null)
if (fetched.code !in 200..299) continue
String(fetched.body, StandardCharsets.UTF_8)
}
result.add(JSONObject()
.put("href", objectUrl)
.put("etag", textContent(element, "getetag").orEmpty())
.put("data", content))
}
return result
}
private fun parseCalendar(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val unfolded = unfold(data)
return Regex("BEGIN:VEVENT(.*?)END:VEVENT", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
.findAll(unfolded).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val uid = fields["UID"].orEmpty().ifBlank { UUID.randomUUID().toString() }
val (date, time) = parseDate(fields["DTSTART"].orEmpty()) ?: return@mapNotNull null
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("title", unescape(fields["SUMMARY"].orEmpty()).ifBlank { "(no title)" })
.put("date", date)
.put("time", time)
.put("with", Regex("(?im)^ATTENDEE[^:]*:(?:mailto:)?([^\\r\\n]+)").findAll(block)
.map { it.groupValues[1].trim() }.joinToString(", "))
.put("place", unescape(fields["LOCATION"].orEmpty()))
.put("notes", unescape(fields["DESCRIPTION"].orEmpty()))
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun parseContacts(data: String, account: JSONObject, collection: JSONObject, resource: JSONObject): List<JSONObject> {
val cards = Regex("BEGIN:VCARD(.*?)END:VCARD", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))
return cards.findAll(unfold(data)).mapNotNull { match ->
val block = match.groupValues[1]
val fields = parseProperties(block)
val name = unescape(fields["FN"].orEmpty()).trim()
if (name.isBlank()) return@mapNotNull null
val uid = fields["UID"].orEmpty()
JSONObject()
.put("id", "dav:${account.optString("id")}:${encode(resource.optString("href"))}:${encode(uid)}")
.put("name", name)
.put("email", unescape(fields["EMAIL"].orEmpty()))
.put("note", unescape(fields["NOTE"].orEmpty()))
.put("initials", name.split(Regex("\\s+")).mapNotNull { it.firstOrNull()?.toString() }
.joinToString("").take(2).uppercase(Locale.getDefault()))
.put("color", "#dce9dd")
.put("_dav", JSONObject()
.put("accountId", account.optString("id"))
.put("collectionUrl", collection.optString("url"))
.put("objectUrl", resource.optString("href"))
.put("etag", resource.optString("etag"))
.put("uid", uid))
}.toList()
}
private fun calendarData(event: JSONObject, uid: String): String {
val date = event.optString("date").replace("-", "")
val time = event.optString("time")
val start = if (time.isBlank()) "DTSTART;VALUE=DATE:$date" else "DTSTART;TZID=UTC:${date}T${time.replace(":", "")}00"
val end = if (time.isBlank()) "" else {
val parts = time.split(":")
val mins = (parts.getOrNull(0)?.toIntOrNull() ?: 0) * 60 + (parts.getOrNull(1)?.toIntOrNull() ?: 0) + 60
val endTime = "%04d%02d00".format(Locale.ROOT, (mins / 60) % 24, mins % 60)
"DTEND;TZID=UTC:${date}T$endTime\r\n"
}
return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${escape(uid)}\r\nDTSTAMP:${utcNow()}\r\n$start\r\n$end${property("SUMMARY", event.optString("title"))}${property("LOCATION", event.optString("place"))}${property("DESCRIPTION", event.optString("notes"))}END:VEVENT\r\nEND:VCALENDAR\r\n"
}
private fun vcardData(contact: JSONObject, uid: String): String {
val name = contact.optString("name").trim().split(Regex("\\s+"))
val first = name.firstOrNull().orEmpty()
val last = name.drop(1).joinToString(" ")
return "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${escape(uid)}\r\nFN:${escape(contact.optString("name"))}\r\nN:${escape(last)};${escape(first)};;;\r\nEMAIL:${escape(contact.optString("email"))}\r\n${if (contact.optString("note").isNotBlank()) "NOTE:${escape(contact.optString("note"))}\r\n" else ""}END:VCARD\r\n"
}
private fun propfindBody(homeSet: String) = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:current-user-principal/><d:displayname/><c:$homeSet/><a:$homeSet/></d:prop>
</d:propfind>""".trimIndent()
private fun collectionBody() = """<?xml version="1.0" encoding="utf-8"?>
<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:a="urn:ietf:params:xml:ns:carddav">
<d:prop><d:resourcetype/><d:displayname/><d:getetag/><c:calendar-data/><a:address-data/></d:prop>
</d:propfind>""".trimIndent()
private fun parseXml(bytes: ByteArray): org.w3c.dom.Document {
val factory = DocumentBuilderFactory.newInstance().apply {
isNamespaceAware = true
isXIncludeAware = false
isExpandEntityReferences = false
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
setFeature("http://xml.org/sax/features/external-general-entities", false)
setFeature("http://xml.org/sax/features/external-parameter-entities", false)
}
return factory.newDocumentBuilder().parse(ByteArrayInputStream(bytes))
}
private fun findHref(document: org.w3c.dom.Document, propertyName: String): String? {
val elements = document.getElementsByTagNameNS("*", propertyName)
for (index in 0 until elements.length) {
val href = (elements.item(index) as? Element)?.getElementsByTagNameNS("*", "href")?.item(0)?.textContent
if (!href.isNullOrBlank()) return href.trim()
}
return null
}
private fun textContent(element: Element, propertyName: String): String? {
val nodes = element.getElementsByTagNameNS("*", propertyName)
return if (nodes.length == 0) null else nodes.item(0)?.textContent?.trim()
}
private fun childText(element: Element, childName: String): String? {
val children = element.childNodes
for (index in 0 until children.length) {
val node = children.item(index)
if (node is Element && node.localName == childName) return node.textContent.trim()
}
return null
}
private fun resolveUrl(base: String, href: String): String = URL(URL(base), href).toString()
private fun basicAuth(account: JSONObject): String {
val raw = "${account.optString("username")}:${account.optString("password")}"
return "Basic " + Base64.encodeToString(raw.toByteArray(StandardCharsets.UTF_8), Base64.NO_WRAP)
}
private fun publicDav(account: JSONObject) = JSONObject()
.put("id", account.optString("id"))
.put("serverUrl", account.optString("serverUrl"))
.put("username", account.optString("username"))
.put("collections", account.optJSONArray("collections") ?: JSONArray())
private fun type(value: String) = if (value == "carddav") "carddav" else "caldav"
private fun findCollection(collections: JSONArray, url: String): JSONObject? {
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
if (url.isBlank() || collection.optString("url") == url) return collection
}
return null
}
private fun encode(value: String) = java.net.URLEncoder.encode(value, "UTF-8")
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")
private fun unescape(value: String) = value.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")
private fun property(name: String, value: String) = if (value.isBlank()) "" else "$name:${escape(value)}\r\n"
private fun utcNow() = java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT)
.apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(java.util.Date())
private fun unfold(data: String) = data.replace("\r\n ", "").replace("\n ", "").replace("\r\n\t", "").replace("\n\t", "")
private fun parseProperties(block: String): Map<String, String> {
val result = LinkedHashMap<String, String>()
for (line in block.lines()) {
val colon = line.indexOf(':')
if (colon <= 0) continue
val name = line.substring(0, colon).substringBefore(';').uppercase(Locale.ROOT)
result.putIfAbsent(name, line.substring(colon + 1).trim())
}
return result
}
private fun parseDate(raw: String): Pair<String, String>? {
if (raw.isBlank()) return null
val rawValue = raw.substringAfter(':', raw)
return try {
when {
rawValue.length == 8 -> "${rawValue.substring(0, 4)}-${rawValue.substring(4, 6)}-${rawValue.substring(6, 8)}" to ""
rawValue.length >= 15 -> {
val digits = rawValue.replace("T", "").replace("Z", "").take(14)
val date = "${digits.substring(0, 4)}-${digits.substring(4, 6)}-${digits.substring(6, 8)}"
val time = "${digits.substring(8, 10)}:${digits.substring(10, 12)}"
date to time
}
else -> null
}
} catch (_: Exception) { null }
}
}
private fun findCollection(collections: JSONArray, url: String): JSONObject? {
for (index in 0 until collections.length()) {
val collection = collections.getJSONObject(index)
if (url.isBlank() || collection.optString("url") == url) return collection
}
return null
}
private fun encode(value: String) = java.net.URLEncoder.encode(value, "UTF-8")
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")
private fun unescape(value: String) = value.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")
private fun property(name: String, value: String) = if (value.isBlank()) "" else "$name:${escape(value)}\r\n"
private fun utcNow() = java.text.SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ROOT)
.apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }.format(java.util.Date())
private fun unfold(data: String) = data.replace("\r\n ", "").replace("\n ", "").replace("\r\n\t", "").replace("\n\t", "")
private fun parseProperties(block: String): Map<String, String> {
val result = LinkedHashMap<String, String>()
for (line in block.lines()) {
val colon = line.indexOf(':')
if (colon <= 0) continue
val name = line.substring(0, colon).substringBefore(';').uppercase(Locale.ROOT)
result.putIfAbsent(name, line.substring(colon + 1).trim())
}
return result
}
private fun parseDate(raw: String): Pair<String, String>? {
if (raw.isBlank()) return null
val rawValue = raw.substringAfter(':', raw)
return try {
when {
rawValue.length == 8 -> "${rawValue.substring(0, 4)}-${rawValue.substring(4, 6)}-${rawValue.substring(6, 8)}" to ""
rawValue.length >= 15 -> {
val digits = rawValue.replace("T", "").replace("Z", "").take(14)
val date = "${digits.substring(0, 4)}-${digits.substring(4, 6)}-${digits.substring(6, 8)}"
val time = "${digits.substring(8, 10)}:${digits.substring(10, 12)}"
date to time
}
else -> null
}
} catch (_: Exception) { null }
}
}
@@ -0,0 +1,7 @@
package studio.daybreak.mail
internal object AndroidDownloadPolicy {
fun isAppOwnedDownload(ownerPackage: String?, relativePath: String?, packageName: String): Boolean =
ownerPackage == packageName &&
relativePath?.trimEnd('/') == "Download"
}
File diff suppressed because it is too large Load Diff
@@ -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,166 @@
package studio.daybreak.mail
import android.content.Context
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import android.util.Base64
import androidx.biometric.BiometricManager
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
internal class PgpBiometricUnlockException(
val errorCode: String,
message: String,
cause: Throwable? = null
) : IllegalStateException(message, cause)
internal object AndroidPgpBiometricUnlock {
private const val ALIAS_PREFIX = "ep-mail-pgp-unlock-"
private const val GCM_TAG_BITS = 128
private const val IV_BYTES = 12
fun requireAvailable(context: Context) {
val authenticators = allowedAuthenticators()
val result = BiometricManager.from(context).canAuthenticate(authenticators)
require(result == BiometricManager.BIOMETRIC_SUCCESS) {
"Set up a strong biometric or device screen lock before enabling biometric key unlock."
}
}
fun encryptCipher(context: Context, fingerprint: String): Cipher {
requireAvailable(context)
try {
return createEncryptCipher(context, fingerprint)
} catch (_: KeyPermanentlyInvalidatedException) {
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
deleteKey(fingerprint)
return createEncryptCipher(context, fingerprint)
}
}
private fun createEncryptCipher(context: Context, fingerprint: String): Cipher {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey(context, fingerprint))
return cipher
}
fun decryptCipher(context: Context, fingerprint: String, ciphertext: String): Cipher {
val payload = try {
Base64.decode(ciphertext, Base64.NO_WRAP)
} catch (_: IllegalArgumentException) {
throw PgpBiometricUnlockException("BIOMETRIC_CORRUPT", "Biometric key unlock data is damaged. Enter the key passphrase and set it up again.")
}
require(payload.size > IV_BYTES) {
"Biometric key unlock data is damaged. Enter the key passphrase and set it up again."
}
val key = try {
secretKey(context, fingerprint, create = false)
} catch (_: KeyPermanentlyInvalidatedException) {
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
} catch (_: Exception) {
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric key unlock is unavailable. Enter the key passphrase and set it up again.")
}
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
try {
cipher.init(
Cipher.DECRYPT_MODE,
key,
GCMParameterSpec(GCM_TAG_BITS, payload.copyOfRange(0, IV_BYTES))
)
} catch (_: KeyPermanentlyInvalidatedException) {
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
}
return cipher
}
fun seal(passphrase: String, cipher: Cipher): String {
require(passphrase.length in 1..4096) { "The key passphrase is empty or too long for biometric unlock." }
val plaintext = passphrase.toByteArray(Charsets.UTF_8)
val encrypted = try {
cipher.doFinal(plaintext)
} finally {
plaintext.fill(0)
}
return Base64.encodeToString(cipher.iv + encrypted, Base64.NO_WRAP)
}
fun open(ciphertext: String, cipher: Cipher): String {
val payload = Base64.decode(ciphertext, Base64.NO_WRAP)
val plaintext = cipher.doFinal(payload.copyOfRange(IV_BYTES, payload.size))
return String(plaintext, Charsets.UTF_8).also { plaintext.fill(0) }
}
fun deleteKey(fingerprint: String) {
val alias = alias(fingerprint)
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
if (keyStore.containsAlias(alias)) keyStore.deleteEntry(alias)
}
fun deleteAllKeys() {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val aliases = keyStore.aliases()
while (aliases.hasMoreElements()) {
val name = aliases.nextElement()
if (name.startsWith(ALIAS_PREFIX)) keyStore.deleteEntry(name)
}
}
private fun secretKey(context: Context, fingerprint: String, create: Boolean = true): SecretKey {
val alias = alias(fingerprint)
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
try {
(keyStore.getKey(alias, null) as? SecretKey)?.let { return it }
} catch (error: KeyPermanentlyInvalidatedException) {
throw error
} catch (error: Exception) {
throw IllegalStateException("Biometric key unlock is unavailable. Enter the key passphrase and set it up again.", error)
}
if (!create) {
throw PgpBiometricUnlockException(
"BIOMETRIC_INVALIDATED",
"Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again."
)
}
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
val spec = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.setRandomizedEncryptionRequired(true)
.setUserAuthenticationRequired(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
spec.setUserAuthenticationParameters(
0,
KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL
)
} else {
spec.setUserAuthenticationValidityDurationSeconds(-1)
spec.setInvalidatedByBiometricEnrollment(true)
}
generator.init(spec.build())
return generator.generateKey()
}
private fun allowedAuthenticators(): Int =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
BiometricManager.Authenticators.BIOMETRIC_STRONG or
BiometricManager.Authenticators.DEVICE_CREDENTIAL
} else {
BiometricManager.Authenticators.BIOMETRIC_STRONG
}
private fun alias(fingerprint: String): String {
require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) {
"The OpenPGP fingerprint is invalid."
}
return ALIAS_PREFIX + fingerprint.uppercase()
}
}
@@ -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,90 @@
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?"
}
fun unverifiedRawMimeWarning(): String =
"Android cannot verify that this raw MIME message is actually encrypted. It may contain readable message content, including inside a deceptive OpenPGP wrapper. " +
"Signing alone does not encrypt a message. Continue only if you independently verified the MIME contents and intend to send them."
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,19 @@
package studio.daybreak.mail
import java.io.ByteArrayOutputStream
import java.io.InputStream
internal object BoundedInputReader {
fun read(input: InputStream, maxBytes: Int): ByteArray {
require(maxBytes > 0) { "A positive byte limit is required." }
val output = ByteArrayOutputStream(minOf(maxBytes, 8192))
val buffer = ByteArray(8192)
while (output.size() < maxBytes) {
val count = input.read(buffer, 0, minOf(buffer.size, maxBytes - output.size()))
if (count < 0) break
if (count == 0) continue
output.write(buffer, 0, count)
}
return output.toByteArray()
}
}
@@ -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."
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,55 +1,55 @@
package studio.daybreak.mail
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.util.concurrent.TimeUnit
class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
override fun doWork(): Result {
return try {
AndroidAccountVault.initialize(applicationContext)
MailIdleService.checkSnoozeReminders(applicationContext)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val newMessages = AndroidMailService.checkForNewMail(account)
if (newMessages > 0) {
MailIdleService.notifyNewMail(applicationContext, account, newMessages)
}
}
Result.success()
} catch (error: Exception) {
android.util.Log.w(TAG, "Periodic mail fallback sync failed", error)
Result.retry()
}
}
companion object {
private const val TAG = "EpMailFallback"
private const val UNIQUE_WORK_NAME = "ep-mail-periodic-sync"
fun schedule(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<MailFallbackWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context.applicationContext).enqueueUniquePeriodicWork(
UNIQUE_WORK_NAME,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
fun cancel(context: Context) {
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(UNIQUE_WORK_NAME)
}
}
}
package studio.daybreak.mail
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.util.concurrent.TimeUnit
class MailFallbackWorker(context: Context, parameters: WorkerParameters) : Worker(context, parameters) {
override fun doWork(): Result {
return try {
AndroidAccountVault.initialize(applicationContext)
MailIdleService.checkSnoozeReminders(applicationContext)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val newMessages = AndroidMailService.checkForNewMail(account)
if (newMessages > 0) {
MailIdleService.notifyNewMail(applicationContext, account, newMessages)
}
}
Result.success()
} catch (error: Exception) {
android.util.Log.w(TAG, "Periodic mail fallback sync failed (${error.javaClass.simpleName})")
Result.retry()
}
}
companion object {
private const val TAG = "EpMailFallback"
private const val UNIQUE_WORK_NAME = "ep-mail-periodic-sync"
fun schedule(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = PeriodicWorkRequestBuilder<MailFallbackWorker>(15, TimeUnit.MINUTES)
.setConstraints(constraints)
.build()
WorkManager.getInstance(context.applicationContext).enqueueUniquePeriodicWork(
UNIQUE_WORK_NAME,
ExistingPeriodicWorkPolicy.KEEP,
request
)
}
fun cancel(context: Context) {
WorkManager.getInstance(context.applicationContext).cancelUniqueWork(UNIQUE_WORK_NAME)
}
}
}
@@ -1,295 +1,313 @@
package studio.daybreak.mail
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import org.json.JSONObject
import javax.mail.Folder
import javax.mail.Store
class MailIdleService : Service() {
private data class Watcher(
val account: JSONObject,
val fingerprint: String,
val stopped: AtomicBoolean = AtomicBoolean(false),
@Volatile var store: Store? = null,
@Volatile var folder: Folder? = null,
@Volatile var thread: Thread? = null
) {
fun stop() {
stopped.set(true)
try { folder?.close(false) } catch (_: Exception) {}
try { store?.close() } catch (_: Exception) {}
thread?.interrupt()
}
}
private val watchers = ConcurrentHashMap<String, Watcher>()
override fun onCreate() {
super.onCreate()
AndroidAccountVault.initialize(applicationContext)
createNotificationChannels()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification())
Thread {
try {
reconcile()
if (watchers.isEmpty()) stopSelf(startId)
} catch (error: Exception) {
android.util.Log.e(TAG, "Could not start mailbox watchers", error)
}
}.start()
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
watchers.values.forEach(Watcher::stop)
watchers.clear()
super.onDestroy()
}
@Synchronized
private fun reconcile() {
val accounts = AndroidAccountVault.accounts()
val desired = LinkedHashMap<String, JSONObject>()
for (index in 0 until accounts.length().coerceAtMost(MAX_WATCHERS)) {
val account = accounts.getJSONObject(index)
desired[account.optString("id")] = account
}
for ((id, watcher) in watchers) {
val account = desired[id]
if (account == null || AndroidMailService.accountFingerprint(account) != watcher.fingerprint) {
watcher.stop()
watchers.remove(id, watcher)
}
}
for ((id, account) in desired) {
if (!watchers.containsKey(id)) startWatcher(id, account)
}
}
private fun startWatcher(id: String, account: JSONObject) {
val watcher = Watcher(account, AndroidMailService.accountFingerprint(account))
watchers[id] = watcher
val thread = Thread({
var failures = 0
while (!watcher.stopped.get()) {
try {
AndroidMailService.watchInbox(
account = account,
onNewMail = { count -> onNewMail(account, count) },
shouldStop = { watcher.stopped.get() },
onConnection = { store, folder ->
watcher.store = store
watcher.folder = folder
}
)
failures = 0
} catch (error: Exception) {
if (!watcher.stopped.get()) android.util.Log.w(TAG, "IMAP watcher disconnected for ${account.optString("email")}", error)
failures += 1
} finally {
watcher.folder = null
watcher.store = null
}
if (!watcher.stopped.get()) {
val delayMs = (15_000L * (1L shl failures.coerceAtMost(5))).coerceAtMost(5 * 60_000L)
try {
Thread.sleep(delayMs)
} catch (_: InterruptedException) {
if (watcher.stopped.get()) break
package studio.daybreak.mail
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import org.json.JSONObject
import javax.mail.Folder
import javax.mail.Store
class MailIdleService : Service() {
private data class Watcher(
val account: JSONObject,
val fingerprint: String,
val stopped: AtomicBoolean = AtomicBoolean(false),
@Volatile var store: Store? = null,
@Volatile var folder: Folder? = null,
@Volatile var thread: Thread? = null
) {
fun stop() {
stopped.set(true)
try { folder?.close(false) } catch (_: Exception) {}
try { store?.close() } catch (_: Exception) {}
thread?.interrupt()
}
}
private val watchers = ConcurrentHashMap<String, Watcher>()
override fun onCreate() {
super.onCreate()
AndroidAccountVault.initialize(applicationContext)
createNotificationChannels()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForeground(FOREGROUND_NOTIFICATION_ID, foregroundNotification())
Thread {
try {
reconcile()
if (watchers.isEmpty()) stopSelf(startId)
} catch (error: Exception) {
android.util.Log.e(TAG, "Could not start mailbox watchers (${error.javaClass.simpleName})")
}
}.start()
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
watchers.values.forEach(Watcher::stop)
watchers.clear()
super.onDestroy()
}
@Synchronized
private fun reconcile() {
val accounts = AndroidAccountVault.accounts()
val desired = LinkedHashMap<String, JSONObject>()
for (index in 0 until accounts.length().coerceAtMost(MAX_WATCHERS)) {
val account = accounts.getJSONObject(index)
desired[account.optString("id")] = account
}
for ((id, watcher) in watchers) {
val account = desired[id]
if (account == null || AndroidMailService.accountFingerprint(account) != watcher.fingerprint) {
watcher.stop()
watchers.remove(id, watcher)
}
}
for ((id, account) in desired) {
if (!watchers.containsKey(id)) startWatcher(id, account)
}
}
private fun startWatcher(id: String, account: JSONObject) {
val watcher = Watcher(account, AndroidMailService.accountFingerprint(account))
watchers[id] = watcher
val thread = Thread({
var failures = 0
while (!watcher.stopped.get()) {
try {
AndroidMailService.watchInbox(
account = account,
onNewMail = { count -> onNewMail(account, count) },
shouldStop = { watcher.stopped.get() },
onConnection = { store, folder ->
watcher.store = store
watcher.folder = folder
}
)
failures = 0
} catch (error: Exception) {
if (!watcher.stopped.get()) {
android.util.Log.w(TAG, "IMAP watcher disconnected (${error.javaClass.simpleName})")
}
}
}
}, "ep-mail-idle-$id")
thread.isDaemon = true
watcher.thread = thread
thread.start()
}
private fun onNewMail(account: JSONObject, count: Int) {
notifyNewMail(this, account, count)
}
private fun foregroundNotification(): Notification = NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(getString(R.string.app_name))
.setContentText("Checking mail in the background")
.setContentIntent(appPendingIntent())
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
private fun appPendingIntent(): PendingIntent {
val intent = packageManager.getLaunchIntentForPackage(packageName)
?: Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
private fun createNotificationChannels() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(NotificationChannel(
SERVICE_CHANNEL_ID,
"Background mail sync",
NotificationManager.IMPORTANCE_LOW
).apply { description = "Keeps mail synchronized in the background." })
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
companion object {
const val ACTION_MAIL_SYNC = "studio.daybreak.mail.MAIL_SYNC_UPDATE"
const val EXTRA_SYNC_UPDATE = "syncUpdate"
private const val TAG = "EpMailIdle"
private const val MAX_WATCHERS = 2
private const val FOREGROUND_NOTIFICATION_ID = 3410
private const val SERVICE_CHANNEL_ID = "mail-sync-service"
private const val MAIL_CHANNEL_ID = "mail-new-message"
fun start(context: Context) {
AndroidAccountVault.initialize(context)
if (AndroidAccountVault.accounts().length() == 0) return
MailFallbackWorker.schedule(context)
val intent = Intent(context, MailIdleService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
else context.startService(intent)
}
fun stop(context: Context) {
context.stopService(Intent(context, MailIdleService::class.java))
MailFallbackWorker.cancel(context)
}
fun checkSnoozeReminders(context: Context) {
AndroidAccountVault.initialize(context)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val reminders = AndroidAccountVault.takeDueSnoozes(
account.optString("id"),
System.currentTimeMillis()
)
for (reminderIndex in 0 until reminders.length()) {
notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
}
}
}
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
if (count <= 0) return
val appContext = context.applicationContext
val email = account.optString("email")
if (account.optBoolean("notificationsEnabled", true)) {
val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
notificationManager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
?: Intent(appContext, MainActivity::class.java)
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
appContext, 0, launchIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val title = if (count == 1) "New mail" else "$count new messages"
failures += 1
} finally {
watcher.folder = null
watcher.store = null
}
if (!watcher.stopped.get()) {
val delayMs = (15_000L * (1L shl failures.coerceAtMost(5))).coerceAtMost(5 * 60_000L)
try {
Thread.sleep(delayMs)
} catch (_: InterruptedException) {
if (watcher.stopped.get()) break
}
}
}
}, "ep-mail-idle-$id")
thread.isDaemon = true
watcher.thread = thread
thread.start()
}
private fun onNewMail(account: JSONObject, count: Int) {
notifyNewMail(this, account, count)
}
private fun foregroundNotification(): Notification = NotificationCompat.Builder(this, SERVICE_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(getString(R.string.app_name))
.setContentText("Checking mail in the background")
.setContentIntent(appPendingIntent())
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.build()
private fun appPendingIntent(): PendingIntent {
val intent = packageManager.getLaunchIntentForPackage(packageName)
?: Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}
private fun createNotificationChannels() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.createNotificationChannel(NotificationChannel(
SERVICE_CHANNEL_ID,
"Background mail sync",
NotificationManager.IMPORTANCE_LOW
).apply { description = "Keeps mail synchronized in the background." })
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
companion object {
const val ACTION_MAIL_SYNC = "studio.daybreak.mail.MAIL_SYNC_UPDATE"
const val EXTRA_SYNC_UPDATE = "syncUpdate"
private const val TAG = "EpMailIdle"
private const val MAX_WATCHERS = 2
private const val FOREGROUND_NOTIFICATION_ID = 3410
private const val SERVICE_CHANNEL_ID = "mail-sync-service"
private const val MAIL_CHANNEL_ID = "mail-new-message"
fun start(context: Context) {
AndroidAccountVault.initialize(context)
if (AndroidAccountVault.accounts().length() == 0) return
MailFallbackWorker.schedule(context)
val intent = Intent(context, MailIdleService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(intent)
else context.startService(intent)
}
fun stop(context: Context) {
context.stopService(Intent(context, MailIdleService::class.java))
MailFallbackWorker.cancel(context)
}
fun checkSnoozeReminders(context: Context) {
AndroidAccountVault.initialize(context)
val accounts = AndroidAccountVault.accounts()
for (index in 0 until accounts.length()) {
val account = accounts.getJSONObject(index)
val reminders = AndroidAccountVault.takeDueSnoozes(
account.optString("id"),
System.currentTimeMillis()
)
for (reminderIndex in 0 until reminders.length()) {
notifySnoozeReminder(context, account, reminders.getJSONObject(reminderIndex))
}
}
}
fun notifyNewMail(context: Context, account: JSONObject, count: Int) {
if (count <= 0) return
val appContext = context.applicationContext
val email = account.optString("email")
if (account.optBoolean("notificationsEnabled", true)) {
val notificationManager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
notificationManager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
notificationManager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"New mail",
NotificationManager.IMPORTANCE_DEFAULT
).apply { description = "Notifies you when new mail arrives." })
}
val launchIntent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
?: Intent(appContext, MainActivity::class.java)
launchIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(
appContext, 0, launchIntent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false)
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle(title)
.setContentText(email)
.setContentTitle("New mail")
.setContentText(NotificationPrivacyPolicy.newMailText(showDetails, email, count))
.setAutoCancel(true)
.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)
.build()
try {
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Notification permission is unavailable", error)
}
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("newCount", count)
.put("foldersChanged", org.json.JSONArray().put("Inbox"))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
}
fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
val appContext = context.applicationContext
val email = account.optString("email")
if (account.optBoolean("notificationsEnabled", true)) {
val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"Mail reminders",
NotificationManager.IMPORTANCE_DEFAULT
))
}
.build()
try {
NotificationManagerCompat.from(appContext).notify(email.hashCode(), notification)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Notification permission is unavailable (${error.javaClass.simpleName})")
}
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("newCount", count)
.put("foldersChanged", org.json.JSONArray().put("Inbox"))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
}
fun notifySnoozeReminder(context: Context, account: JSONObject, reminder: JSONObject) {
val appContext = context.applicationContext
val email = account.optString("email")
if (account.optBoolean("notificationsEnabled", true)) {
val manager = appContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
manager.getNotificationChannel(MAIL_CHANNEL_ID) == null) {
manager.createNotificationChannel(NotificationChannel(
MAIL_CHANNEL_ID,
"Mail reminders",
NotificationManager.IMPORTANCE_DEFAULT
))
}
val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false)
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setContentTitle("Mail reminder")
.setContentText(reminder.optString("subject").ifBlank { "A snoozed message is due" })
.setContentText(NotificationPrivacyPolicy.reminderText(showDetails, reminder.optString("subject")))
.setAutoCancel(true)
.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))
.build()
try {
NotificationManagerCompat.from(appContext).notify(
(email + reminder.optLong("uid")).hashCode(),
notification
)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Reminder notification permission is unavailable", error)
}
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("snoozeReminder", true)
.put("foldersChanged", org.json.JSONArray()
.put("Snoozed")
.put(reminder.optString("folder", "Inbox")))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
}
private fun appPendingIntentFor(context: Context): PendingIntent {
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
?: Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(
context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
}
}
.build()
try {
NotificationManagerCompat.from(appContext).notify(
(email + reminder.optLong("uid")).hashCode(),
notification
)
} catch (error: SecurityException) {
android.util.Log.w(TAG, "Reminder notification permission is unavailable (${error.javaClass.simpleName})")
}
}
val update = JSONObject()
.put("accountId", account.optString("id"))
.put("snoozeReminder", true)
.put("foldersChanged", org.json.JSONArray()
.put("Snoozed")
.put(reminder.optString("folder", "Inbox")))
appContext.sendBroadcast(Intent(ACTION_MAIL_SYNC)
.setPackage(appContext.packageName)
.putExtra(EXTRA_SYNC_UPDATE, update.toString()))
}
private fun appPendingIntentFor(context: Context): PendingIntent {
val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)
?: Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
return PendingIntent.getActivity(
context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
}
}
}
@@ -1,19 +1,439 @@
package studio.daybreak.mail;
import android.Manifest;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebStorage;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.activity.OnBackPressedCallback;
import com.getcapacitor.BridgeActivity;
import javax.crypto.Cipher;
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 pgpAuthInProgress;
private boolean pgpAuthPaused;
private long pgpAuthPauseAt;
private boolean activityResumed;
private boolean vaultRecoveryRequired;
private final Handler appLockHandler = new Handler(Looper.getMainLooper());
private final Runnable delayedAppLock = () -> {
if (!activityResumed && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
};
private final Runnable lockAfterPgpAuth = () -> {
if (!activityResumed && pgpAuthPaused && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(EpMailPlugin.class);
super.onCreate(savedInstanceState);
hardenWebView();
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (appLocked || vaultRecoveryRequired || getBridge() == null || getBridge().getWebView() == null) {
dispatchDefaultBack();
return;
}
getBridge().getWebView().evaluateJavascript(
"(function(){if(document.body.classList.contains('reader-open') && " +
"!document.querySelector('#modal-root .modal-overlay')){" +
"const back=document.querySelector('#reader-back');if(back){back.click();return true;}}" +
"return false;})()",
result -> {
if (!"true".equals(result)) dispatchDefaultBack();
}
);
}
private void dispatchDefaultBack() {
setEnabled(false);
try {
getOnBackPressedDispatcher().onBackPressed();
} finally {
setEnabled(true);
}
}
});
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) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
}
}
@Override
public void onResume() {
super.onResume();
if (vaultRecoveryRequired) return;
activityResumed = true;
appLockHandler.removeCallbacks(delayedAppLock);
appLockHandler.removeCallbacks(lockAfterPgpAuth);
pgpAuthPaused = false;
if (!appLocked) getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (isAppLockEnabled() && appLocked) {
lockWebView();
configureUnlockButton();
}
}
@Override
public void onPause() {
activityResumed = false;
if (!vaultRecoveryRequired && isAppLockEnabled() && !pgpAuthInProgress) {
int delaySeconds = appLockDelaySeconds();
if (delaySeconds == 0) {
lockWebView();
} else {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
appLockHandler.postDelayed(delayedAppLock, delaySeconds * 1000L);
}
} else if (!vaultRecoveryRequired && isAppLockEnabled() && pgpAuthInProgress) {
pgpAuthPaused = true;
pgpAuthPauseAt = SystemClock.elapsedRealtime();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
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.");
}
@Override
public void onDestroy() {
appLockHandler.removeCallbacks(delayedAppLock);
appLockHandler.removeCallbacks(lockAfterPgpAuth);
super.onDestroy();
}
public void onAppLockSettingChanged(boolean enabled) {
runOnUiThread(() -> {
appLockHandler.removeCallbacks(delayedAppLock);
appLockHandler.removeCallbacks(lockAfterPgpAuth);
pgpAuthPaused = false;
if (!enabled) {
awaitingUnlockResult = false;
unlockWebView(false);
} else if (activityResumed) {
appLocked = false;
} else {
lockWebView();
}
});
}
private int appLockDelaySeconds() {
try {
int delay = AndroidAccountVault.INSTANCE.appLockDelaySeconds();
AndroidAppLockPolicy.INSTANCE.requireValidDelay(delay);
return delay;
} catch (Exception ignored) {
return 0;
}
}
public void authenticatePgpCipher(Cipher cipher, BiometricPrompt.AuthenticationCallback callback) {
int authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
authenticators |= BiometricManager.Authenticators.DEVICE_CREDENTIAL;
}
BiometricPrompt.PromptInfo.Builder prompt = new BiometricPrompt.PromptInfo.Builder()
.setTitle("Unlock OpenPGP key")
.setSubtitle("Confirm to release this key's passphrase")
.setAllowedAuthenticators(authenticators)
.setConfirmationRequired(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
prompt.setNegativeButtonText("Cancel");
}
BiometricPrompt biometricPrompt = new BiometricPrompt(
this,
ContextCompat.getMainExecutor(this),
new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
finishPgpAuthentication();
callback.onAuthenticationSucceeded(result);
}
@Override
public void onAuthenticationFailed() {
callback.onAuthenticationFailed();
}
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
finishPgpAuthentication();
callback.onAuthenticationError(errorCode, errString);
}
}
);
pgpAuthInProgress = true;
try {
biometricPrompt.authenticate(
prompt.build(),
new BiometricPrompt.CryptoObject(cipher)
);
} catch (RuntimeException error) {
pgpAuthInProgress = false;
throw error;
}
}
private void finishPgpAuthentication() {
pgpAuthInProgress = false;
if (!pgpAuthPaused) return;
long elapsed = SystemClock.elapsedRealtime() - pgpAuthPauseAt;
long remaining = Math.max(1000L, appLockDelaySeconds() * 1000L - elapsed);
appLockHandler.postDelayed(lockAfterPgpAuth, remaining);
}
public void clearLocalWebData() {
if (getBridge() == null || getBridge().getWebView() == null) return;
getBridge().getWebView().clearCache(true);
WebStorage.getInstance().deleteAllData();
}
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,12 @@
package studio.daybreak.mail
internal object PgpMessageUid {
fun requireValid(value: Any?): Long {
require(value is Number) { "That message could not be identified." }
val number = value.toDouble()
require(number.isFinite() && number >= 1 && number <= 4294967295.0 && number == kotlin.math.floor(number)) {
"That message could not be identified."
}
return number.toLong()
}
}
@@ -1,34 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,3 @@
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="@drawable/ep_splash_icon"
android:inset="22dp" />
@@ -0,0 +1,26 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="64"
android:viewportHeight="64">
<path
android:fillColor="@android:color/transparent"
android:strokeColor="#eee9de"
android:strokeWidth="3"
android:pathData="M32,5a27,27 0,1 0,0 54a27,27 0,1 0,0 -54" />
<path
android:strokeColor="#eee9de"
android:strokeWidth="4"
android:pathData="M32,4v56" />
<group android:rotation="22" android:pivotX="32" android:pivotY="18">
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
android:strokeWidth="3" android:pathData="M20,18a12,5 0,1 0,24 0a12,5 0,1 0,-24 0" />
</group>
<group android:rotation="-22" android:pivotX="32" android:pivotY="46">
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
android:strokeWidth="3" android:pathData="M20,46a12,5 0,1 0,24 0a12,5 0,1 0,-24 0" />
</group>
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
android:strokeAlpha="0.75" android:strokeWidth="2"
android:pathData="M24,32a8,8 0,1 0,16 0a8,8 0,1 0,-16 0" />
</vector>
@@ -1,170 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
@@ -1,12 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ep_launcher_foreground"/>
</adaptive-icon>
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ep_launcher_foreground"/>
</adaptive-icon>
@@ -0,0 +1,9 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/ic_launcher_background" />
<item
android:drawable="@drawable/ep_splash_icon"
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</layer-list>
@@ -0,0 +1,13 @@
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/ic_launcher_background" />
</shape>
</item>
<item
android:drawable="@drawable/ep_splash_icon"
android:left="5dp"
android:top="5dp"
android:right="5dp"
android:bottom="5dp" />
</layer-list>
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#FFFFFF</color>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#0a0c0b</color>
</resources>
+7 -7
View File
@@ -1,7 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">ep-mail</string>
<string name="title_activity_main">ep-mail</string>
<string name="package_name">studio.daybreak.mail</string>
<string name="custom_url_scheme">studio.daybreak.mail</string>
</resources>
<?xml version='1.0' encoding='utf-8'?>
<resources>
<string name="app_name">ep-mail</string>
<string name="title_activity_main">ep-mail</string>
<string name="package_name">studio.daybreak.mail</string>
<string name="custom_url_scheme">studio.daybreak.mail</string>
</resources>
+23 -21
View File
@@ -1,22 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="android:background">@drawable/splash</item>
</style>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:background">@null</item>
</style>
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
<item name="windowSplashScreenBackground">#0a0c0b</item>
<item name="windowSplashScreenAnimatedIcon">@drawable/ep_splash_icon</item>
<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>
</style>
</resources>
@@ -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>
@@ -1,18 +1,18 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
@@ -0,0 +1,14 @@
package studio.daybreak.mail
import org.junit.Assert.assertThrows
import org.junit.Test
class AndroidAppLockPolicyTest {
@Test
fun acceptsOnlySupportedAppLockDelays() {
AndroidAppLockPolicy.allowedDelaySeconds.forEach(AndroidAppLockPolicy::requireValidDelay)
assertThrows(IllegalArgumentException::class.java) {
AndroidAppLockPolicy.requireValidDelay(45)
}
}
}
@@ -0,0 +1,15 @@
package studio.daybreak.mail
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class AndroidDownloadPolicyTest {
@Test
fun onlySelectsDownloadsCreatedByThisApplication() {
assertTrue(AndroidDownloadPolicy.isAppOwnedDownload("studio.daybreak.mail", "Download/", "studio.daybreak.mail"))
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload("other.app", "Download/", "studio.daybreak.mail"))
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload(null, "Download/", "studio.daybreak.mail"))
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload("studio.daybreak.mail", "Documents/", "studio.daybreak.mail"))
}
}
@@ -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,52 @@
package studio.daybreak.mail
import java.io.ByteArrayInputStream
import java.io.File
import java.util.Properties
import javax.mail.Session
import javax.mail.internet.MimeMessage
import org.junit.Assert.assertThrows
import org.junit.Assume.assumeTrue
import org.junit.Test
class AndroidPgpMimeValidationTest {
private fun message(contentType: String, parts: String): MimeMessage {
val source = "MIME-Version: 1.0\r\nContent-Type: $contentType; boundary=\"test\"\r\n\r\n$parts"
return MimeMessage(Session.getInstance(Properties()), ByteArrayInputStream(source.toByteArray(Charsets.UTF_8)))
}
private fun encrypted(version: String = "Version: 1", partType: String = "application/octet-stream", armor: String = "-----BEGIN PGP MESSAGE-----\r\nabc\r\n-----END PGP MESSAGE-----"): MimeMessage =
message("multipart/encrypted; protocol=\"application/pgp-encrypted\"",
"--test\r\nContent-Type: application/pgp-encrypted\r\n\r\n$version\r\n" +
"--test\r\nContent-Type: $partType\r\n\r\n$armor\r\n--test--\r\n")
private fun signed(armor: String = "-----BEGIN PGP SIGNATURE-----\r\nabc\r\n-----END PGP SIGNATURE-----"): MimeMessage =
message("multipart/signed; protocol=\"application/pgp-signature\"",
"--test\r\nContent-Type: text/plain\r\n\r\nhello\r\n" +
"--test\r\nContent-Type: application/pgp-signature\r\n\r\n$armor\r\n--test--\r\n")
@Test
fun acceptsValidEncryptedAndSignedMime() {
AndroidMailService.validateOpenPgpMime(encrypted())
AndroidMailService.validateOpenPgpMime(signed())
}
@Test
fun rejectsMalformedEncryptedAndSignedMime() {
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(version = "Version: 2")) }
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(partType = "text/plain")) }
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(armor = "missing armor")) }
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(signed(armor = "missing signature")) }
}
@Test
fun acceptsMimeGeneratedByAndroidOpenPgpBuilder() {
val directory = System.getenv("EP_MAIL_PGP_MIME_FIXTURE_DIR")
assumeTrue("Set EP_MAIL_PGP_MIME_FIXTURE_DIR to run the JavaScript-to-JavaMail integration test.", !directory.isNullOrBlank())
for (name in listOf("encrypted", "signed", "encrypted-signed")) {
val file = File(directory, "$name.eml")
val parsed = file.inputStream().use { MimeMessage(Session.getInstance(Properties()), it) }
AndroidMailService.validateOpenPgpMime(parsed)
}
}
}
@@ -0,0 +1,92 @@
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:"))
}
@Test
fun rawMimeRequiresNativeConfirmationBecauseEncryptionCannotBeVerified() {
val warning = AndroidPgpPolicy.unverifiedRawMimeWarning()
assertTrue(warning.contains("cannot verify"))
assertTrue(warning.contains("deceptive OpenPGP wrapper"))
assertTrue(warning.contains("Signing alone does not encrypt"))
}
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,23 @@
package studio.daybreak.mail
import java.io.ByteArrayInputStream
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
class BoundedInputReaderTest {
@Test
fun readsOnlyUpToTheRequestedLimit() {
val input = ByteArrayInputStream(byteArrayOf(1, 2, 3, 4, 5))
assertArrayEquals(byteArrayOf(1, 2, 3), BoundedInputReader.read(input, 3))
assertEquals(2, input.available())
}
@Test
fun readsShortStreamsToEnd() {
assertArrayEquals(
byteArrayOf(1, 2),
BoundedInputReader.read(ByteArrayInputStream(byteArrayOf(1, 2)), 5)
)
}
}
@@ -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, " "))
}
}
@@ -0,0 +1,22 @@
package studio.daybreak.mail
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
class PgpMessageUidTest {
@Test
fun acceptsJsonIntegerAndLongUids() {
assertEquals(42L, PgpMessageUid.requireValid(42))
assertEquals(42L, PgpMessageUid.requireValid(42L))
assertEquals(4294967295L, PgpMessageUid.requireValid(4294967295L))
assertEquals(42L, PgpMessageUid.requireValid(42.0))
}
@Test
fun rejectsMissingAndInvalidUids() {
for (value in listOf(null, "42", 0, -1, 1.5, Double.NaN, Double.POSITIVE_INFINITY, 4294967296L)) {
assertThrows(IllegalArgumentException::class.java) { PgpMessageUid.requireValid(value) }
}
}
}
+35 -29
View File
@@ -1,30 +1,36 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:9.4.0'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
// Capacitor-generated modules declare their own AGP version.
buildscript {
configurations.classpath {
resolutionStrategy.force 'com.android.tools.build:gradle:9.4.0'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:8.13.0'
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
classpath 'com.google.gms:google-services:4.4.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
+25 -22
View File
@@ -1,22 +1,25 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Capacitor's generated modules and the current Kotlin plugin still use the legacy AGP APIs.
android.builtInKotlin=false
android.newDsl=false
+8 -7
View File
@@ -1,7 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#Mon Nov 09 22:05:03 EET 2026
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+251 -251
View File
@@ -1,251 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+94 -94
View File
@@ -1,94 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
+4 -4
View File
@@ -1,5 +1,5 @@
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
include ':app'
include ':capacitor-cordova-android-plugins'
project(':capacitor-cordova-android-plugins').projectDir = new File('./capacitor-cordova-android-plugins/')
apply from: 'capacitor.settings.gradle'
+15 -15
View File
@@ -1,16 +1,16 @@
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
ext {
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
androidxActivityVersion = '1.11.0'
androidxAppCompatVersion = '1.7.1'
androidxCoordinatorLayoutVersion = '1.3.0'
androidxCoreVersion = '1.17.0'
androidxFragmentVersion = '1.8.9'
coreSplashScreenVersion = '1.2.0'
androidxWebkitVersion = '1.14.0'
junitVersion = '4.13.2'
androidxJunitVersion = '1.3.0'
androidxEspressoCoreVersion = '3.7.0'
cordovaAndroidVersion = '14.0.1'
}
+49 -29
View File
@@ -2,40 +2,57 @@
if('serviceWorker'in navigator)window.addEventListener('load',()=>navigator.serviceWorker.register('./service-worker.js').catch(()=>{}));
const state = window.epMailState;
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]))}
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
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)$('#reader-pane').innerHTML=emptyReader()}
let readerListPosition = null;
function rememberReaderListPosition() {
if (window.daybreakMail?.platform !== 'android' || document.body.classList.contains('reader-open')) return;
const list = $('#message-list');
readerListPosition = { folder: state.activeFolder, scrollTop: list.scrollTop };
}
function returnToMessageList() {
state.activeMessage = null;
document.body.classList.remove('reader-open');
$('#reader-pane').innerHTML = emptyReader();
renderList();
if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop;
readerListPosition = null;
}
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()}}
function openMessage(id){
state.activeMessage=id;
const m=state.messages.find(x=>x.id===id);
if(!m)return;
m.unread=false;
renderList();
let safeHtml={html:'',remoteImageCount:0};
if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)}
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 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>`;
$('#load-remote-images')?.addEventListener('click',()=>{
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
image.removeAttribute('data-remote-src');
if(url)image.src=url;
});
$('.remote-image-notice')?.remove();
});
$('#reader-archive').onclick=()=>{m.archived=true;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-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
$('#reply').onclick=()=>showCompose(m);
$('#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 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;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()}
if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
rememberReaderListPosition();
document.body.classList.add('reader-open');
m.unread=false;
renderList();
let safeHtml={html:'',remoteImageCount:0};
if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)}
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 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"><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=returnToMessageList;
$('#load-remote-images')?.addEventListener('click',()=>{
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
image.removeAttribute('data-remote-src');
if(url)image.src=url;
});
$('.remote-image-notice')?.remove();
});
$('#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;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)};
$('#reply').onclick=()=>showCompose(m);
$('#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 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;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){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();}
$$('.folder').forEach(b=>b.onclick=()=>{state.activeFolder=b.dataset.folder;$$('.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=()=>{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);
$$('.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);
window.epMailShell = Object.freeze({
state,
@@ -49,6 +66,9 @@ window.epMailShell = Object.freeze({
get renderList() { return renderList; },
get openMessage() { return openMessage; },
get showCompose() { return showCompose; },
getReaderListPosition() {
return readerListPosition?.folder === state.activeFolder ? readerListPosition.scrollTop : 0;
},
emptyReader,
wrapRenderList(decorator) { renderList = decorator(renderList); },
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
+147 -147
View File
@@ -5,159 +5,159 @@ const selectAttachmentUi = attachmentMailUi.select;
const selectAllAttachmentUi = attachmentMailUi.selectAll;
const toastAttachmentUi = attachmentMailUi.toast;
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
let attachmentItems = [];
function attachmentKind(filename) {
const ext = String(filename).toLowerCase().split('.').pop();
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
return 'Other';
}
function attachmentSize(size) {
if (!size) return '';
if (typeof size === 'string') return size;
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
}
async function previewAttachment(target, details) {
if (!details.uid || !window.daybreakMail?.previewAttachment) {
target.textContent = 'Previews are available for connected mailbox messages.';
return;
}
target.textContent = 'Loading preview…';
try {
const result = await window.daybreakMail.previewAttachment(details);
target.replaceChildren();
if (result.kind === 'image') {
const image = document.createElement('img');
image.className = 'attachment-preview-image';
image.alt = details.filename;
image.src = result.dataUrl;
target.append(image);
} else if (result.kind === 'text') {
const pre = document.createElement('pre');
pre.className = 'attachment-preview-text';
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
target.append(pre);
} else {
target.textContent = result.reason || 'No preview is available for this file type.';
}
} catch (error) {
target.textContent = error.message || 'Could not load the preview.';
}
}
function downloadAttachment(details) {
if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('Attachment download is available for connected mailbox messages'); return; }
window.daybreakMail.saveAttachment(details)
.then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
.catch(error => toastAttachmentUi(error.message || 'Could not save attachment'));
}
// Add a Preview button to each attachment in the reader.
let attachmentItems = [];
function attachmentKind(filename) {
const ext = String(filename).toLowerCase().split('.').pop();
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
return 'Other';
}
function attachmentSize(size) {
if (!size) return '';
if (typeof size === 'string') return size;
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
}
async function previewAttachment(target, details) {
if (!details.uid || !window.daybreakMail?.previewAttachment) {
target.textContent = 'Previews are available for connected mailbox messages.';
return;
}
target.textContent = 'Loading preview…';
try {
const result = await window.daybreakMail.previewAttachment(details);
target.replaceChildren();
if (result.kind === 'image') {
const image = document.createElement('img');
image.className = 'attachment-preview-image';
image.alt = details.filename;
image.src = result.dataUrl;
target.append(image);
} else if (result.kind === 'text') {
const pre = document.createElement('pre');
pre.className = 'attachment-preview-text';
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
target.append(pre);
} else {
target.textContent = result.reason || 'No preview is available for this file type.';
}
} catch (error) {
target.textContent = error.message || 'Could not load the preview.';
}
}
function downloadAttachment(details) {
if (!details.uid || !window.daybreakMail?.saveAttachment) { toastAttachmentUi('Attachment download is available for connected mailbox messages'); return; }
window.daybreakMail.saveAttachment(details)
.then(result => { if (result.saved) toastAttachmentUi('Attachment saved'); })
.catch(error => toastAttachmentUi(error.message || 'Could not save attachment'));
}
// Add a Preview button to each attachment in the reader.
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
baseOpenMessage(id);
const message = attachmentMailUi.state.messages.find(item => item.id === id);
if (!message?.uid) return;
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
const download = row.querySelector('.download');
if (!download || row.querySelector('.preview-attachment')) return;
const button = document.createElement('button');
button.className = 'preview-attachment icon-button';
button.title = 'Preview';
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
button.textContent = '👁';
button.addEventListener('click', event => {
event.stopPropagation();
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
if (panel) { panel.remove(); return; }
panel = document.createElement('div');
panel.className = 'attachment-preview';
row.after(panel);
if (!message?.uid || message.pgpDecrypted) return;
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
const download = row.querySelector('.download');
if (!download || row.querySelector('.preview-attachment')) return;
const button = document.createElement('button');
button.className = 'preview-attachment icon-button';
button.title = 'Preview';
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
button.textContent = '👁';
button.addEventListener('click', event => {
event.stopPropagation();
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
if (panel) { panel.remove(); return; }
panel = document.createElement('div');
panel.className = 'attachment-preview';
row.after(panel);
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() {
const items = [];
for (const folder of attachmentFolders) {
let offset = 0;
for (let page = 0; page < 5; page += 1) {
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
for (const message of result.messages || []) {
for (const file of message.attachments || []) {
items.push({
uid: message.uid, folder, filename: file.filename, size: file.size,
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
kind: attachmentKind(file.filename)
});
}
}
offset += (result.messages || []).length;
if (!result.messages?.length || offset >= (result.total || 0)) break;
}
}
return items.sort((a, b) => b.timestamp - a.timestamp);
}
async function openAttachmentsView() {
async function collectAttachments() {
const items = [];
for (const folder of attachmentFolders) {
let offset = 0;
for (let page = 0; page < 5; page += 1) {
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
for (const message of result.messages || []) {
for (const file of message.attachments || []) {
items.push({
uid: message.uid, folder, filename: file.filename, size: file.size,
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
kind: attachmentKind(file.filename)
});
}
}
offset += (result.messages || []).length;
if (!result.messages?.length || offset >= (result.total || 0)) break;
}
}
return items.sort((a, b) => b.timestamp - a.timestamp);
}
async function openAttachmentsView() {
if (!attachmentMailUi.connectedAccount || !window.daybreakMail) { attachmentMailUi.openMailAccount(); return; }
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>`;
const close = () => { root.innerHTML = ''; };
root.querySelector('.modal-close').onclick = close;
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const list = selectAttachmentUi('#attachment-list');
const render = () => {
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
const type = selectAttachmentUi('#attachment-type').value;
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
list.replaceChildren();
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
shown.forEach(item => {
const row = document.createElement('div');
row.className = 'attachment-row';
const info = document.createElement('div');
info.className = 'attachment-row-info';
const name = document.createElement('strong');
name.textContent = item.filename;
const meta = document.createElement('small');
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
info.append(name, meta);
const preview = document.createElement('button');
preview.className = 'discard';
preview.textContent = 'Preview';
const save = document.createElement('button');
save.className = 'discard';
save.textContent = 'Download';
const panel = document.createElement('div');
panel.className = 'attachment-preview';
panel.hidden = true;
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
preview.onclick = () => {
panel.hidden = !panel.hidden;
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
};
save.onclick = () => downloadAttachment(details);
row.append(info, preview, save, panel);
list.append(row);
});
};
selectAttachmentUi('#attachment-search').oninput = render;
selectAttachmentUi('#attachment-type').onchange = render;
try {
attachmentItems = await collectAttachments();
if (selectAttachmentUi('#attachment-list')) render();
} catch (error) {
if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#attachment-list').textContent = error.message || 'Could not load attachments.';
}
}
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>`;
const close = () => { root.innerHTML = ''; };
root.querySelector('.modal-close').onclick = close;
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const list = selectAttachmentUi('#attachment-list');
const render = () => {
const text = selectAttachmentUi('#attachment-search').value.trim().toLowerCase();
const type = selectAttachmentUi('#attachment-type').value;
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
list.replaceChildren();
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
shown.forEach(item => {
const row = document.createElement('div');
row.className = 'attachment-row';
const info = document.createElement('div');
info.className = 'attachment-row-info';
const name = document.createElement('strong');
name.textContent = item.filename;
const meta = document.createElement('small');
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
info.append(name, meta);
const preview = document.createElement('button');
preview.className = 'discard';
preview.textContent = 'Preview';
const save = document.createElement('button');
save.className = 'discard';
save.textContent = 'Download';
const panel = document.createElement('div');
panel.className = 'attachment-preview';
panel.hidden = true;
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
preview.onclick = () => {
panel.hidden = !panel.hidden;
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
};
save.onclick = () => downloadAttachment(details);
row.append(info, preview, save, panel);
list.append(row);
});
};
selectAttachmentUi('#attachment-search').oninput = render;
selectAttachmentUi('#attachment-type').onchange = render;
try {
attachmentItems = await collectAttachments();
if (selectAttachmentUi('#attachment-list')) render();
} catch (error) {
if (selectAttachmentUi('#attachment-list')) selectAttachmentUi('#attachment-list').textContent = error.message || 'Could not load attachments.';
}
}
document.addEventListener('DOMContentLoaded', () => {
selectAttachmentUi('#attachments-nav')?.addEventListener('click', openAttachmentsView);
});
+30 -30
View File
@@ -1,30 +1,30 @@
.brand-mark,
body.wasteland .brand-mark,
body.ep-wasteland .brand-mark,
body.ep-daylight .brand-mark {
background: transparent !important;
box-shadow: none !important;
border-radius: 0;
}
.brand-mark img {
display: block;
width: 35px;
height: 35px;
object-fit: contain;
}
.settings-select {
flex: 1;
border: 0;
padding: 5px 0;
background: transparent;
color: var(--text);
font: inherit;
text-align: right;
}
body.ep-wasteland .settings-select,
body.ep-daylight .settings-select {
color-scheme: inherit;
}
.brand-mark,
body.wasteland .brand-mark,
body.ep-wasteland .brand-mark,
body.ep-daylight .brand-mark {
background: transparent !important;
box-shadow: none !important;
border-radius: 0;
}
.brand-mark img {
display: block;
width: 35px;
height: 35px;
object-fit: contain;
}
.settings-select {
flex: 1;
border: 0;
padding: 5px 0;
background: transparent;
color: var(--text);
font: inherit;
text-align: right;
}
body.ep-wasteland .settings-select,
body.ep-daylight .settings-select {
color-scheme: inherit;
}
+8 -8
View File
@@ -1,8 +1,8 @@
{
"appId": "studio.daybreak.mail",
"appName": "ep-mail",
"webDir": "www",
"server": {
"androidScheme": "https"
}
}
{
"appId": "studio.daybreak.mail",
"appName": "ep-mail",
"webDir": "www",
"server": {
"androidScheme": "https"
}
}
+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*
+36 -36
View File
@@ -3,42 +3,42 @@ const davProductivityUi = window.epMailFeatures.productivity;
const selectDavUi = davProductivityUi.select;
function davTypeName(type){return type==='caldav'?'calendar':'contacts'}
async function syncDav(type, uploadLocal=false){
try{
const localOnly=type==='caldav'?davProductivityUi.events.filter(item=>!item._dav):davProductivityUi.contacts.filter(item=>!item._dav);
const result=await window.daybreakMail.davSync(type);
if(type==='caldav'){
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}`)}}
davProductivityUi.events=[...localOnly,...result.items];
davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar();davProductivityUi.toast(`Synced ${result.items.length} calendar events`);
}else{
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}`)}}
davProductivityUi.contacts=[...localOnly,...result.items];
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
}
}catch(error){davProductivityUi.toast(error.message||`Could not sync ${davTypeName(type)}`)}
}
async function openDavManager(type){
const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
try{
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>${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>`;
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.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){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'){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){davProductivityUi.toast(error.message||`Could not load ${label} servers`)}
}
function showDavConnect(type){
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>`;
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();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();
}
async function syncDav(type, uploadLocal=false){
try{
const localOnly=type==='caldav'?davProductivityUi.events.filter(item=>!item._dav):davProductivityUi.contacts.filter(item=>!item._dav);
const result=await window.daybreakMail.davSync(type);
if(type==='caldav'){
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}`)}}
davProductivityUi.events=[...localOnly,...result.items];
davProductivityUi.productWrite(davProductivityUi.productKeys.events,davProductivityUi.events);davProductivityUi.renderCalendar();davProductivityUi.toast(`Synced ${result.items.length} calendar events`);
}else{
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}`)}}
davProductivityUi.contacts=[...localOnly,...result.items];
davProductivityUi.productWrite(davProductivityUi.productKeys.contacts,davProductivityUi.contacts);davProductivityUi.renderContacts();davProductivityUi.toast(`Synced ${result.items.length} contacts`);
}
}catch(error){davProductivityUi.toast(error.message||`Could not sync ${davTypeName(type)}`)}
}
async function openDavManager(type){
const root=selectDavUi('#modal-root'),label=type==='caldav'?'CalDAV':'CardDAV';
try{
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>${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>`;
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.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){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'){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){davProductivityUi.toast(error.message||`Could not load ${label} servers`)}
}
function showDavConnect(type){
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>`;
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();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();
}
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({
+3 -1
View File
@@ -5,7 +5,7 @@ function registerDavIpcHandlers({
davPublicConfig,
openDavClient,
activeDavConfig,
ICAL,
getICAL,
makeCalendarData,
makeVcard,
randomUUID,
@@ -88,6 +88,7 @@ function registerDavIpcHandlers({
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) {
@@ -116,6 +117,7 @@ function registerDavIpcHandlers({
}
return { items: result, account: davPublicConfig(config) };
}
const { default: ICAL } = await getICAL();
const books = await client.fetchAddressBooks();
const result = [];
for (const book of books) {
+310 -309
View File
@@ -35,49 +35,49 @@ function registerMailIpcHandlers(dependencies) {
mailOutbox,
pgpMail,
PgpError,
simpleParser,
getMailparser,
folderPath,
sendMailNow,
pgpFailure
} = dependencies;
registerIpcHandler('mail:get-account', async () => {
const account = await readAccount();
return account ? publicAccount(account) : null;
});
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.');
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,
@@ -95,189 +95,190 @@ registerIpcHandler('mail:update-account', async (_event, accountId, input) => {
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}`);
}
});
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 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);
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 };
});
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;
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.
}
});
// Encrypted messages keep their attachments inside the encrypted payload.
async function parseForAttachments(source) {
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 { 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 });
@@ -294,34 +295,34 @@ registerIpcHandler('mail:preview-attachment', async (_event, input) => {
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: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.');
@@ -342,83 +343,83 @@ registerIpcHandler('mail:send', async (event, message) => {
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 };
});
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 };
});
}
+17 -10
View File
@@ -1,3 +1,5 @@
const { BUILTIN_SERVER_IDS } = require('../pgp-keyservers.cjs');
function pgpFailure(error) {
return {
failed: true,
@@ -14,6 +16,7 @@ function registerPgpIpcHandlers({
BrowserWindow,
dialog,
fs,
getOpenPGP,
openpgp,
pgpKeys,
pgpCache,
@@ -27,7 +30,7 @@ function registerPgpIpcHandlers({
readAccount,
imapClient,
folderPath,
simpleParser,
getMailparser,
extractMailContent
}) {
async function fetchMessageSource(account, folder, uid) {
@@ -108,6 +111,7 @@ function registerPgpIpcHandlers({
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 });
@@ -143,7 +147,7 @@ function registerPgpIpcHandlers({
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 openpgp.readKey({ armoredKey }).catch(() => {
const key = await (getOpenPGP ? (await getOpenPGP()).readKey({ armoredKey }) : openpgp.readKey({ armoredKey })).catch(() => {
throw new Error('That is not a valid OpenPGP public key.');
});
const fingerprint = key.getFingerprint().toUpperCase();
@@ -205,12 +209,12 @@ function registerPgpIpcHandlers({
});
registerIpcHandler('pgp:key-servers', async () => {
const settings = await pgpKeys.getSettings();
return listServers(settings.customKeyServers, settings.enabledKeyServers);
return listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
});
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 servers = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
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);
@@ -219,7 +223,8 @@ function registerPgpIpcHandlers({
await pgpKeys.setSettings({
cacheMinutes: settings.cacheMinutes,
customKeyServers: settings.customKeyServers,
enabledKeyServers: [...enabled]
enabledKeyServers: [...enabled],
removedBuiltinKeyServers: settings.removedBuiltinKeyServers
});
return { serverId, enabled: input.enabled };
});
@@ -254,30 +259,32 @@ function registerPgpIpcHandlers({
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.');
const removesBuiltin = BUILTIN_SERVER_IDS.includes(id) && !settings.removedBuiltinKeyServers.includes(id);
if (customServers.length === settings.customKeyServers.length && !removesBuiltin) throw new Error('That key server was not found.');
await pgpKeys.setSettings({
cacheMinutes: settings.cacheMinutes,
customKeyServers,
customKeyServers: customServers,
removedBuiltinKeyServers: removesBuiltin ? [...settings.removedBuiltinKeyServers, id] : settings.removedBuiltinKeyServers,
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);
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
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 || ''));
const server = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers).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 openpgp.readKey({ armoredKey });
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))];
+30 -30
View File
@@ -1,30 +1,30 @@
const path = require('node:path');
function normalizeOutgoingAttachments(value) {
if (value === undefined) return [];
if (!Array.isArray(value)) throw new Error('The attachment list is invalid.');
return value.map(file => {
if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') {
throw new Error('An attachment could not be read.');
}
const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/'))
.replace(/[\r\n\0]/g, '')
.slice(0, 255) || 'attachment';
const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase();
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) {
throw new Error(`The content type for ${filename} is invalid.`);
}
const encoded = file.contentBase64;
if (encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {
throw new Error(`The contents of ${filename} are invalid.`);
}
const content = Buffer.from(encoded, 'base64');
return { filename, contentType, contentBase64: encoded, size: content.length, content };
});
}
function serializeOutgoingAttachments(attachments) {
return attachments.map(({ content, ...file }) => file);
}
module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments };
const path = require('node:path');
function normalizeOutgoingAttachments(value) {
if (value === undefined) return [];
if (!Array.isArray(value)) throw new Error('The attachment list is invalid.');
return value.map(file => {
if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') {
throw new Error('An attachment could not be read.');
}
const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/'))
.replace(/[\r\n\0]/g, '')
.slice(0, 255) || 'attachment';
const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase();
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) {
throw new Error(`The content type for ${filename} is invalid.`);
}
const encoded = file.contentBase64;
if (encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {
throw new Error(`The contents of ${filename} are invalid.`);
}
const content = Buffer.from(encoded, 'base64');
return { filename, contentType, contentBase64: encoded, size: content.length, content };
});
}
function serializeOutgoingAttachments(attachments) {
return attachments.map(({ content, ...file }) => file);
}
module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments };
+13 -3
View File
@@ -1,10 +1,17 @@
function createMailConnections({ ImapFlow, createTransport, oauthTokenManager }) {
function createMailConnections({ ImapFlow, createTransport, getImapFlow, getNodemailer, oauthTokenManager }) {
let ImapFlowModule = ImapFlow;
let nodemailerModule = createTransport ? { createTransport } : null;
async function imapClient(account, options = {}) {
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 ImapFlow({
return new ImapFlowModule({
host: account.imapHost,
port: account.imapPort,
secure: Boolean(account.imapSecure),
@@ -20,6 +27,9 @@ function createMailConnections({ ImapFlow, createTransport, oauthTokenManager })
}
async function smtpTransport(account) {
if (!nodemailerModule) {
nodemailerModule = await getNodemailer();
}
const isOAuth = account.authMethod === 'oauth2';
const auth = isOAuth
? {
@@ -30,7 +40,7 @@ function createMailConnections({ ImapFlow, createTransport, oauthTokenManager })
}
: { user: account.email, pass: account.password };
const secure = Boolean(account.smtpSecure);
return createTransport({
return nodemailerModule.createTransport({
host: account.smtpHost,
port: account.smtpPort,
secure,
+387 -316
View File
@@ -1,14 +1,56 @@
require('v8-compile-cache');
const startupTraceEnabled = process.env.EP_MAIL_STARTUP_TRACE === '1';
const startupTraceStartedAt = process.hrtime.bigint();
function traceStartup(message) {
if (!startupTraceEnabled) return;
const elapsed = Number(process.hrtime.bigint() - startupTraceStartedAt) / 1e6;
console.info(`[ep-mail startup +${elapsed.toFixed(1)}ms] ${message}`);
}
traceStartup('main process entered');
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron');
const fsSync = require('node:fs');
const path = require('node:path');
const fs = require('node:fs/promises');
const { ImapFlow } = require('imapflow');
const nodemailer = require('nodemailer');
const { simpleParser } = require('mailparser');
const { randomUUID } = require('node:crypto');
const { createDAVClient } = require('tsdav');
const ICAL = require('ical.js');
const openpgp = require('openpgp');
const fsSync = require('node:fs');
const path = require('node:path');
const fs = require('node:fs/promises');
const { randomUUID } = require('node:crypto');
let tsdavPromise = null;
function getTsdav() {
if (!tsdavPromise) tsdavPromise = import('tsdav');
return tsdavPromise;
}
let icalPromise = null;
function getICAL() {
if (!icalPromise) icalPromise = import('ical.js');
return icalPromise;
}
let openpgpPromise = null;
function getOpenPGP() {
if (!openpgpPromise) openpgpPromise = import('openpgp');
return openpgpPromise;
}
let imapFlowPromise = null;
function getImapFlow() {
if (!imapFlowPromise) imapFlowPromise = import('imapflow');
return imapFlowPromise;
}
let nodemailerPromise = null;
function getNodemailer() {
if (!nodemailerPromise) nodemailerPromise = import('nodemailer');
return nodemailerPromise;
}
let mailparserPromise = null;
function getMailparser() {
if (!mailparserPromise) mailparserPromise = import('mailparser');
return mailparserPromise;
}
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
const {
@@ -43,6 +85,8 @@ const { pgpFailure, registerPgpIpcHandlers } = require('./ipc/pgp.cjs');
const { registerDavIpcHandlers } = require('./ipc/dav.cjs');
const { registerMailIpcHandlers } = require('./ipc/mail.cjs');
traceStartup('all requires complete');
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
@@ -65,11 +109,11 @@ const pgpJsonStore = createSecureJsonStore({
assertSecureStorage,
unavailableMessage: 'Secure key storage is unavailable.'
});
const backgroundSyncIntervalMs = 30 * 1000;
const backgroundRetryIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2;
const backgroundIdleConcurrency = 2;
const snoozeCheckIntervalMs = 30 * 1000;
const backgroundSyncIntervalMs = 30 * 1000;
const backgroundRetryIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2;
const backgroundIdleConcurrency = 2;
const snoozeCheckIntervalMs = 30 * 1000;
const windowsAppUserModelId = 'studio.daybreak.mail';
const applicationHtmlPath = path.join(__dirname, '..', 'index.html');
const ipcMainHandle = ipcMain.handle.bind(ipcMain);
@@ -78,26 +122,34 @@ const backgroundSyncGenerations = new Map();
const backgroundSyncFailures = new Map();
const flagSnapshots = new Map();
const lastBackgroundSyncAt = new Map();
let windowsAppIcon = null;
let windowsAppIcon = null;
let tray = null;
function registerIpcHandler(channel, handler) {
return ipcMainHandle(channel, (event, ...args) => {
assertTrustedIpcSender(event, applicationHtmlPath);
validateIpcArguments(channel, args);
return handler(event, ...args);
return ipcMainHandle(channel, async (event, ...args) => {
const startedAt = startupTraceEnabled ? process.hrtime.bigint() : null;
try {
assertTrustedIpcSender(event, applicationHtmlPath);
validateIpcArguments(channel, args);
return await handler(event, ...args);
} finally {
if (startedAt) {
const elapsed = Number(process.hrtime.bigint() - startedAt) / 1e6;
traceStartup(`${channel} IPC completed in ${elapsed.toFixed(1)}ms`);
}
}
});
}
function updateAccountStore(update) {
const operation = accountStoreQueue.then(async () => {
const store = (await readAccountStore()) || { accounts: [], activeId: null };
const result = await update(store);
if (store.accounts.length) await saveAccountStore(store);
else await fs.rm(credentialsPath(), { force: true });
return result;
});
accountStoreQueue = operation.catch(() => {});
const operation = accountStoreQueue.then(async () => {
const store = (await readAccountStore()) || { accounts: [], activeId: null };
const result = await update(store);
if (store.accounts.length) await saveAccountStore(store);
else await fs.rm(credentialsPath(), { force: true });
return result;
});
accountStoreQueue = operation.catch(() => {});
return operation;
}
@@ -123,13 +175,13 @@ async function authorizeOAuthAccount(account) {
function listOAuthProviders() {
return oauth2Service.listProviders();
}
function sendMailSyncUpdate(update) {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
window.webContents.send('mail:sync-update', update);
}
}
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed() && !window.webContents.isDestroyed()) {
window.webContents.send('mail:sync-update', update);
}
}
}
const { checkSnoozeReminders } = createSnoozeReminderService({
@@ -145,10 +197,10 @@ const { checkSnoozeReminders } = createSnoozeReminderService({
},
sendMailSyncUpdate
});
const { createKeyStore } = require('./pgp-keystore.cjs');
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
const pgpKeys = createKeyStore({
async load() {
try {
@@ -160,58 +212,59 @@ const pgpKeys = createKeyStore({
},
save(data) { return pgpJsonStore.save(data); }
});
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
const pgpKeyServers = createKeyServerService();
const { findSpecialMailbox, findSentMailbox, listCustomFolders, folderPath } = createFolderService({
customFolderPrefix: CUSTOM_FOLDER_PREFIX,
isReservedFolderName
});
async function readDavStore() {
try {
return await davJsonStore.load();
} catch (error) {
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
throw error;
}
}
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
throw error;
}
}
async function saveDavStore(store) {
return davJsonStore.save(store);
}
function davPublicConfig(config) {
return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] };
}
async function openDavClient(config, type) {
return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type });
}
function activeDavConfig(store, type, id = null) {
const key = type === 'caldav' ? 'caldav' : 'carddav';
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
return store[key].find(item => item.id === (id || store[activeKey])) || null;
}
}
function davPublicConfig(config) {
return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] };
}
async function openDavClient(config, type) {
const { createDAVClient } = await getTsdav();
return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type });
}
function activeDavConfig(store, type, id = null) {
const key = type === 'caldav' ? 'caldav' : 'carddav';
const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId';
return store[key].find(item => item.id === (id || store[activeKey])) || null;
}
const { imapClient, smtpTransport } = createMailConnections({
ImapFlow,
createTransport: nodemailer.createTransport,
getImapFlow,
getNodemailer,
oauthTokenManager
});
function assertSecureStorage() {
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
const backend = safeStorage.getSelectedStorageBackend();
if (backend === 'basic_text') {
throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.');
}
}
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
}
function assertSecureStorage() {
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
const backend = safeStorage.getSelectedStorageBackend();
if (backend === 'basic_text') {
throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.');
}
}
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
}
async function readAccountStore() {
return accountRepository.load();
}
@@ -219,134 +272,135 @@ async function readAccountStore() {
async function saveAccountStore(store) {
return accountRepository.save(store);
}
async function readAccount(accountId = null) {
const store = await readAccountStore();
if (!store?.accounts.length) return null;
return store.accounts.find(account => account.id === (accountId || store.activeId)) || null;
}
async function readAccount(accountId = null) {
const store = await readAccountStore();
if (!store?.accounts.length) return null;
return store.accounts.find(account => account.id === (accountId || store.activeId)) || null;
}
async function saveAccount(account) {
return updateAccountStore(store => {
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
const saved = { ...existing, ...account, id: existing?.id || randomUUID() };
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
store.activeId = saved.id;
return saved;
});
}
return updateAccountStore(store => {
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
const saved = { ...existing, ...account, id: existing?.id || randomUUID() };
store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved];
store.activeId = saved.id;
return saved;
});
}
async function connectMail(account) {
const client = await imapClient(account);
let transport;
try {
await client.connect();
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
let transport;
try {
await client.connect();
const mailbox = await client.mailboxOpen('INBOX', { readOnly: true });
transport = await smtpTransport(account);
await transport.verify();
return { mailbox: mailbox.name, messages: mailbox.exists };
} finally {
if (transport) transport.close();
if (client.usable) await client.logout().catch(() => {});
}
}
await transport.verify();
return { mailbox: mailbox.name, messages: mailbox.exists };
} finally {
if (transport) transport.close();
if (client.usable) await client.logout().catch(() => {});
}
}
async function cacheMailboxMessages(accountId, folder, messages) {
if (!messages.length) return;
await updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
if (!account) return;
account.mailCache = account.mailCache || {};
const previous = account.mailCache[folder] || [];
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
for (const message of messages) merged.set(String(message.uid || message.id), message);
account.mailCache[folder] = [...merged.values()].slice(-50);
});
}
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
const start = Math.max(0, Number(offset) || 0);
const messages = all.slice(start, start + limit);
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
}
if (!messages.length) return;
await updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
if (!account) return;
account.mailCache = account.mailCache || {};
const previous = account.mailCache[folder] || [];
const merged = new Map(previous.map(message => [String(message.uid || message.id), message]));
for (const message of messages) merged.set(String(message.uid || message.id), message);
account.mailCache[folder] = [...merged.values()].slice(-50);
});
}
function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters)
.sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0));
const start = Math.max(0, Number(offset) || 0);
const messages = all.slice(start, start + limit);
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
}
async function toUiMessage(item, folder) {
const parsed = await simpleParser(item.source);
const sender = parsed.from?.value?.[0];
const pgpKind = pgpMail.detect(parsed);
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
const content = encrypted
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
const { simpleParser } = await getMailparser();
const parsed = await simpleParser(item.source);
const sender = parsed.from?.value?.[0];
const pgpKind = pgpMail.detect(parsed);
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
const content = encrypted
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
: extractMailContent(parsed);
const { bodyText, body, links } = content;
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
const date = parsed.date || item.internalDate || new Date();
return {
id: Number(item.uid),
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
color: '#dce6df',
sender: sender?.name || sender?.address || 'Unknown sender',
email: sender?.address || '',
subject: parsed.subject || '(no subject)',
snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
encrypted,
pgpSignatures,
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
timestamp: date.getTime(),
unread: !item.flags?.has('\\Seen'),
star: item.flags?.has('\\Flagged') || false,
tags: [folder],
sent: folder === 'Sent',
archived: folder === 'Archive',
deleted: folder === 'Trash',
sourceFolder: folder,
body,
html: content.html,
links,
uid: Number(item.uid),
attachments: content.attachments,
attachment: content.attachment,
size: content.size
};
}
const { bodyText, body, links } = content;
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
const date = parsed.date || item.internalDate || new Date();
return {
id: Number(item.uid),
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
color: '#dce6df',
sender: sender?.name || sender?.address || 'Unknown sender',
email: sender?.address || '',
subject: parsed.subject || '(no subject)',
snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
encrypted,
pgpSignatures,
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
timestamp: date.getTime(),
unread: !item.flags?.has('\\Seen'),
star: item.flags?.has('\\Flagged') || false,
tags: [folder],
sent: folder === 'Sent',
archived: folder === 'Archive',
deleted: folder === 'Trash',
sourceFolder: folder,
body,
html: content.html,
links,
uid: Number(item.uid),
attachments: content.attachments,
attachment: content.attachment,
size: content.size
};
}
async function fetchSnoozedMailbox(account, offset, limit) {
const now = Date.now();
const pending = (account.snoozedMessages || [])
.filter(item => Number(item.dueAt) > now)
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
const now = Date.now();
const pending = (account.snoozedMessages || [])
.filter(item => Number(item.dueAt) > now)
.sort((first, second) => Number(first.dueAt) - Number(second.dueAt));
const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20)));
const client = await imapClient(account);
const messages = [];
try {
await client.connect();
for (const snooze of selected) {
const sourceFolder = String(snooze.folder || 'Inbox');
const mailboxPath = await folderPath(client, sourceFolder);
if (!mailboxPath) continue;
const lock = await client.getMailboxLock(mailboxPath);
try {
const item = await client.fetchOne(Number(snooze.uid), {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}, { uid: true });
if (!item?.source) continue;
const message = await toUiMessage(item, 'Snoozed');
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
messages.push({
...message,
sourceFolder,
snoozedUntil: Number(snooze.dueAt)
});
} finally {
lock.release();
}
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
const messages = [];
try {
await client.connect();
for (const snooze of selected) {
const sourceFolder = String(snooze.folder || 'Inbox');
const mailboxPath = await folderPath(client, sourceFolder);
if (!mailboxPath) continue;
const lock = await client.getMailboxLock(mailboxPath);
try {
const item = await client.fetchOne(Number(snooze.uid), {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}, { uid: true });
if (!item?.source) continue;
const message = await toUiMessage(item, 'Snoozed');
message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || []));
messages.push({
...message,
sourceFolder,
snoozedUntil: Number(snooze.dueAt)
});
} finally {
lock.release();
}
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
}
@@ -366,34 +420,34 @@ const { applyMessageAction } = createMessageActionService({
});
async function saveAccountSyncState(accountId, generation, folders) {
return updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false;
account.syncState = account.syncState || { folders: {} };
account.syncState.folders = folders;
return true;
});
}
return updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false;
account.syncState = account.syncState || { folders: {} };
account.syncState.folders = folders;
return true;
});
}
function showNewMailNotification(account, count) {
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
if (focused) return;
const notification = new Notification({
title: count === 1 ? 'New mail' : `${count} new messages`,
body: account.email
});
notification.show();
}
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
if (focused) return;
const notification = new Notification({
title: count === 1 ? 'New mail' : `${count} new messages`,
body: account.email
});
notification.show();
}
registerIpcHandler('app:get-version', () => app.getVersion());
registerPgpIpcHandlers({
registerIpcHandler,
BrowserWindow,
dialog,
fs,
openpgp,
getOpenPGP,
pgpKeys,
pgpCache,
pgpMail,
@@ -406,7 +460,7 @@ registerPgpIpcHandlers({
readAccount,
imapClient,
folderPath,
simpleParser,
getMailparser,
extractMailContent
});
const { sendMailNow } = createMailSender({ smtpTransport, imapClient, findSentMailbox });
@@ -483,7 +537,7 @@ registerMailIpcHandlers({
mailOutbox,
pgpMail,
PgpError,
simpleParser,
getMailparser,
folderPath,
sendMailNow,
pgpFailure
@@ -496,135 +550,152 @@ registerDavIpcHandlers({
davPublicConfig,
openDavClient,
activeDavConfig,
ICAL,
getICAL,
makeCalendarData,
makeVcard,
randomUUID,
assertDavObjectReference
});
traceStartup('main services and IPC handlers initialized');
function createWindow() {
traceStartup('creating BrowserWindow');
const window = new BrowserWindow({
width: 1440,
height: 920,
minWidth: 920,
minHeight: 680,
title: `ep-mail v${app.getVersion()}`,
backgroundColor: '#f4f5f1',
show: false,
autoHideMenuBar: true,
icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true
}
width: 1440,
height: 920,
minWidth: 920,
minHeight: 680,
title: `ep-mail v${app.getVersion()}`,
backgroundColor: '#f4f5f1',
show: false,
autoHideMenuBar: true,
icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
nodeIntegration: false,
sandbox: true
}
});
window.webContents.on('dom-ready', () => traceStartup('renderer DOM ready'));
window.webContents.on('did-finish-load', () => traceStartup('renderer load complete'));
window.once('ready-to-show', () => {
traceStartup('BrowserWindow ready-to-show');
window.show();
});
window.once('ready-to-show', () => window.show());
window.loadFile(path.join(__dirname, '..', 'index.html'));
window.loadFile(path.join(__dirname, '..', 'index.html')).catch(error => {
traceStartup(`loadFile failed: ${error.message}`);
console.error('Could not load the application window:', error);
});
window.webContents.setWindowOpenHandler(() => {
return { action: 'deny' };
});
window.webContents.on('will-navigate', (event, url) => {
if (!isTrustedApplicationUrl(url, applicationHtmlPath)) event.preventDefault();
});
return window;
}
function showMainWindow() {
let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed());
if (!window) {
window = createWindow();
} else {
if (window.isMinimized()) window.restore();
window.show();
window.focus();
}
}
function createWindowsTray() {
tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 }));
tray.setToolTip('ep-mail');
tray.setContextMenu(Menu.buildFromTemplate([
{ label: 'Open ep-mail', click: showMainWindow },
{ type: 'separator' },
{ label: 'Quit ep-mail', click: () => app.quit() }
]));
tray.on('click', showMainWindow);
tray.on('double-click', showMainWindow);
}
function repairWindowsStartMenuShortcut() {
if (!app.isPackaged) return;
const shortcutPath = path.join(
app.getPath('appData'),
'Microsoft',
'Windows',
'Start Menu',
'Programs',
'ep-mail.lnk'
);
if (!fsSync.existsSync(shortcutPath)) return;
try {
const shortcut = shell.readShortcutLink(shortcutPath);
const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe'
|| shortcut.appUserModelId === windowsAppUserModelId;
if (!isEpMailShortcut) return;
if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return;
const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE;
const executable = portableExecutable && fsSync.existsSync(portableExecutable)
? portableExecutable
: process.execPath;
const updated = shell.writeShortcutLink(shortcutPath, 'update', {
...shortcut,
target: executable,
cwd: path.dirname(executable),
icon: executable,
iconIndex: 0,
appUserModelId: windowsAppUserModelId
});
if (!updated) throw new Error('Windows did not update the shortcut.');
} catch (error) {
console.error('Could not repair the ep-mail Start Menu shortcut:', error);
}
}
return window;
}
function showMainWindow() {
let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed());
if (!window) {
window = createWindow();
} else {
if (window.isMinimized()) window.restore();
window.show();
window.focus();
}
}
function createWindowsTray() {
tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 }));
tray.setToolTip('ep-mail');
tray.setContextMenu(Menu.buildFromTemplate([
{ label: 'Open ep-mail', click: showMainWindow },
{ type: 'separator' },
{ label: 'Quit ep-mail', click: () => app.quit() }
]));
tray.on('click', showMainWindow);
tray.on('double-click', showMainWindow);
}
function repairWindowsStartMenuShortcut() {
if (!app.isPackaged) return;
const shortcutPath = path.join(
app.getPath('appData'),
'Microsoft',
'Windows',
'Start Menu',
'Programs',
'ep-mail.lnk'
);
if (!fsSync.existsSync(shortcutPath)) return;
try {
const shortcut = shell.readShortcutLink(shortcutPath);
const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe'
|| shortcut.appUserModelId === windowsAppUserModelId;
if (!isEpMailShortcut) return;
if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return;
const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE;
const executable = portableExecutable && fsSync.existsSync(portableExecutable)
? portableExecutable
: process.execPath;
const updated = shell.writeShortcutLink(shortcutPath, 'update', {
...shortcut,
target: executable,
cwd: path.dirname(executable),
icon: executable,
iconIndex: 0,
appUserModelId: windowsAppUserModelId
});
if (!updated) throw new Error('Windows did not update the shortcut.');
} catch (error) {
console.error('Could not repair the ep-mail Start Menu shortcut:', error);
}
}
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.');
repairWindowsStartMenuShortcut();
createWindowsTray();
}
createWindow();
const mainWindow = createWindow();
mainWindow.once('ready-to-show', () => {
if (process.platform === 'win32') {
repairWindowsStartMenuShortcut();
createWindowsTray();
}
void checkSnoozeReminders();
const startupSyncTimer = setTimeout(() => requestBackgroundSync(), 3000);
startupSyncTimer.unref();
traceStartup('post-first-frame work started; background sync scheduled');
});
const syncTimer = setInterval(() => {
void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error));
}, backgroundSyncIntervalMs);
syncTimer.unref();
const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs);
snoozeTimer.unref();
void checkSnoozeReminders();
requestBackgroundSync();
powerMonitor.on('suspend', () => {
idleWatcherManager.stopAll();
});
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
});
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('before-quit', () => {
idleWatcherManager.stopAll();
});
+284 -277
View File
@@ -1,277 +1,284 @@
const openpgp = require('openpgp');
const MAX_KEY_LENGTH = 200000;
const MAX_RESPONSE_BYTES = 600000;
const REQUEST_TIMEOUT_MS = 15000;
const MAX_CUSTOM_SERVERS = 10;
const BUILTIN_SERVERS = [
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true }
];
function normalizeBaseUrl(value) {
const raw = String(value || '').trim();
if (raw.length > 300) throw new Error('The key server URL is too long.');
let url;
try {
url = new URL(raw);
} catch {
throw new Error('Enter a valid HTTPS key server URL.');
}
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
throw new Error('Key server URLs must use HTTPS and cannot contain credentials, a query, or a fragment.');
}
url.pathname = `${url.pathname.replace(/\/+$/, '')}/`;
return url.toString();
}
function normalizeCustomServer(input) {
const name = String(input?.name || '').trim().slice(0, 60);
const protocol = input?.protocol;
if (!name) throw new Error('Enter a name for the key server.');
if (!['hkp', 'vks'].includes(protocol)) throw new Error('Choose a supported HKP or VKS protocol.');
return {
id: String(input?.id || ''),
name,
url: normalizeBaseUrl(input?.url),
protocol,
builtin: false
};
}
function listServers(customServers = [], enabledServerIds = []) {
const enabled = new Set(enabledServerIds);
return [
...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })),
...customServers.map(server => {
const normalized = normalizeCustomServer(server);
return { ...normalized, enabled: enabled.has(normalized.id) };
})
];
}
function validateEmail(value) {
const email = String(value || '').trim();
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new Error('Enter a valid email address.');
return email;
}
function baseUrl(server) {
return new URL(normalizeBaseUrl(server.url));
}
function endpoint(server, path) {
return new URL(path, baseUrl(server));
}
async function readResponseText(response) {
const declaredLength = Number(response.headers?.get?.('content-length') || 0);
if (declaredLength > MAX_RESPONSE_BYTES) throw new Error('The key server response is too large.');
if (!response.body) return '';
const chunks = [];
let length = 0;
for await (const chunk of response.body) {
const bytes = Buffer.from(chunk);
length += bytes.length;
if (length > MAX_RESPONSE_BYTES) {
throw new Error('The key server response is too large.');
}
chunks.push(bytes);
}
return Buffer.concat(chunks, length).toString('utf8');
}
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
if (typeof fetchImpl !== 'function') throw new Error('Fetch is unavailable for key server requests.');
async function request(server, url, options = {}) {
let response;
try {
response = await fetchImpl(url, {
...options,
redirect: 'error',
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
} catch (error) {
throw new Error(`Could not reach ${server.name}: ${error.message}`);
}
const text = await readResponseText(response);
return { response, text };
}
async function parsePublicKeys(armored, email) {
if (typeof armored !== 'string' || armored.length > MAX_RESPONSE_BYTES) {
throw new Error('The key server returned an invalid or oversized key response.');
}
const blocks = armored.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g) || [];
if (!blocks.length) {
if (!armored.trim() || /no (matching )?keys|no results/i.test(armored)) return [];
throw new Error('The key server response did not contain an OpenPGP public key.');
}
if (blocks.length > 10) throw new Error('The key server returned too many keys.');
const keys = [];
const seen = new Set();
let validKeyCount = 0;
for (const block of blocks) {
if (block.length > MAX_KEY_LENGTH) continue;
const key = await openpgp.readKey({ armoredKey: block }).catch(() => null);
if (!key) continue;
const fingerprint = key.getFingerprint().toUpperCase();
if (seen.has(fingerprint)) continue;
seen.add(fingerprint);
const emails = [...new Set(key.getUserIDs()
.map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase())
.filter(Boolean))];
const primary = await key.getPrimaryUser().catch(() => null);
if (!primary) continue;
validKeyCount += 1;
if (email && !emails.includes(email.toLowerCase())) continue;
keys.push({
fingerprint,
name: primary.user.userID?.name || '',
emails,
armoredKey: key.armor()
});
}
if (!validKeyCount) throw new Error('The key server returned no valid public keys.');
return keys;
}
async function lookup(serverInput, emailInput) {
const server = normalizeCustomServer(serverInput);
const email = validateEmail(emailInput);
let url;
if (server.protocol === 'vks') {
url = endpoint(server, `vks/v1/by-email/${encodeURIComponent(email)}`);
} else {
url = endpoint(server, 'pks/lookup');
url.searchParams.set('op', 'get');
url.searchParams.set('search', email);
}
const { response, text } = await request(server, url);
if (response.status === 404) return [];
if (!response.ok) throw new Error(`${server.name} returned HTTP ${response.status}.`);
let armored = text;
if (server.protocol === 'hkp' && /^\s*\{/.test(text)) {
try {
const data = JSON.parse(text);
armored = data.publicKeyArmored || '';
} catch {
throw new Error(`${server.name} returned an invalid key response.`);
}
}
return parsePublicKeys(armored, email);
}
async function lookupEnabled(serverInputs, emailInput) {
const servers = serverInputs.filter(server => server.enabled === true);
if (!servers.length) throw new Error('Enable at least one key server before searching.');
const email = validateEmail(emailInput);
const lookups = await Promise.all(servers.map(async server => {
try {
return { server, keys: await lookup(server, email), error: null };
} catch (error) {
return { server, keys: [], error: error.message };
}
}));
const keysByFingerprint = new Map();
for (const result of lookups) {
for (const key of result.keys) {
const existing = keysByFingerprint.get(key.fingerprint);
if (existing) existing.sources.push(result.server.name);
else keysByFingerprint.set(key.fingerprint, { ...key, sources: [result.server.name] });
}
}
return {
keys: [...keysByFingerprint.values()],
searchedServers: lookups.map(({ server }) => ({ id: server.id, name: server.name })),
errors: lookups.filter(result => result.error).map(({ server, error }) => ({
id: server.id,
name: server.name,
message: error
}))
};
}
async function publishVks(server, email, armoredKey, expectedFingerprint) {
const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ keytext: armoredKey })
});
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
let result;
try { result = JSON.parse(text); } catch { throw new Error(`${server.name} returned an invalid upload response.`); }
if (String(result.key_fpr || '').toUpperCase() !== expectedFingerprint || !result.token || !result.status || typeof result.status !== 'object') {
throw new Error(`${server.name} returned an incomplete or mismatched upload response.`);
}
const addressStatus = Object.entries(result.status).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
if (addressStatus === 'published') return { uploaded: true, verification: 'published' };
if (addressStatus === 'pending') return { uploaded: true, verification: 'pending' };
if (addressStatus !== 'unpublished') {
return { uploaded: true, verification: addressStatus || 'unknown' };
}
try {
const verify = await request(server, endpoint(server, 'vks/v1/request-verify'), {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ token: result.token, addresses: [email] })
});
if (!verify.response.ok) throw new Error(`HTTP ${verify.response.status}`);
let verified;
try { verified = JSON.parse(verify.text); } catch { throw new Error('invalid verification response'); }
if (String(verified.key_fpr || '').toUpperCase() !== expectedFingerprint || !verified.status || typeof verified.status !== 'object') {
throw new Error('verification response did not match the uploaded key');
}
const state = Object.entries(verified.status || {}).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
return { uploaded: true, verification: state || 'requested' };
} catch (error) {
return { uploaded: true, verification: 'request-failed', warning: `The key was uploaded, but email verification could not be requested: ${error.message}` };
}
}
async function publishHkp(server, armoredKey) {
const form = new URLSearchParams({ keytext: armoredKey });
const { response, text } = await request(server, endpoint(server, 'pks/add'), {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: form.toString()
});
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
if (!/upload successful|successfully added|key added/i.test(text)) {
throw new Error(`${server.name} did not confirm the key upload: ${text.trim().slice(0, 300) || 'empty response'}`);
}
return {
uploaded: true,
verification: server.id === 'mailvelope-hkp' ? 'check-email' : 'server-accepted',
message: text.trim().slice(0, 500)
};
}
async function publish(serverInput, emailInput, armoredInput, expectedFingerprint) {
const server = normalizeCustomServer(serverInput);
const email = validateEmail(emailInput);
const armoredKey = String(armoredInput || '').trim();
if (!armoredKey || armoredKey.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armoredKey)) {
throw new Error('Only a valid public key can be published.');
}
const keys = await parsePublicKeys(armoredKey, email);
if (keys.length !== 1 || keys[0].fingerprint !== String(expectedFingerprint || '').toUpperCase()) {
throw new Error('The selected public key does not match the key and email being published.');
}
if (server.protocol === 'vks') return publishVks(server, email, keys[0].armoredKey, keys[0].fingerprint);
return publishHkp(server, keys[0].armoredKey);
}
return { lookup, lookupEnabled, publish };
}
module.exports = {
BUILTIN_SERVERS,
MAX_CUSTOM_SERVERS,
createKeyServerService,
listServers,
normalizeBaseUrl,
normalizeCustomServer
};
const openpgp = require('openpgp');
const MAX_KEY_LENGTH = 200000;
const MAX_RESPONSE_BYTES = 600000;
const REQUEST_TIMEOUT_MS = 15000;
const MAX_CUSTOM_SERVERS = 10;
const BUILTIN_SERVERS = [
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true },
{ id: 'eternity-vks', name: 'keys.eternityproject.fi', url: 'https://keys.eternityproject.fi', protocol: 'vks', builtin: true }
];
const BUILTIN_SERVER_IDS = BUILTIN_SERVERS.map(server => server.id);
function normalizeBaseUrl(value) {
const raw = String(value || '').trim();
if (raw.length > 300) throw new Error('The key server URL is too long.');
let url;
try {
url = new URL(raw);
} catch {
throw new Error('Enter a valid HTTPS key server URL.');
}
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
throw new Error('Key server URLs must use HTTPS and cannot contain credentials, a query, or a fragment.');
}
url.pathname = `${url.pathname.replace(/\/+$/, '')}/`;
return url.toString();
}
function normalizeCustomServer(input) {
const name = String(input?.name || '').trim().slice(0, 60);
const protocol = input?.protocol;
if (!name) throw new Error('Enter a name for the key server.');
if (!['hkp', 'vks'].includes(protocol)) throw new Error('Choose a supported HKP or VKS protocol.');
return {
id: String(input?.id || ''),
name,
url: normalizeBaseUrl(input?.url),
protocol,
builtin: false
};
}
function listServers(customServers = [], enabledServerIds = [], removedBuiltinIds = []) {
const enabled = new Set(enabledServerIds);
const removed = new Set(removedBuiltinIds);
return [
...BUILTIN_SERVERS.filter(server => !removed.has(server.id)).map(server => ({ ...server, enabled: enabled.has(server.id) })),
...customServers.map(server => {
const normalized = normalizeCustomServer(server);
return { ...normalized, enabled: enabled.has(normalized.id) };
})
];
}
function validateEmail(value) {
const email = String(value || '').trim();
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new Error('Enter a valid email address.');
return email;
}
function baseUrl(server) {
return new URL(normalizeBaseUrl(server.url));
}
function endpoint(server, path) {
return new URL(path, baseUrl(server));
}
async function readResponseText(response) {
const declaredLength = Number(response.headers?.get?.('content-length') || 0);
if (declaredLength > MAX_RESPONSE_BYTES) throw new Error('The key server response is too large.');
if (!response.body) return '';
const chunks = [];
let length = 0;
for await (const chunk of response.body) {
const bytes = typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;
length += bytes.length;
if (length > MAX_RESPONSE_BYTES) {
throw new Error('The key server response is too large.');
}
chunks.push(bytes);
}
const joined = new Uint8Array(length);
let offset = 0;
for (const bytes of chunks) { joined.set(bytes, offset); offset += bytes.length; }
return new TextDecoder().decode(joined);
}
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
if (typeof fetchImpl !== 'function') throw new Error('Fetch is unavailable for key server requests.');
async function request(server, url, options = {}) {
let response;
try {
response = await fetchImpl(url, {
...options,
redirect: 'error',
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
});
} catch (error) {
throw new Error(`Could not reach ${server.name}: ${error.message}`);
}
const text = await readResponseText(response);
return { response, text };
}
async function parsePublicKeys(armored, email) {
if (typeof armored !== 'string' || armored.length > MAX_RESPONSE_BYTES) {
throw new Error('The key server returned an invalid or oversized key response.');
}
const blocks = armored.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g) || [];
if (!blocks.length) {
if (!armored.trim() || /no (matching )?keys|no results/i.test(armored)) return [];
throw new Error('The key server response did not contain an OpenPGP public key.');
}
if (blocks.length > 10) throw new Error('The key server returned too many keys.');
const keys = [];
const seen = new Set();
let validKeyCount = 0;
for (const block of blocks) {
if (block.length > MAX_KEY_LENGTH) continue;
const key = await openpgp.readKey({ armoredKey: block }).catch(() => null);
if (!key) continue;
const fingerprint = key.getFingerprint().toUpperCase();
if (seen.has(fingerprint)) continue;
seen.add(fingerprint);
const emails = [...new Set(key.getUserIDs()
.map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase())
.filter(Boolean))];
const primary = await key.getPrimaryUser().catch(() => null);
if (!primary) continue;
validKeyCount += 1;
if (email && !emails.includes(email.toLowerCase())) continue;
keys.push({
fingerprint,
name: primary.user.userID?.name || '',
emails,
armoredKey: key.armor()
});
}
if (!validKeyCount) throw new Error('The key server returned no valid public keys.');
return keys;
}
async function lookup(serverInput, emailInput) {
const server = normalizeCustomServer(serverInput);
const email = validateEmail(emailInput);
let url;
if (server.protocol === 'vks') {
url = endpoint(server, `vks/v1/by-email/${encodeURIComponent(email)}`);
} else {
url = endpoint(server, 'pks/lookup');
url.searchParams.set('op', 'get');
url.searchParams.set('search', email);
}
const { response, text } = await request(server, url);
if (response.status === 404) return [];
if (!response.ok) throw new Error(`${server.name} returned HTTP ${response.status}.`);
let armored = text;
if (server.protocol === 'hkp' && /^\s*\{/.test(text)) {
try {
const data = JSON.parse(text);
armored = data.publicKeyArmored || '';
} catch {
throw new Error(`${server.name} returned an invalid key response.`);
}
}
return parsePublicKeys(armored, email);
}
async function lookupEnabled(serverInputs, emailInput) {
const servers = serverInputs.filter(server => server.enabled === true);
if (!servers.length) throw new Error('Enable at least one key server before searching.');
const email = validateEmail(emailInput);
const lookups = await Promise.all(servers.map(async server => {
try {
return { server, keys: await lookup(server, email), error: null };
} catch (error) {
return { server, keys: [], error: error.message };
}
}));
const keysByFingerprint = new Map();
for (const result of lookups) {
for (const key of result.keys) {
const existing = keysByFingerprint.get(key.fingerprint);
if (existing) existing.sources.push(result.server.name);
else keysByFingerprint.set(key.fingerprint, { ...key, sources: [result.server.name] });
}
}
return {
keys: [...keysByFingerprint.values()],
searchedServers: lookups.map(({ server }) => ({ id: server.id, name: server.name })),
errors: lookups.filter(result => result.error).map(({ server, error }) => ({
id: server.id,
name: server.name,
message: error
}))
};
}
async function publishVks(server, email, armoredKey, expectedFingerprint) {
const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ keytext: armoredKey })
});
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
let result;
try { result = JSON.parse(text); } catch { throw new Error(`${server.name} returned an invalid upload response.`); }
if (String(result.key_fpr || '').toUpperCase() !== expectedFingerprint || !result.token || !result.status || typeof result.status !== 'object') {
throw new Error(`${server.name} returned an incomplete or mismatched upload response.`);
}
const addressStatus = Object.entries(result.status).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
if (addressStatus === 'published') return { uploaded: true, verification: 'published' };
if (addressStatus === 'pending') return { uploaded: true, verification: 'pending' };
if (addressStatus !== 'unpublished') {
return { uploaded: true, verification: addressStatus || 'unknown' };
}
try {
const verify = await request(server, endpoint(server, 'vks/v1/request-verify'), {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'application/json' },
body: JSON.stringify({ token: result.token, addresses: [email] })
});
if (!verify.response.ok) throw new Error(`HTTP ${verify.response.status}`);
let verified;
try { verified = JSON.parse(verify.text); } catch { throw new Error('invalid verification response'); }
if (String(verified.key_fpr || '').toUpperCase() !== expectedFingerprint || !verified.status || typeof verified.status !== 'object') {
throw new Error('verification response did not match the uploaded key');
}
const state = Object.entries(verified.status || {}).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
return { uploaded: true, verification: state || 'requested' };
} catch (error) {
return { uploaded: true, verification: 'request-failed', warning: `The key was uploaded, but email verification could not be requested: ${error.message}` };
}
}
async function publishHkp(server, armoredKey) {
const form = new URLSearchParams({ keytext: armoredKey });
const { response, text } = await request(server, endpoint(server, 'pks/add'), {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: form.toString()
});
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
if (!/upload successful|successfully added|key added/i.test(text)) {
throw new Error(`${server.name} did not confirm the key upload: ${text.trim().slice(0, 300) || 'empty response'}`);
}
return {
uploaded: true,
verification: server.id === 'mailvelope-hkp' ? 'check-email' : 'server-accepted',
message: text.trim().slice(0, 500)
};
}
async function publish(serverInput, emailInput, armoredInput, expectedFingerprint) {
const server = normalizeCustomServer(serverInput);
const email = validateEmail(emailInput);
const armoredKey = String(armoredInput || '').trim();
if (!armoredKey || armoredKey.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armoredKey)) {
throw new Error('Only a valid public key can be published.');
}
const keys = await parsePublicKeys(armoredKey, email);
if (keys.length !== 1 || keys[0].fingerprint !== String(expectedFingerprint || '').toUpperCase()) {
throw new Error('The selected public key does not match the key and email being published.');
}
if (server.protocol === 'vks') return publishVks(server, email, keys[0].armoredKey, keys[0].fingerprint);
return publishHkp(server, keys[0].armoredKey);
}
return { lookup, lookupEnabled, publish };
}
module.exports = {
BUILTIN_SERVERS,
BUILTIN_SERVER_IDS,
MAX_CUSTOM_SERVERS,
createKeyServerService,
listServers,
normalizeBaseUrl,
normalizeCustomServer
};
+356 -346
View File
@@ -1,346 +1,356 @@
const openpgp = require('openpgp');
const MAX_KEY_LENGTH = 200000;
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)
};
}
function requirePassphrase(passphrase) {
if (typeof passphrase !== 'string' || passphrase.length < 8) {
throw new Error('Use a passphrase of at least 8 characters.');
}
return passphrase;
}
function readArmored(value) {
const armored = String(value || '').trim();
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
return armored;
}
async function unlock(armoredPrivateKey, passphrase) {
try {
return await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: armoredPrivateKey }),
passphrase
});
} catch {
throw new Error('The passphrase is incorrect.');
}
}
const TRUST_LEVELS = ['unknown', 'trusted', 'verified'];
const DEFAULT_CACHE_MINUTES = 10;
function contactInfo(entry) {
return {
fingerprint: entry.fingerprint,
name: entry.name,
emails: entry.emails,
trust: entry.trust,
source: entry.source,
addedAt: entry.addedAt
};
}
async function readPublicOnly(value) {
const armored = readArmored(value);
if (/BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('That file contains a private key. Import public keys only.');
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.');
});
return key;
}
async function keyEmails(key) {
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
}
// Passphrase-protected OpenPGP key storage. `storage` persists one JSON object
// (the desktop app wraps it with the OS credential store before writing it).
function createKeyStore(storage) {
async function read() {
const data = await storage.load();
return {
keys: Array.isArray(data?.keys) ? data.keys : [],
contacts: Array.isArray(data?.contacts) ? data.contacts : [],
settings: data?.settings && typeof data.settings === 'object' ? data.settings : {}
};
}
async function add(entry) {
const data = await read();
if (data.keys.some(key => key.fingerprint === entry.fingerprint)) {
throw new Error('That key is already in your keyring.');
}
data.keys.push(entry);
await storage.save(data);
}
return {
async listContacts() {
return (await read()).contacts.map(contactInfo);
},
async addContact({ armoredKey, source = 'import' }) {
const key = await readPublicOnly(armoredKey);
const fingerprint = key.getFingerprint().toUpperCase();
const emails = await keyEmails(key);
const data = await read();
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 user = await key.getPrimaryUser();
const replaces = data.contacts
.filter(entry => entry.emails.some(email => emails.includes(email)))
.map(entry => entry.fingerprint);
const entry = {
fingerprint,
name: user.user.userID?.name || '',
emails,
trust: 'unknown',
source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import',
addedAt: Date.now(),
publicKey: key.armor()
};
data.contacts.push(entry);
await storage.save(data);
return { contact: contactInfo(entry), keyChangedFrom: replaces };
},
async setTrust(fingerprint, trust) {
if (!TRUST_LEVELS.includes(trust)) throw new Error('Unknown trust level.');
const data = await read();
const entry = data.contacts.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That contact key was not found.');
entry.trust = trust;
await storage.save(data);
return contactInfo(entry);
},
async removeContact(fingerprint) {
const data = await read();
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 storage.save(data);
return { removed: true };
},
async exportContact(fingerprint) {
const entry = (await read()).contacts.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That contact key was not found.');
return entry.publicKey;
},
// Resolves public keys for recipient addresses (contacts and own keys).
async findRecipientKeys(addresses) {
const data = await read();
const pool = [
...data.contacts.map(entry => ({ ...entry, own: false })),
...data.keys.map(entry => ({ fingerprint: entry.fingerprint, emails: [String(entry.email).toLowerCase()], trust: 'verified', addedAt: entry.createdAt, publicKey: entry.publicKey, own: true }))
];
const keys = [];
const missing = [];
for (const address of addresses.map(value => String(value).trim().toLowerCase())) {
const candidates = pool
.filter(entry => entry.emails.includes(address))
.sort((a, b) => TRUST_LEVELS.indexOf(b.trust) - TRUST_LEVELS.indexOf(a.trust) || b.addedAt - a.addedAt);
let usable = null;
for (const candidate of candidates) {
try {
const key = await openpgp.readKey({ armoredKey: candidate.publicKey });
await key.getEncryptionKey();
usable = { key, fingerprint: candidate.fingerprint, trust: candidate.trust };
break;
} catch { /* expired or revoked: try the next key */ }
}
if (usable) keys.push({ address, ...usable });
else missing.push(address);
}
return { keys, missing };
},
async verificationKeys() {
const data = await read();
const result = [];
for (const entry of [...data.contacts.map(item => ({ ...item, own: false })), ...data.keys.map(item => ({ ...item, trust: 'verified', emails: [String(item.email).toLowerCase()], own: true }))]) {
try {
result.push({ key: await openpgp.readKey({ armoredKey: entry.publicKey }), fingerprint: entry.fingerprint, trust: entry.trust, emails: entry.emails, own: entry.own });
} catch { /* skip unreadable entries */ }
}
return result;
},
async privateEntries() {
return (await read()).keys.map(entry => ({ fingerprint: entry.fingerprint, email: entry.email, name: entry.name, privateKey: entry.privateKey, publicKey: entry.publicKey }));
},
async unlockKey(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
return unlock(entry.privateKey, passphrase);
},
async getSettings() {
const settings = (await read()).settings;
return {
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
: []
};
},
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) {
const minutes = Number(cacheMinutes);
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
const data = await read();
data.settings.cacheMinutes = Math.round(minutes);
if (customKeyServers !== undefined) {
if (!Array.isArray(customKeyServers) || customKeyServers.length > 10 || customKeyServers.some(server => !server || typeof server !== 'object')) {
throw new Error('You can configure up to 10 valid custom key servers.');
}
data.settings.customKeyServers = customKeyServers.map(server => ({
id: String(server.id || ''),
name: String(server.name || '').slice(0, 60),
url: String(server.url || '').slice(0, 300),
protocol: String(server.protocol || '')
}));
}
if (enabledKeyServers !== undefined) {
if (!Array.isArray(enabledKeyServers) || enabledKeyServers.length > 12 || enabledKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
throw new Error('Choose no more than 12 valid enabled key servers.');
}
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
}
await storage.save(data);
return {
cacheMinutes: data.settings.cacheMinutes,
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : []
};
},
async list() {
return (await read()).keys.map(publicInfo);
},
async generate({ name, email, passphrase, accountId = null }) {
const cleanName = String(name || '').trim().slice(0, 100);
const cleanEmail = String(email || '').trim();
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
requirePassphrase(passphrase);
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
type: 'ecc',
curve: 'curve25519Legacy',
userIDs: [{ name: cleanName || undefined, email: cleanEmail }],
passphrase,
format: 'armored'
});
const key = await openpgp.readKey({ armoredKey: publicKey });
const entry = {
fingerprint: key.getFingerprint().toUpperCase(),
name: cleanName,
email: cleanEmail,
accountId,
createdAt: Date.now(),
algorithm: 'Curve25519',
privateKey,
publicKey,
revocationCertificate
};
await add(entry);
return { key: publicInfo(entry), revocationCertificate };
},
async import({ armoredKey, passphrase, accountId = null }) {
const parsed = await openpgp.readPrivateKey({ armoredKey: readArmored(armoredKey) }).catch(() => {
throw new Error('That is not a valid OpenPGP private key.');
});
requirePassphrase(passphrase);
let protectedKey;
if (parsed.isDecrypted()) {
protectedKey = await openpgp.encryptKey({ privateKey: parsed, passphrase });
} else {
await unlock(parsed.armor(), passphrase);
protectedKey = parsed;
}
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: protectedKey.toPublic().armor(),
revocationCertificate: null
};
await add(entry);
return publicInfo(entry);
},
async exportPublic(fingerprint) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
return entry.publicKey;
},
async exportPrivate(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
await unlock(entry.privateKey, passphrase);
return entry.privateKey;
},
async changePassphrase(fingerprint, currentPassphrase, newPassphrase) {
requirePassphrase(newPassphrase);
const data = await read();
const keyIndex = data.keys.findIndex(key => key.fingerprint === fingerprint);
if (keyIndex < 0) throw new Error('That key was not found.');
const entry = data.keys[keyIndex];
const privateKey = await unlock(entry.privateKey, currentPassphrase);
const protectedKey = await openpgp.encryptKey({ privateKey, passphrase: newPassphrase });
const updated = {
...data,
keys: data.keys.map((key, index) => index === keyIndex
? { ...key, privateKey: protectedKey.armor() }
: key)
};
await storage.save(updated);
return { changed: true };
},
async exportRevocation(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
if (!entry.revocationCertificate) throw new Error('No revocation certificate is stored for this key.');
await unlock(entry.privateKey, passphrase);
return entry.revocationCertificate;
},
async remove(fingerprint, passphrase) {
const data = await read();
const entry = data.keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
await unlock(entry.privateKey, passphrase);
data.keys = data.keys.filter(key => key.fingerprint !== fingerprint);
await storage.save(data);
return { removed: true };
}
};
}
module.exports = { createKeyStore };
const openpgp = require('openpgp');
const MAX_KEY_LENGTH = 200000;
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)
};
}
function requirePassphrase(passphrase) {
if (typeof passphrase !== 'string' || passphrase.length < 8) {
throw new Error('Use a passphrase of at least 8 characters.');
}
return passphrase;
}
function readArmored(value) {
const armored = String(value || '').trim();
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
return armored;
}
async function unlock(armoredPrivateKey, passphrase) {
try {
return await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: armoredPrivateKey }),
passphrase
});
} catch {
throw new Error('The passphrase is incorrect.');
}
}
const TRUST_LEVELS = ['unknown', 'trusted', 'verified'];
const DEFAULT_CACHE_MINUTES = 10;
function contactInfo(entry) {
return {
fingerprint: entry.fingerprint,
name: entry.name,
emails: entry.emails,
trust: entry.trust,
source: entry.source,
addedAt: entry.addedAt
};
}
async function readPublicOnly(value) {
const armored = readArmored(value);
if (/BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('That file contains a private key. Import public keys only.');
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.');
});
return key;
}
async function keyEmails(key) {
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
}
// Passphrase-protected OpenPGP key storage. `storage` persists one JSON object
// (the desktop app wraps it with the OS credential store before writing it).
function createKeyStore(storage) {
async function read() {
const data = await storage.load();
return {
keys: Array.isArray(data?.keys) ? data.keys : [],
contacts: Array.isArray(data?.contacts) ? data.contacts : [],
settings: data?.settings && typeof data.settings === 'object' ? data.settings : {}
};
}
async function add(entry) {
const data = await read();
if (data.keys.some(key => key.fingerprint === entry.fingerprint)) {
throw new Error('That key is already in your keyring.');
}
data.keys.push(entry);
await storage.save(data);
}
return {
async listContacts() {
return (await read()).contacts.map(contactInfo);
},
async addContact({ armoredKey, source = 'import' }) {
const key = await readPublicOnly(armoredKey);
const fingerprint = key.getFingerprint().toUpperCase();
const emails = await keyEmails(key);
const data = await read();
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 user = await key.getPrimaryUser();
const replaces = data.contacts
.filter(entry => entry.emails.some(email => emails.includes(email)))
.map(entry => entry.fingerprint);
const entry = {
fingerprint,
name: user.user.userID?.name || '',
emails,
trust: 'unknown',
source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import',
addedAt: Date.now(),
publicKey: key.armor()
};
data.contacts.push(entry);
await storage.save(data);
return { contact: contactInfo(entry), keyChangedFrom: replaces };
},
async setTrust(fingerprint, trust) {
if (!TRUST_LEVELS.includes(trust)) throw new Error('Unknown trust level.');
const data = await read();
const entry = data.contacts.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That contact key was not found.');
entry.trust = trust;
await storage.save(data);
return contactInfo(entry);
},
async removeContact(fingerprint) {
const data = await read();
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 storage.save(data);
return { removed: true };
},
async exportContact(fingerprint) {
const entry = (await read()).contacts.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That contact key was not found.');
return entry.publicKey;
},
// Resolves public keys for recipient addresses (contacts and own keys).
async findRecipientKeys(addresses) {
const data = await read();
const pool = [
...data.contacts.map(entry => ({ ...entry, own: false })),
...data.keys.map(entry => ({ fingerprint: entry.fingerprint, emails: [String(entry.email).toLowerCase()], trust: 'verified', addedAt: entry.createdAt, publicKey: entry.publicKey, own: true }))
];
const keys = [];
const missing = [];
for (const address of addresses.map(value => String(value).trim().toLowerCase())) {
const candidates = pool
.filter(entry => entry.emails.includes(address))
.sort((a, b) => TRUST_LEVELS.indexOf(b.trust) - TRUST_LEVELS.indexOf(a.trust) || b.addedAt - a.addedAt);
let usable = null;
for (const candidate of candidates) {
try {
const key = await openpgp.readKey({ armoredKey: candidate.publicKey });
await key.getEncryptionKey();
usable = { key, fingerprint: candidate.fingerprint, trust: candidate.trust };
break;
} catch { /* expired or revoked: try the next key */ }
}
if (usable) keys.push({ address, ...usable });
else missing.push(address);
}
return { keys, missing };
},
async verificationKeys() {
const data = await read();
const result = [];
for (const entry of [...data.contacts.map(item => ({ ...item, own: false })), ...data.keys.map(item => ({ ...item, trust: 'verified', emails: [String(item.email).toLowerCase()], own: true }))]) {
try {
result.push({ key: await openpgp.readKey({ armoredKey: entry.publicKey }), fingerprint: entry.fingerprint, trust: entry.trust, emails: entry.emails, own: entry.own });
} catch { /* skip unreadable entries */ }
}
return result;
},
async privateEntries() {
return (await read()).keys.map(entry => ({ fingerprint: entry.fingerprint, email: entry.email, name: entry.name, privateKey: entry.privateKey, publicKey: entry.publicKey }));
},
async unlockKey(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
return unlock(entry.privateKey, passphrase);
},
async getSettings() {
const settings = (await read()).settings;
return {
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
: [],
removedBuiltinKeyServers: Array.isArray(settings.removedBuiltinKeyServers)
? [...new Set(settings.removedBuiltinKeyServers.filter(id => typeof id === 'string'))]
: []
};
},
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers, removedBuiltinKeyServers }) {
const minutes = Number(cacheMinutes);
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
const data = await read();
data.settings.cacheMinutes = Math.round(minutes);
if (customKeyServers !== undefined) {
if (!Array.isArray(customKeyServers) || customKeyServers.length > 10 || customKeyServers.some(server => !server || typeof server !== 'object')) {
throw new Error('You can configure up to 10 valid custom key servers.');
}
data.settings.customKeyServers = customKeyServers.map(server => ({
id: String(server.id || ''),
name: String(server.name || '').slice(0, 60),
url: String(server.url || '').slice(0, 300),
protocol: String(server.protocol || '')
}));
}
if (enabledKeyServers !== undefined) {
if (!Array.isArray(enabledKeyServers) || enabledKeyServers.length > 12 || enabledKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
throw new Error('Choose no more than 12 valid enabled key servers.');
}
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
}
if (removedBuiltinKeyServers !== undefined) {
if (!Array.isArray(removedBuiltinKeyServers) || removedBuiltinKeyServers.length > 12 || removedBuiltinKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
throw new Error('Choose no more than 12 valid built-in key servers to remove.');
}
data.settings.removedBuiltinKeyServers = [...new Set(removedBuiltinKeyServers)];
}
await storage.save(data);
return {
cacheMinutes: data.settings.cacheMinutes,
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : [],
removedBuiltinKeyServers: Array.isArray(data.settings.removedBuiltinKeyServers) ? [...data.settings.removedBuiltinKeyServers] : []
};
},
async list() {
return (await read()).keys.map(publicInfo);
},
async generate({ name, email, passphrase, accountId = null }) {
const cleanName = String(name || '').trim().slice(0, 100);
const cleanEmail = String(email || '').trim();
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
requirePassphrase(passphrase);
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
type: 'ecc',
curve: 'curve25519Legacy',
userIDs: [{ name: cleanName || undefined, email: cleanEmail }],
passphrase,
format: 'armored'
});
const key = await openpgp.readKey({ armoredKey: publicKey });
const entry = {
fingerprint: key.getFingerprint().toUpperCase(),
name: cleanName,
email: cleanEmail,
accountId,
createdAt: Date.now(),
algorithm: 'Curve25519',
privateKey,
publicKey,
revocationCertificate
};
await add(entry);
return { key: publicInfo(entry), revocationCertificate };
},
async import({ armoredKey, passphrase, accountId = null }) {
const parsed = await openpgp.readPrivateKey({ armoredKey: readArmored(armoredKey) }).catch(() => {
throw new Error('That is not a valid OpenPGP private key.');
});
requirePassphrase(passphrase);
let protectedKey;
if (parsed.isDecrypted()) {
protectedKey = await openpgp.encryptKey({ privateKey: parsed, passphrase });
} else {
await unlock(parsed.armor(), passphrase);
protectedKey = parsed;
}
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: protectedKey.toPublic().armor(),
revocationCertificate: null
};
await add(entry);
return publicInfo(entry);
},
async exportPublic(fingerprint) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
return entry.publicKey;
},
async exportPrivate(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
await unlock(entry.privateKey, passphrase);
return entry.privateKey;
},
async changePassphrase(fingerprint, currentPassphrase, newPassphrase) {
requirePassphrase(newPassphrase);
const data = await read();
const keyIndex = data.keys.findIndex(key => key.fingerprint === fingerprint);
if (keyIndex < 0) throw new Error('That key was not found.');
const entry = data.keys[keyIndex];
const privateKey = await unlock(entry.privateKey, currentPassphrase);
const protectedKey = await openpgp.encryptKey({ privateKey, passphrase: newPassphrase });
const updated = {
...data,
keys: data.keys.map((key, index) => index === keyIndex
? { ...key, privateKey: protectedKey.armor() }
: key)
};
await storage.save(updated);
return { changed: true };
},
async exportRevocation(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
if (!entry.revocationCertificate) throw new Error('No revocation certificate is stored for this key.');
await unlock(entry.privateKey, passphrase);
return entry.revocationCertificate;
},
async remove(fingerprint, passphrase) {
const data = await read();
const entry = data.keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
await unlock(entry.privateKey, passphrase);
data.keys = data.keys.filter(key => key.fingerprint !== fingerprint);
await storage.save(data);
return { removed: true };
}
};
}
module.exports = { createKeyStore };
+376 -376
View File
@@ -1,376 +1,376 @@
const openpgp = require('openpgp');
const { simpleParser } = require('mailparser');
const addressParser = require('nodemailer/lib/addressparser');
const MailComposer = require('nodemailer/lib/mail-composer');
const { randomBytes } = require('node:crypto');
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
const CLEARTEXT_SIGNED = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/;
const MAX_ENCRYPTED_BYTES = 60 * 1048576;
class PgpError extends Error {
constructor(code, message, details = {}) {
super(message);
this.code = code;
this.details = details;
}
}
// Remembers unlocked-key passphrases in memory only, for a limited time.
function createPassphraseCache(getMinutes, now = () => Date.now()) {
const entries = new Map();
return {
async remember(fingerprint, passphrase) {
const minutes = await getMinutes();
if (!minutes) { entries.delete(fingerprint); return; }
entries.set(fingerprint, { passphrase, expires: now() + minutes * 60000 });
},
get(fingerprint) {
const entry = entries.get(fingerprint);
if (!entry) return null;
if (entry.expires <= now()) { entries.delete(fingerprint); return null; }
return entry.passphrase;
},
has(fingerprint) { return this.get(fingerprint) !== null; },
clear(fingerprint) { if (fingerprint) entries.delete(fingerprint); else entries.clear(); }
};
}
function headerValue(parsed, name) {
const value = parsed.headers?.get(name);
return value && typeof value === 'object' ? value : { value: String(value || ''), params: {} };
}
// Classifies a parsed message: encrypted/signed PGP/MIME or inline PGP.
function detect(parsed) {
const type = String(headerValue(parsed, 'content-type').value).toLowerCase();
const protocol = String(headerValue(parsed, 'content-type').params?.protocol || '').toLowerCase();
if (type === 'multipart/encrypted' && protocol === 'application/pgp-encrypted') return 'encrypted-mime';
if (type === 'multipart/signed' && protocol === 'application/pgp-signature') return 'signed-mime';
const text = String(parsed.text || '');
if (ARMORED_MESSAGE.test(text)) return 'encrypted-inline';
if (CLEARTEXT_SIGNED.test(text)) return 'signed-inline';
return null;
}
function encryptedArmor(parsed, kind) {
if (kind === 'encrypted-inline') return ARMORED_MESSAGE.exec(String(parsed.text || ''))[0];
for (const file of parsed.attachments || []) {
const content = file.content.toString('latin1');
const match = ARMORED_MESSAGE.exec(content);
if (match) return match[0];
}
throw new PgpError('CORRUPT', 'The encrypted part of this message is missing or damaged.');
}
function emailsOf(key) {
return key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean);
}
function fingerprintsByKeyId(verification) {
const map = new Map();
for (const item of verification) {
for (const key of item.key.getKeys()) map.set(key.getKeyID().toHex().toUpperCase(), item);
}
return map;
}
// Interprets signature results and flags a sender whose key changed.
async function describeSignatures(signatures, verification, senderEmail) {
const byKeyId = fingerprintsByKeyId(verification);
const sender = String(senderEmail || '').toLowerCase();
const results = [];
for (const signature of signatures) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = byKeyId.get(keyId);
let status;
try {
await signature.verified;
status = 'valid';
} catch (error) {
status = /could not find signing key|no signing key|not found/i.test(String(error?.message)) || !known ? 'unknown-key' : 'invalid';
}
const result = { status, keyId, fingerprint: known?.fingerprint || null, trust: known?.trust || null, email: null, matchesSender: false, keyChanged: false };
if (known) {
result.email = known.emails[0] || null;
result.matchesSender = Boolean(sender) && known.emails.includes(sender);
}
if (sender && status === 'valid' && known && !known.emails.includes(sender)) result.mismatch = true;
if (sender && status !== 'unknown-key') {
const others = verification.filter(item => !item.own && item.emails.includes(sender) && item.fingerprint !== known?.fingerprint);
if (others.length && !result.matchesSender) result.keyChanged = true;
}
if (sender && status === 'unknown-key' && verification.some(item => !item.own && item.emails.includes(sender))) result.keyChanged = true;
results.push(result);
}
return results;
}
function chunkBase64(buffer) {
return buffer.toString('base64').replace(/(.{76})/g, '$1\r\n').replace(/\r\n$/, '');
}
function encodeHeader(value) {
const clean = String(value).replace(/[\r\n]+/g, ' ').trim();
if (/^[\x20-\x7e]*$/.test(clean) && clean.length <= 900) return clean;
const chars = Array.from(clean);
const words = [];
for (let index = 0; index < chars.length; index += 24) {
words.push(`=?UTF-8?B?${Buffer.from(chars.slice(index, index + 24).join(''), 'utf8').toString('base64')}?=`);
}
return words.join('\r\n ');
}
function formatAddress(entry) {
const address = String(entry.address || '').trim();
if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+$/.test(address)) throw new Error(`"${address || entry.name}" is not a valid email address.`);
const name = String(entry.name || '').replace(/[\r\n"\\]+/g, ' ').trim();
return name ? `${encodeHeader(`"${name}"`)} <${address}>` : address;
}
function parseAddresses(value) {
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
}
async function innerEntity(text, attachments) {
if (attachments.length) {
return new Promise((resolve, reject) => {
new MailComposer({
text: String(text || ''),
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
}).compile().build((error, message) => error
? reject(error)
: resolve(Buffer.from(message.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1')));
});
}
const body = Buffer.from(String(text || ''), 'utf8');
return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1');
}
function boundary() {
return `=_ep-${randomBytes(12).toString('hex')}`;
}
function createPgpMail({ keyStore, cache }) {
async function findDecryptionKey(message) {
const wanted = new Set(message.getEncryptionKeyIDs().map(id => id.toHex().toUpperCase()));
const entries = await keyStore.privateEntries();
const candidates = [];
for (const entry of entries) {
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
if (publicKey.getKeys().some(key => wanted.has(key.getKeyID().toHex().toUpperCase()))) candidates.push(entry);
}
if (!candidates.length) throw new PgpError('NO_KEY', 'None of your keys can decrypt this message.');
return candidates;
}
async function unlockAny(candidates, passphrase) {
let lastError = null;
for (const candidate of candidates) {
const secret = passphrase || cache.get(candidate.fingerprint);
if (!secret) continue;
try {
const key = await keyStore.unlockKey(candidate.fingerprint, secret);
await cache.remember(candidate.fingerprint, secret);
return key;
} catch (error) {
cache.clear(candidate.fingerprint);
lastError = error;
}
}
if (lastError) throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: candidates[0].fingerprint });
throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to read this message.', {
fingerprint: candidates[0].fingerprint, email: candidates[0].email
});
}
return {
detect,
async decrypt(parsed, { passphrase = null } = {}) {
const kind = detect(parsed);
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') throw new PgpError('NOT_ENCRYPTED', 'This message is not encrypted.');
const armored = encryptedArmor(parsed, kind);
if (armored.length > MAX_ENCRYPTED_BYTES) throw new PgpError('TOO_LARGE', 'This encrypted message is too large to open.');
let message;
try {
message = await openpgp.readMessage({ armoredMessage: armored });
} catch {
throw new PgpError('CORRUPT', 'The encrypted part of this message is damaged.');
}
const decryptionKey = await unlockAny(await findDecryptionKey(message), passphrase);
const verification = await keyStore.verificationKeys();
let result;
try {
result = await openpgp.decrypt({
message,
decryptionKeys: decryptionKey,
verificationKeys: verification.map(item => item.key),
format: 'binary'
});
} catch {
throw new PgpError('CORRUPT', 'The message could not be decrypted. It may be damaged or altered.');
}
const data = Buffer.from(result.data);
const sender = parsed.from?.value?.[0]?.address || '';
const signatures = await describeSignatures(result.signatures, verification, sender);
const inner = kind === 'encrypted-mime' ? await simpleParser(data) : await simpleParser(Buffer.concat([
Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'), data
]));
return { parsed: inner, signatures, attachedKeys: await this.attachedKeys(inner) };
},
// Public keys attached to a message (offered to the user, never added silently).
async attachedKeys(parsed) {
const keys = [];
for (const file of parsed.attachments || []) {
const type = String(file.contentType || '').toLowerCase();
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
const armored = file.content.toString('utf8');
if (!/BEGIN PGP PUBLIC KEY BLOCK/.test(armored) || armored.length > 200000) continue;
try {
const key = await openpgp.readKey({ armoredKey: armored });
keys.push({ armoredKey: armored, fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
} catch { /* ignore unreadable attachments */ }
}
return keys.slice(0, 5);
},
// Verifies PGP/MIME (multipart/signed) and cleartext signatures on unencrypted mail.
async verifySigned(parsed, source) {
const kind = detect(parsed);
const verification = await keyStore.verificationKeys();
const sender = parsed.from?.value?.[0]?.address || '';
try {
if (kind === 'signed-inline') {
const message = await openpgp.readCleartextMessage({ cleartextMessage: CLEARTEXT_SIGNED.exec(String(parsed.text))[0] });
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
return describeSignatures(result.signatures, verification, sender);
}
if (kind !== 'signed-mime') return null;
const parts = splitSigned(source, headerValue(parsed, 'content-type').params?.boundary);
if (!parts) return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
const signature = await openpgp.readSignature({ armoredSignature: parts.signature });
const result = await openpgp.verify({
message: await openpgp.createMessage({ binary: parts.signed }),
signature,
verificationKeys: verification.map(item => item.key)
});
return describeSignatures(result.signatures, verification, sender);
} catch {
return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
}
},
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) {
const toList = parseAddresses(to);
const ccList = parseAddresses(cc);
if (!toList.length) throw new Error('Add at least one recipient.');
const everyone = [...toList, ...ccList];
everyone.forEach(entry => formatAddress(entry));
let signingKey = null;
let signerEntry = null;
if (sign) {
const entries = await keyStore.privateEntries();
signerEntry = entries.find(entry => entry.fingerprint === signerFingerprint)
|| entries.find(entry => entry.email.toLowerCase() === String(from.address).toLowerCase());
if (!signerEntry) throw new PgpError('NO_SIGNING_KEY', 'Create or import an encryption key for this address first.');
const secret = passphrase || cache.get(signerEntry.fingerprint);
if (!secret) throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to sign this message.', { fingerprint: signerEntry.fingerprint, email: signerEntry.email });
try {
signingKey = await keyStore.unlockKey(signerEntry.fingerprint, secret);
} catch {
cache.clear(signerEntry.fingerprint);
throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: signerEntry.fingerprint });
}
await cache.remember(signerEntry.fingerprint, secret);
}
const headers = [
`From: ${formatAddress(from)}`,
`To: ${toList.map(formatAddress).join(', ')}`,
...(ccList.length ? [`Cc: ${ccList.map(formatAddress).join(', ')}`] : []),
`Subject: ${encodeHeader(subject || '(no subject)')}`,
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
'MIME-Version: 1.0'
];
const inner = await innerEntity(text, attachments);
const mark = boundary();
let body;
let contentType;
if (encrypt) {
const { keys, missing } = await keyStore.findRecipientKeys(everyone.map(entry => entry.address));
if (missing.length) throw new PgpError('NO_RECIPIENT_KEY', `No public key for ${missing.join(', ')}.`, { missing });
const own = signerEntry ? [await openpgp.readKey({ armoredKey: signerEntry.publicKey })] : [];
const ownKeys = own.length ? own : (await keyStore.findRecipientKeys([from.address])).keys.map(item => item.key);
const armored = await openpgp.encrypt({
message: await openpgp.createMessage({ binary: inner }),
encryptionKeys: [...keys.map(item => item.key), ...ownKeys],
signingKeys: signingKey || undefined,
format: 'armored'
});
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${mark}"`;
body = [
`--${mark}`, 'Content-Type: application/pgp-encrypted', 'Content-Description: PGP/MIME version identification', '', 'Version: 1', '',
`--${mark}`, 'Content-Type: application/octet-stream; name="encrypted.asc"', 'Content-Description: OpenPGP encrypted message',
'Content-Disposition: inline; filename="encrypted.asc"', '', String(armored).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
].join('\r\n');
} else if (sign) {
const signedBytes = inner.subarray(0, inner.length - 2);
const detached = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signingKey, detached: true, format: 'armored' });
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${mark}"`;
const signedPart = signedBytes.toString('latin1');
body = [
`--${mark}`, signedPart, `--${mark}`, 'Content-Type: application/pgp-signature; name="signature.asc"',
'Content-Description: OpenPGP digital signature', 'Content-Disposition: attachment; filename="signature.asc"', '',
String(detached).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
].join('\r\n');
} else {
throw new Error('Choose encryption or signing for this message.');
}
const raw = Buffer.from(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`, 'latin1');
return { raw, envelope: { from: from.address, to: everyone.map(entry => entry.address) }, signerFingerprint: signerEntry?.fingerprint || null };
},
async recipientStatus(addresses, { sign = false, from = '' } = {}) {
const list = addresses.flatMap(value => parseAddresses(value)).map(entry => entry.address).filter(Boolean);
const { keys, missing } = await keyStore.findRecipientKeys(list);
let signer = null;
if (sign) {
const entries = await keyStore.privateEntries();
const entry = entries.find(item => item.email.toLowerCase() === String(from).toLowerCase()) || null;
if (entry) signer = { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: cache.has(entry.fingerprint) };
}
return {
recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
missing,
signer
};
}
};
}
// Extracts the signed part and detached signature from a multipart/signed source.
function splitSigned(source, boundaryValue) {
if (!boundaryValue) return null;
const text = Buffer.from(source).toString('latin1');
const escaped = String(boundaryValue).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 armored = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!armored) return null;
return { signed: Buffer.from(signed, 'latin1'), signature: armored };
}
module.exports = { createPgpMail, createPassphraseCache, detect, PgpError, splitSigned };
const openpgp = require('openpgp');
const { simpleParser } = require('mailparser');
const addressParser = require('nodemailer/lib/addressparser');
const MailComposer = require('nodemailer/lib/mail-composer');
const { randomBytes } = require('node:crypto');
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
const CLEARTEXT_SIGNED = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/;
const MAX_ENCRYPTED_BYTES = 60 * 1048576;
class PgpError extends Error {
constructor(code, message, details = {}) {
super(message);
this.code = code;
this.details = details;
}
}
// Remembers unlocked-key passphrases in memory only, for a limited time.
function createPassphraseCache(getMinutes, now = () => Date.now()) {
const entries = new Map();
return {
async remember(fingerprint, passphrase) {
const minutes = await getMinutes();
if (!minutes) { entries.delete(fingerprint); return; }
entries.set(fingerprint, { passphrase, expires: now() + minutes * 60000 });
},
get(fingerprint) {
const entry = entries.get(fingerprint);
if (!entry) return null;
if (entry.expires <= now()) { entries.delete(fingerprint); return null; }
return entry.passphrase;
},
has(fingerprint) { return this.get(fingerprint) !== null; },
clear(fingerprint) { if (fingerprint) entries.delete(fingerprint); else entries.clear(); }
};
}
function headerValue(parsed, name) {
const value = parsed.headers?.get(name);
return value && typeof value === 'object' ? value : { value: String(value || ''), params: {} };
}
// Classifies a parsed message: encrypted/signed PGP/MIME or inline PGP.
function detect(parsed) {
const type = String(headerValue(parsed, 'content-type').value).toLowerCase();
const protocol = String(headerValue(parsed, 'content-type').params?.protocol || '').toLowerCase();
if (type === 'multipart/encrypted' && protocol === 'application/pgp-encrypted') return 'encrypted-mime';
if (type === 'multipart/signed' && protocol === 'application/pgp-signature') return 'signed-mime';
const text = String(parsed.text || '');
if (ARMORED_MESSAGE.test(text)) return 'encrypted-inline';
if (CLEARTEXT_SIGNED.test(text)) return 'signed-inline';
return null;
}
function encryptedArmor(parsed, kind) {
if (kind === 'encrypted-inline') return ARMORED_MESSAGE.exec(String(parsed.text || ''))[0];
for (const file of parsed.attachments || []) {
const content = file.content.toString('latin1');
const match = ARMORED_MESSAGE.exec(content);
if (match) return match[0];
}
throw new PgpError('CORRUPT', 'The encrypted part of this message is missing or damaged.');
}
function emailsOf(key) {
return key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean);
}
function fingerprintsByKeyId(verification) {
const map = new Map();
for (const item of verification) {
for (const key of item.key.getKeys()) map.set(key.getKeyID().toHex().toUpperCase(), item);
}
return map;
}
// Interprets signature results and flags a sender whose key changed.
async function describeSignatures(signatures, verification, senderEmail) {
const byKeyId = fingerprintsByKeyId(verification);
const sender = String(senderEmail || '').toLowerCase();
const results = [];
for (const signature of signatures) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = byKeyId.get(keyId);
let status;
try {
await signature.verified;
status = 'valid';
} catch (error) {
status = /could not find signing key|no signing key|not found/i.test(String(error?.message)) || !known ? 'unknown-key' : 'invalid';
}
const result = { status, keyId, fingerprint: known?.fingerprint || null, trust: known?.trust || null, email: null, matchesSender: false, keyChanged: false };
if (known) {
result.email = known.emails[0] || null;
result.matchesSender = Boolean(sender) && known.emails.includes(sender);
}
if (sender && status === 'valid' && known && !known.emails.includes(sender)) result.mismatch = true;
if (sender && status !== 'unknown-key') {
const others = verification.filter(item => !item.own && item.emails.includes(sender) && item.fingerprint !== known?.fingerprint);
if (others.length && !result.matchesSender) result.keyChanged = true;
}
if (sender && status === 'unknown-key' && verification.some(item => !item.own && item.emails.includes(sender))) result.keyChanged = true;
results.push(result);
}
return results;
}
function chunkBase64(buffer) {
return buffer.toString('base64').replace(/(.{76})/g, '$1\r\n').replace(/\r\n$/, '');
}
function encodeHeader(value) {
const clean = String(value).replace(/[\r\n]+/g, ' ').trim();
if (/^[\x20-\x7e]*$/.test(clean) && clean.length <= 900) return clean;
const chars = Array.from(clean);
const words = [];
for (let index = 0; index < chars.length; index += 24) {
words.push(`=?UTF-8?B?${Buffer.from(chars.slice(index, index + 24).join(''), 'utf8').toString('base64')}?=`);
}
return words.join('\r\n ');
}
function formatAddress(entry) {
const address = String(entry.address || '').trim();
if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+$/.test(address)) throw new Error(`"${address || entry.name}" is not a valid email address.`);
const name = String(entry.name || '').replace(/[\r\n"\\]+/g, ' ').trim();
return name ? `${encodeHeader(`"${name}"`)} <${address}>` : address;
}
function parseAddresses(value) {
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
}
async function innerEntity(text, attachments) {
if (attachments.length) {
return new Promise((resolve, reject) => {
new MailComposer({
text: String(text || ''),
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
}).compile().build((error, message) => error
? reject(error)
: resolve(Buffer.from(message.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1')));
});
}
const body = Buffer.from(String(text || ''), 'utf8');
return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1');
}
function boundary() {
return `=_ep-${randomBytes(12).toString('hex')}`;
}
function createPgpMail({ keyStore, cache }) {
async function findDecryptionKey(message) {
const wanted = new Set(message.getEncryptionKeyIDs().map(id => id.toHex().toUpperCase()));
const entries = await keyStore.privateEntries();
const candidates = [];
for (const entry of entries) {
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
if (publicKey.getKeys().some(key => wanted.has(key.getKeyID().toHex().toUpperCase()))) candidates.push(entry);
}
if (!candidates.length) throw new PgpError('NO_KEY', 'None of your keys can decrypt this message.');
return candidates;
}
async function unlockAny(candidates, passphrase) {
let lastError = null;
for (const candidate of candidates) {
const secret = passphrase || cache.get(candidate.fingerprint);
if (!secret) continue;
try {
const key = await keyStore.unlockKey(candidate.fingerprint, secret);
await cache.remember(candidate.fingerprint, secret);
return key;
} catch (error) {
cache.clear(candidate.fingerprint);
lastError = error;
}
}
if (lastError) throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: candidates[0].fingerprint });
throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to read this message.', {
fingerprint: candidates[0].fingerprint, email: candidates[0].email
});
}
return {
detect,
async decrypt(parsed, { passphrase = null } = {}) {
const kind = detect(parsed);
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') throw new PgpError('NOT_ENCRYPTED', 'This message is not encrypted.');
const armored = encryptedArmor(parsed, kind);
if (armored.length > MAX_ENCRYPTED_BYTES) throw new PgpError('TOO_LARGE', 'This encrypted message is too large to open.');
let message;
try {
message = await openpgp.readMessage({ armoredMessage: armored });
} catch {
throw new PgpError('CORRUPT', 'The encrypted part of this message is damaged.');
}
const decryptionKey = await unlockAny(await findDecryptionKey(message), passphrase);
const verification = await keyStore.verificationKeys();
let result;
try {
result = await openpgp.decrypt({
message,
decryptionKeys: decryptionKey,
verificationKeys: verification.map(item => item.key),
format: 'binary'
});
} catch {
throw new PgpError('CORRUPT', 'The message could not be decrypted. It may be damaged or altered.');
}
const data = Buffer.from(result.data);
const sender = parsed.from?.value?.[0]?.address || '';
const signatures = await describeSignatures(result.signatures, verification, sender);
const inner = kind === 'encrypted-mime' ? await simpleParser(data) : await simpleParser(Buffer.concat([
Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'), data
]));
return { parsed: inner, signatures, attachedKeys: await this.attachedKeys(inner) };
},
// Public keys attached to a message (offered to the user, never added silently).
async attachedKeys(parsed) {
const keys = [];
for (const file of parsed.attachments || []) {
const type = String(file.contentType || '').toLowerCase();
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
const armored = file.content.toString('utf8');
if (!/BEGIN PGP PUBLIC KEY BLOCK/.test(armored) || armored.length > 200000) continue;
try {
const key = await openpgp.readKey({ armoredKey: armored });
keys.push({ armoredKey: armored, fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
} catch { /* ignore unreadable attachments */ }
}
return keys.slice(0, 5);
},
// Verifies PGP/MIME (multipart/signed) and cleartext signatures on unencrypted mail.
async verifySigned(parsed, source) {
const kind = detect(parsed);
const verification = await keyStore.verificationKeys();
const sender = parsed.from?.value?.[0]?.address || '';
try {
if (kind === 'signed-inline') {
const message = await openpgp.readCleartextMessage({ cleartextMessage: CLEARTEXT_SIGNED.exec(String(parsed.text))[0] });
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
return describeSignatures(result.signatures, verification, sender);
}
if (kind !== 'signed-mime') return null;
const parts = splitSigned(source, headerValue(parsed, 'content-type').params?.boundary);
if (!parts) return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
const signature = await openpgp.readSignature({ armoredSignature: parts.signature });
const result = await openpgp.verify({
message: await openpgp.createMessage({ binary: parts.signed }),
signature,
verificationKeys: verification.map(item => item.key)
});
return describeSignatures(result.signatures, verification, sender);
} catch {
return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
}
},
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) {
const toList = parseAddresses(to);
const ccList = parseAddresses(cc);
if (!toList.length) throw new Error('Add at least one recipient.');
const everyone = [...toList, ...ccList];
everyone.forEach(entry => formatAddress(entry));
let signingKey = null;
let signerEntry = null;
if (sign) {
const entries = await keyStore.privateEntries();
signerEntry = entries.find(entry => entry.fingerprint === signerFingerprint)
|| entries.find(entry => entry.email.toLowerCase() === String(from.address).toLowerCase());
if (!signerEntry) throw new PgpError('NO_SIGNING_KEY', 'Create or import an encryption key for this address first.');
const secret = passphrase || cache.get(signerEntry.fingerprint);
if (!secret) throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to sign this message.', { fingerprint: signerEntry.fingerprint, email: signerEntry.email });
try {
signingKey = await keyStore.unlockKey(signerEntry.fingerprint, secret);
} catch {
cache.clear(signerEntry.fingerprint);
throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: signerEntry.fingerprint });
}
await cache.remember(signerEntry.fingerprint, secret);
}
const headers = [
`From: ${formatAddress(from)}`,
`To: ${toList.map(formatAddress).join(', ')}`,
...(ccList.length ? [`Cc: ${ccList.map(formatAddress).join(', ')}`] : []),
`Subject: ${encodeHeader(subject || '(no subject)')}`,
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
'MIME-Version: 1.0'
];
const inner = await innerEntity(text, attachments);
const mark = boundary();
let body;
let contentType;
if (encrypt) {
const { keys, missing } = await keyStore.findRecipientKeys(everyone.map(entry => entry.address));
if (missing.length) throw new PgpError('NO_RECIPIENT_KEY', `No public key for ${missing.join(', ')}.`, { missing });
const own = signerEntry ? [await openpgp.readKey({ armoredKey: signerEntry.publicKey })] : [];
const ownKeys = own.length ? own : (await keyStore.findRecipientKeys([from.address])).keys.map(item => item.key);
const armored = await openpgp.encrypt({
message: await openpgp.createMessage({ binary: inner }),
encryptionKeys: [...keys.map(item => item.key), ...ownKeys],
signingKeys: signingKey || undefined,
format: 'armored'
});
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${mark}"`;
body = [
`--${mark}`, 'Content-Type: application/pgp-encrypted', 'Content-Description: PGP/MIME version identification', '', 'Version: 1', '',
`--${mark}`, 'Content-Type: application/octet-stream; name="encrypted.asc"', 'Content-Description: OpenPGP encrypted message',
'Content-Disposition: inline; filename="encrypted.asc"', '', String(armored).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
].join('\r\n');
} else if (sign) {
const signedBytes = inner.subarray(0, inner.length - 2);
const detached = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signingKey, detached: true, format: 'armored' });
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${mark}"`;
const signedPart = signedBytes.toString('latin1');
body = [
`--${mark}`, signedPart, `--${mark}`, 'Content-Type: application/pgp-signature; name="signature.asc"',
'Content-Description: OpenPGP digital signature', 'Content-Disposition: attachment; filename="signature.asc"', '',
String(detached).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
].join('\r\n');
} else {
throw new Error('Choose encryption or signing for this message.');
}
const raw = Buffer.from(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`, 'latin1');
return { raw, envelope: { from: from.address, to: everyone.map(entry => entry.address) }, signerFingerprint: signerEntry?.fingerprint || null };
},
async recipientStatus(addresses, { sign = false, from = '' } = {}) {
const list = addresses.flatMap(value => parseAddresses(value)).map(entry => entry.address).filter(Boolean);
const { keys, missing } = await keyStore.findRecipientKeys(list);
let signer = null;
if (sign) {
const entries = await keyStore.privateEntries();
const entry = entries.find(item => item.email.toLowerCase() === String(from).toLowerCase()) || null;
if (entry) signer = { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: cache.has(entry.fingerprint) };
}
return {
recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
missing,
signer
};
}
};
}
// Extracts the signed part and detached signature from a multipart/signed source.
function splitSigned(source, boundaryValue) {
if (!boundaryValue) return null;
const text = Buffer.from(source).toString('latin1');
const escaped = String(boundaryValue).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 armored = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!armored) return null;
return { signed: Buffer.from(signed, 'latin1'), signature: armored };
}
module.exports = { createPgpMail, createPassphraseCache, detect, PgpError, splitSigned };
+59 -59
View File
@@ -1,62 +1,62 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('daybreakMail', {
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('daybreakMail', {
getAppVersion: () => ipcRenderer.invoke('app:get-version'),
getAccount: () => ipcRenderer.invoke('mail:get-account'),
listAccounts: () => ipcRenderer.invoke('mail:list-accounts'),
listOAuthProviders: () => ipcRenderer.invoke('mail:list-oauth-providers'),
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
connect: details => ipcRenderer.invoke('mail:connect', details),
updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details),
syncFolder: (folder, offset, filters) => ipcRenderer.invoke('mail:sync-folder', folder, offset, filters),
listFolders: () => ipcRenderer.invoke('mail:list-folders'),
createFolder: name => ipcRenderer.invoke('mail:create-folder', { name }),
listDrafts: () => ipcRenderer.invoke('mail:list-drafts'),
saveDraft: draft => ipcRenderer.invoke('mail:save-draft', draft),
deleteDraft: id => ipcRenderer.invoke('mail:delete-draft', id),
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
send: message => ipcRenderer.invoke('mail:send', message),
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
pgp: {
list: () => ipcRenderer.invoke('pgp:list'),
generate: details => ipcRenderer.invoke('pgp:generate', details),
importKey: details => ipcRenderer.invoke('pgp:import', details),
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
changePassphrase: details => ipcRenderer.invoke('pgp:change-passphrase', details),
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
checkSend: details => ipcRenderer.invoke('pgp:check-send', details),
contacts: () => ipcRenderer.invoke('pgp:contacts'),
addContact: details => ipcRenderer.invoke('pgp:add-contact', details),
setTrust: (fingerprint, trust) => ipcRenderer.invoke('pgp:set-trust', fingerprint, trust),
removeContact: fingerprint => ipcRenderer.invoke('pgp:remove-contact', fingerprint),
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases'),
keyServers: () => ipcRenderer.invoke('pgp:key-servers'),
setKeyServerEnabled: (serverId, enabled) => ipcRenderer.invoke('pgp:set-key-server-enabled', { serverId, enabled }),
addKeyServer: server => ipcRenderer.invoke('pgp:add-key-server', server),
removeKeyServer: id => ipcRenderer.invoke('pgp:remove-key-server', id),
findKey: details => ipcRenderer.invoke('pgp:find-key', details),
publishKey: details => ipcRenderer.invoke('pgp:publish-key', details)
},
davList: () => ipcRenderer.invoke('dav:list'),
davConnect: config => ipcRenderer.invoke('dav:connect', config),
davActivate: (type, id) => ipcRenderer.invoke('dav:activate', { type, id }),
davRemove: (type, id) => ipcRenderer.invoke('dav:remove', { type, id }),
davSync: type => ipcRenderer.invoke('dav:sync', type),
davSaveEvent: event => ipcRenderer.invoke('dav:save-event', event),
davDeleteEvent: remote => ipcRenderer.invoke('dav:delete-event', remote),
davSaveContact: contact => ipcRenderer.invoke('dav:save-contact', contact),
davDeleteContact: remote => ipcRenderer.invoke('dav:delete-contact', remote)
});
selectAccount: id => ipcRenderer.invoke('mail:select-account', id),
removeAccount: id => ipcRenderer.invoke('mail:remove-account', id),
connect: details => ipcRenderer.invoke('mail:connect', details),
updateAccount: (id, details) => ipcRenderer.invoke('mail:update-account', id, details),
syncFolder: (folder, offset, filters) => ipcRenderer.invoke('mail:sync-folder', folder, offset, filters),
listFolders: () => ipcRenderer.invoke('mail:list-folders'),
createFolder: name => ipcRenderer.invoke('mail:create-folder', { name }),
listDrafts: () => ipcRenderer.invoke('mail:list-drafts'),
saveDraft: draft => ipcRenderer.invoke('mail:save-draft', draft),
deleteDraft: id => ipcRenderer.invoke('mail:delete-draft', id),
syncInbox: () => ipcRenderer.invoke('mail:sync-folder', 'INBOX'),
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', details),
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
send: message => ipcRenderer.invoke('mail:send', message),
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
pgp: {
list: () => ipcRenderer.invoke('pgp:list'),
generate: details => ipcRenderer.invoke('pgp:generate', details),
importKey: details => ipcRenderer.invoke('pgp:import', details),
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
changePassphrase: details => ipcRenderer.invoke('pgp:change-passphrase', details),
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
checkSend: details => ipcRenderer.invoke('pgp:check-send', details),
contacts: () => ipcRenderer.invoke('pgp:contacts'),
addContact: details => ipcRenderer.invoke('pgp:add-contact', details),
setTrust: (fingerprint, trust) => ipcRenderer.invoke('pgp:set-trust', fingerprint, trust),
removeContact: fingerprint => ipcRenderer.invoke('pgp:remove-contact', fingerprint),
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases'),
keyServers: () => ipcRenderer.invoke('pgp:key-servers'),
setKeyServerEnabled: (serverId, enabled) => ipcRenderer.invoke('pgp:set-key-server-enabled', { serverId, enabled }),
addKeyServer: server => ipcRenderer.invoke('pgp:add-key-server', server),
removeKeyServer: id => ipcRenderer.invoke('pgp:remove-key-server', id),
findKey: details => ipcRenderer.invoke('pgp:find-key', details),
publishKey: details => ipcRenderer.invoke('pgp:publish-key', details)
},
davList: () => ipcRenderer.invoke('dav:list'),
davConnect: config => ipcRenderer.invoke('dav:connect', config),
davActivate: (type, id) => ipcRenderer.invoke('dav:activate', { type, id }),
davRemove: (type, id) => ipcRenderer.invoke('dav:remove', { type, id }),
davSync: type => ipcRenderer.invoke('dav:sync', type),
davSaveEvent: event => ipcRenderer.invoke('dav:save-event', event),
davDeleteEvent: remote => ipcRenderer.invoke('dav:delete-event', remote),
davSaveContact: contact => ipcRenderer.invoke('dav:save-contact', contact),
davDeleteContact: remote => ipcRenderer.invoke('dav:delete-contact', remote)
});
+133
View File
@@ -0,0 +1,133 @@
# Electron Startup Optimization Results
## Summary of Changes Applied
### Performance Optimizations
| Change | File(s) | Impact |
|--------|---------|--------|
| **V8 bytecode caching** | `desktop/main.cjs` (line 1) | ~30-50% faster subsequent starts |
| **Lazy-load `openpgp`** | `desktop/main.cjs`, `desktop/ipc/pgp.cjs` | ~500-1000ms saved |
| **Lazy-load `imapflow`** | `desktop/main.cjs`, `desktop/mail/connection-factory.cjs` | ~300-500ms saved |
| **Lazy-load `nodemailer`** | `desktop/main.cjs`, `desktop/mail/connection-factory.cjs` | ~150-250ms saved |
| **Lazy-load `mailparser`** | `desktop/main.cjs`, `desktop/ipc/mail.cjs`, `desktop/ipc/pgp.cjs` | ~200-400ms saved |
| **Lazy-load `tsdav` + `ical.js`** | `desktop/main.cjs`, `desktop/ipc/dav.cjs` | ~200-300ms saved |
| **Deferred service init** | Already in place (services init after `ready-to-show`) | Window shows in ~476ms |
### Key Results
| Metric | Before | After |
|--------|--------|-------|
| **Time to window visible** | 15-20 seconds | **~476ms** |
| **All requires complete** | ~2000ms+ | **~108ms** |
| **All tests pass** | 142/142 | 142/142 |
### Files Modified
1. `desktop/main.cjs` - Added v8-compile-cache, lazy getters for all heavy modules
2. `desktop/mail/connection-factory.cjs` - Lazy-load ImapFlow and nodemailer
3. `desktop/ipc/pgp.cjs` - Use lazy `getOpenPGP` and `getMailparser`
4. `desktop/ipc/mail.cjs` - Use lazy `getMailparser`
5. `desktop/ipc/dav.cjs` - Use lazy `getICAL`
6. `package.json` - Added `v8-compile-cache` devDependency
### Documents Saved to Project
- `cpp-translation-assessment.md` - C++ translation effort analysis
- `electron-startup-optimization.md` - Detailed optimization guide
- `electron-startup-optimization-results.md` - This file
### Startup Trace (with EP_MAIL_STARTUP_TRACE=1)
**Development (`npm start`):**
```
[ep-mail startup +0.0ms] main process entered
[ep-mail startup +108.1ms] all requires complete
[ep-mail startup +189.9ms] main services and IPC handlers initialized
[ep-mail startup +230.5ms] Electron app.whenReady
[ep-mail startup +233.6ms] creating BrowserWindow
[ep-mail startup +360.9ms] app:get-version IPC completed in 0.3ms
[ep-mail startup +379.4ms] renderer DOM ready
[ep-mail startup +405.8ms] mail:get-account IPC completed in 44.7ms
[ep-mail startup +473.2ms] renderer load complete
[ep-mail startup +476.8ms] BrowserWindow ready-to-show <-- WINDOW VISIBLE
[ep-mail startup +502.1ms] post-first-frame work started; background sync scheduled
[ep-mail startup +1198.7ms] mail:list-folders IPC completed in 724.7ms
[ep-mail startup +1549.0ms] mail:sync-folder IPC completed in 1074.8ms
...
```
**Built App (`release/win-unpacked/ep-mail.exe`):**
```
[ep-mail startup +0.0ms] main process entered
[ep-mail startup +106.0ms] all requires complete
[ep-mail startup +195.5ms] main services and IPC handlers initialized
[ep-mail startup +248.4ms] Electron app.whenReady
[ep-mail startup +262.3ms] creating BrowserWindow
[ep-mail startup +550.5ms] BrowserWindow ready-to-show <-- WINDOW VISIBLE
[ep-mail startup +849.3ms] post-first-frame work started; background sync scheduled
[ep-mail startup +852.3ms] app:get-version IPC completed in 0.4ms
[ep-mail startup +853.9ms] renderer DOM ready
[ep-mail startup +854.4ms] renderer load complete
```
**Built App - Second Run (`release/win-unpacked/ep-mail.exe`):**
```
[ep-mail startup +0.0ms] main process entered
[ep-mail startup +77.1ms] all requires complete
[ep-mail startup +119.0ms] main services and IPC handlers initialized
[ep-mail startup +163.4ms] Electron app.whenReady
[ep-mail startup +177.7ms] creating BrowserWindow
[ep-mail startup +422.6ms] BrowserWindow ready-to-show <-- WINDOW VISIBLE
[ep-mail startup +596.5ms] post-first-frame work started; background sync scheduled
[ep-mail startup +599.6ms] app:get-version IPC completed in 0.2ms
[ep-mail startup +601.0ms] renderer DOM ready
[ep-mail startup +601.4ms] renderer load complete
[ep-mail startup +629.5ms] mail:get-account IPC completed in 29.6ms
```
### Verification
- All 142 tests pass
- Window visible in <500ms (vs 15-20s before)
- Background sync continues after window shows
- Full functionality preserved (IMAP, SMTP, PGP, DAV, OAuth2)
- **Build verified**: `v8-compile-cache` moved to `dependencies` in `package.json` so it's included in the packaged app
---
## Portable vs Installer Performance
### The Problem
The portable `.exe` (`release/ep-mail 0.5.1.exe`) takes **12-15 seconds** to show the window on **every launch**.
### Root Cause
electron-builder's `portable` target creates a **self-extracting 7z archive**. On every launch:
1. The `.exe` extracts the entire app to a temporary folder (`%TEMP%/ep-mail-<random>/`)
2. Then runs the extracted `ep-mail.exe`
3. This extraction happens **every time**, not just first run
### Verified Performance by Build Type
| Build Type | Time to Window | Notes |
|------------|----------------|-------|
| `npm start` (dev) | ~476ms | Development mode |
| **NSIS Installer** (recommended) | **~422ms** | Installs to Program Files, runs natively |
| **win-unpacked** (dev/testing) | **~422ms** | Direct execution, no extraction |
| **Portable .exe** | **12-15s** | Self-extracts to `%TEMP%` on **every** launch |
### Recommendation
**For distribution, use the NSIS installer** (`npm run dist:win:installer`):
- Installs permanently to Program Files
- Runs at native speed (~422ms)
- Creates Start Menu shortcuts
- Supports auto-updates
The portable format is designed for USB stick usage where installation isn't possible. For daily use, the installer is the correct choice.
---
*Generated: 2026-10-18*
+202
View File
@@ -0,0 +1,202 @@
# Electron Startup Optimization: ep-mail-client
## Current Problem
- **15-20 seconds** to see window
- Root cause: **39 modules loaded synchronously** before window creation
- All services constructed at module load time (lines 121-220, 425-467 in `main.cjs`)
---
## Quick Wins (Priority Order)
### 1. Enable V8 Bytecode Caching — **5 min, 30-50% gain**
```bash
npm install v8-compile-cache-electron --save-dev
```
Add to **top of `desktop/main.cjs`** (before any other require):
```javascript
require('v8-compile-cache-electron');
```
Caches compiled bytecode to disk — subsequent starts skip parsing/compilation.
---
### 2. Lazy-Load Heavy Modules — **30 min each, 500-1000ms gain each**
| Module | Est. Load Time | Where to Lazy-Load |
|--------|---------------|-------------------|
| `openpgp` | ~500-1000ms | Inside `registerPgpIpcHandlers` |
| `imapflow` | ~300-500ms | Inside `createMailConnections` |
| `mailparser` | ~200-400ms | Inside `toUiMessage` / `createMailReader` |
| `tsdav` + `ical.js` | ~200-300ms | Inside DAV handlers |
| `nodemailer` | ~150-250ms | Inside `createMailConnections` |
**Pattern:**
```javascript
// BEFORE (top-level)
const openpgp = require('openpgp');
// AFTER (lazy)
let openpgpPromise = null;
function getOpenPGP() {
if (!openpgpPromise) openpgpPromise = import('openpgp');
return openpgpPromise;
}
// Then: const openpgp = await getOpenPGP();
```
---
### 3. Defer Service Initialization Until After First Paint — **1 hr, shows window in 1-2s**
**Current:** All services created at module load (before `app.whenReady()`)
**Fix:** Move service creation into `ready-to-show` handler:
```javascript
app.whenReady().then(() => {
traceStartup('Electron app.whenReady');
app.setAppUserModelId(windowsAppUserModelId);
if (process.platform === 'win32') {
windowsAppIcon = nativeImage.createFromPath(path.join(__dirname, '..', 'icon.ico'));
if (windowsAppIcon.isEmpty()) throw new Error('Could not load the Windows application icon.');
}
// 1. Create window FIRST
const mainWindow = createWindow();
// 2. Defer heavy init until window is visible
mainWindow.once('ready-to-show', () => {
traceStartup('BrowserWindow ready-to-show');
mainWindow.show();
// NOW initialize heavy services (async, non-blocking)
setImmediate(async () => {
await initializeHeavyServices(); // move all createXxxService calls here
if (process.platform === 'win32') {
repairWindowsStartMenuShortcut();
createWindowsTray();
}
void checkSnoozeReminders();
setTimeout(() => requestBackgroundSync(), 3000);
traceStartup('post-first-frame work started; background sync scheduled');
});
});
// ... timers, etc.
});
```
---
### 4. Add Startup Profiling — **15 min, identifies real bottlenecks**
Add to top of `main.cjs`:
```javascript
const startupMarks = { mainStart: Date.now() };
function mark(label) {
startupMarks[label] = Date.now();
console.log(`[STARTUP] ${label}: +${startupMarks[label] - startupMarks.mainStart}ms`);
}
mark('beforeRequires');
// ... all your requires ...
mark('afterRequires');
// ... service creation ...
mark('afterServices');
// app.whenReady().then(() => {
mark('appReady');
// createWindow()
mark('windowCreated');
// ready-to-show
mark('readyToShow');
```
Run with:
```bash
EP_MAIL_STARTUP_TRACE=1 npm start
```
---
### 5. Build-Time Optimizations
**In `package.json` build config:**
```json
"build": {
"asar": true,
"asarUnpack": [],
"compression": "maximum"
}
```
---
## Expected Results
| Approach | Startup Time |
|----------|--------------|
| Current | 15-20s |
| + v8-compile-cache only | ~8-12s |
| + Lazy-load heavy deps | ~4-7s |
| + Defer service init (window shows early) | **Window visible in 1-2s**, background init continues |
---
## Portable vs Installer Performance
### The Problem
The portable `.exe` takes **12-15 seconds** to show the window on **every launch**.
### Root Cause
electron-builder's `portable` target creates a **self-extracting 7z archive**. On every launch:
1. The `.exe` extracts the entire app to a temporary folder (`%TEMP%/ep-mail-<random>/`)
2. Then runs the extracted `ep-mail.exe`
3. This extraction happens **every time**, not just first run
### Verified Performance by Build Type
| Build Type | Time to Window | Notes |
|------------|----------------|-------|
| `npm start` (dev) | ~476ms | Development mode |
| **NSIS Installer** (recommended) | **~422ms** | Installs to Program Files, runs natively |
| **win-unpacked** (dev/testing) | **~422ms** | Direct execution, no extraction |
| **Portable .exe** | **12-15s** | Self-extracts to `%TEMP%` on **every** launch |
### Recommendation
**For distribution, use the NSIS installer** (`npm run dist:win:installer`):
- Installs permanently to Program Files
- Runs at native speed (~422ms)
- Creates Start Menu shortcuts
- Supports auto-updates
The portable format is designed for USB stick usage where installation isn't possible. For daily use, the installer is the correct choice.
---
## Implementation Checklist
- [ ] Install `v8-compile-cache-electron`
- [ ] Add require at top of `main.cjs`
- [ ] Lazy-load `openpgp` (biggest single win)
- [ ] Lazy-load `imapflow`, `mailparser`, `nodemailer`
- [ ] Lazy-load `tsdav`, `ical.js`
- [ ] Refactor `main.cjs` to defer service init until `ready-to-show`
- [ ] Add profiling timestamps
- [ ] Measure and verify
---
## Files to Modify
1. `desktop/main.cjs` — Primary target (all changes)
2. `package.json` — Add devDependency, build config
3. `desktop/preload.cjs` — Verify no unnecessary loads (currently clean ✅)
---
*Generated: 2026-10-18*
+10 -10
View File
@@ -1,10 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
<g fill="none" stroke="#eee9de">
<circle cx="32" cy="32" r="27" stroke-width="3"/>
<path d="M32 4v56" stroke-width="4"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
</g>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<rect width="64" height="64" rx="12" fill="#0a0c0b"/>
<g fill="none" stroke="#eee9de">
<circle cx="32" cy="32" r="27" stroke-width="3"/>
<path d="M32 4v56" stroke-width="4"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="3" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="3" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="2" opacity=".75" transform="rotate(45 32 32)"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 552 B

After

Width:  |  Height:  |  Size: 562 B

+73 -73
View File
@@ -1,82 +1,82 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4f5f1">
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
<title>ep-mail</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="branding.css">
</head>
<body>
<div class="app-shell">
<aside class="rail" aria-label="Main navigation">
<div class="brand-mark" title="ep-mail"><img id="brand-logo" src="logo-ep-daylight.svg" alt="Eternity Project"></div>
<button class="rail-button active" data-view="mail" aria-label="Mail"><span>✉</span></button>
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
<div class="rail-spacer"></div>
</aside>
<aside class="sidebar">
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
<button class="folder" data-folder="Snoozed"><span class="nav-glyph">◷</span><span>Snoozed</span></button>
<button class="folder" data-folder="Sent"><span class="nav-glyph">↗</span><span>Sent</span></button>
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
<div id="custom-folders"></div>
</nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="sidebar-divider"></div>
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
<button class="label-link" data-label="Travel"><i class="label-dot dot-blue"></i>Travel</button>
<button class="label-link" data-label="Personal"><i class="label-dot dot-green"></i>Personal</button>
<div id="custom-labels"></div>
<div class="sidebar-bottom"><div class="storage"><div class="storage-top"><span>Storage</span><span>4.2 / 15 GB</span></div><div class="storage-bar"><i></i></div><small>Plenty of room for the good things.</small></div><button class="settings-button" id="settings-button"><span>⚙</span> Settings</button></div>
</aside>
<main class="main-area">
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
<section id="mail-view" class="content-view mail-layout">
<div class="list-pane">
<div class="list-heading"><div><div class="date-line" id="today-label">MONDAY, OCTOBER 4</div><h2 id="welcome-heading">Good morning<span id="greeting-name" hidden></span></h2></div><button class="compose-button" id="compose"><span>+</span> Compose</button></div>
<div class="toolbar"><button class="tool-checkbox" id="select-all" aria-label="Select all">□</button><button class="icon-button" id="refresh" title="Refresh">↻</button><span class="toolbar-divider"></span><button class="icon-button" id="archive-selected" title="Archive">▱</button><button class="icon-button" id="delete-selected" title="Delete">⌫</button><button class="icon-button" id="mark-unread" title="Mark unread">✉</button><span class="toolbar-spacer"></span><button class="icon-button" id="previous-page" title="Previous page">‹</button><span class="pagination" id="pagination">1–8 of 24</span><button class="icon-button" id="next-page" title="Next page">›</button></div>
<div class="message-list" id="message-list" aria-label="Messages"></div>
<div class="list-foot"><span><i class="online-dot"></i> <span id="mail-status">All caught up with your mail</span></span><button class="text-button" id="load-more">Load more <span>↓</span></button></div>
</div>
<article class="reader-pane" id="reader-pane"></article>
</section>
<section id="calendar-view" class="content-view page-view hidden"></section>
<section id="contacts-view" class="content-view page-view hidden"></section>
</main>
</div>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4f5f1">
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
<title>ep-mail</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="branding.css">
</head>
<body>
<div class="app-shell">
<aside class="rail" aria-label="Main navigation">
<div class="brand-mark" title="ep-mail"><img id="brand-logo" src="logo-ep-daylight.svg" alt="Eternity Project"></div>
<button class="rail-button active" data-view="mail" aria-label="Mail"><span>✉</span></button>
<button class="rail-button" data-view="calendar" aria-label="Calendar"><span>▦</span></button>
<button class="rail-button" data-view="contacts" aria-label="Contacts"><span>♙</span></button>
<div class="rail-spacer"></div>
</aside>
<aside class="sidebar">
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
<button class="folder" data-folder="Snoozed"><span class="nav-glyph">◷</span><span>Snoozed</span></button>
<button class="folder" data-folder="Sent"><span class="nav-glyph">↗</span><span>Sent</span></button>
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
<div id="custom-folders"></div>
</nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="sidebar-divider"></div>
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
<button class="label-link" data-label="Travel"><i class="label-dot dot-blue"></i>Travel</button>
<button class="label-link" data-label="Personal"><i class="label-dot dot-green"></i>Personal</button>
<div id="custom-labels"></div>
<div class="sidebar-bottom"><div class="storage"><div class="storage-top"><span>Storage</span><span>4.2 / 15 GB</span></div><div class="storage-bar"><i></i></div><small>Plenty of room for the good things.</small></div><button class="settings-button" id="settings-button"><span>⚙</span> Settings</button></div>
</aside>
<main class="main-area">
<header class="topbar"><div class="breadcrumbs"><span id="crumb-parent">Mail</span><span class="crumb-divider">/</span><strong id="crumb-current">Inbox</strong></div><div class="top-actions"><div class="search-wrap"><span>⌕</span><input id="search" placeholder="Search mail" aria-label="Search mail"><kbd>⌘ K</kbd></div><button class="icon-button" id="search-filters-toggle" aria-expanded="false" title="Search filters">☷</button><button class="icon-button help-button" aria-label="Help" title="Help">?</button><button class="avatar top-avatar profile-button" title="Account settings" aria-label="Account settings">•</button><section id="search-filters" class="search-filters hidden" aria-label="Advanced search filters"><label>Folder<select id="filter-folder"><option value="">Current folder</option><option>Inbox</option><option>Sent</option><option>Archive</option><option>Trash</option></select></label><label>From<input id="filter-sender" placeholder="Sender contains"></label><label>Subject<input id="filter-subject" placeholder="Subject contains"></label><label>After<input id="filter-after" type="date"></label><label>Before<input id="filter-before" type="date"></label><label class="filter-checkbox"><input id="filter-attachments" type="checkbox"> Has attachments</label><button id="clear-search-filters" class="text-button">Clear filters</button></section></div></header>
<section id="mail-view" class="content-view mail-layout">
<div class="list-pane">
<div class="list-heading"><div><div class="date-line" id="today-label">MONDAY, OCTOBER 4</div><h2 id="welcome-heading">Good morning<span id="greeting-name" hidden></span></h2></div><button class="compose-button" id="compose"><span>+</span> Compose</button></div>
<div class="toolbar"><button class="tool-checkbox" id="select-all" aria-label="Select all">□</button><button class="icon-button" id="refresh" title="Refresh">↻</button><span class="toolbar-divider"></span><button class="icon-button" id="archive-selected" title="Archive">▱</button><button class="icon-button" id="delete-selected" title="Delete">⌫</button><button class="icon-button" id="mark-unread" title="Mark unread">✉</button><span class="toolbar-spacer"></span><button class="icon-button" id="previous-page" title="Previous page">‹</button><span class="pagination" id="pagination">1–8 of 24</span><button class="icon-button" id="next-page" title="Next page">›</button></div>
<div class="message-list" id="message-list" aria-label="Messages"></div>
<div class="list-foot"><span><i class="online-dot"></i> <span id="mail-status">All caught up with your mail</span></span><button class="text-button" id="load-more">Load more <span>↓</span></button></div>
</div>
<article class="reader-pane" id="reader-pane"></article>
</section>
<section id="calendar-view" class="content-view page-view hidden"></section>
<section id="contacts-view" class="content-view page-view hidden"></section>
</main>
</div>
<div id="modal-root"></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="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="productivity.js"></script>
<script src="snooze-ui.js"></script>
<script src="productivity.js"></script>
<script src="snooze-ui.js"></script>
<script src="dav-ui.js"></script>
<script src="account-ui.js"></script>
<script src="shortcuts.js"></script>
<script src="attachments.js"></script>
<script src="pgp-ui.js"></script>
<script src="pgp-mail-ui.js"></script>
</body>
</html>
<script src="shortcuts.js"></script>
<script src="attachments.js"></script>
<script src="pgp-ui.js"></script>
<script src="pgp-mail-ui.js"></script>
</body>
</html>
+9 -9
View File
@@ -1,9 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
<g fill="none" stroke="#181b19">
<circle cx="32" cy="32" r="28" stroke-width="2"/>
<path d="M32 3v58" stroke-width="3"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
</g>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
<g fill="none" stroke="#181b19">
<circle cx="32" cy="32" r="28" stroke-width="2"/>
<path d="M32 3v58" stroke-width="3"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 534 B

After

Width:  |  Height:  |  Size: 543 B

+9 -9
View File
@@ -1,9 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
<g fill="none" stroke="#e7e2d3">
<circle cx="32" cy="32" r="28" stroke-width="2"/>
<path d="M32 3v58" stroke-width="3"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
</g>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" aria-hidden="true" focusable="false">
<g fill="none" stroke="#e7e2d3">
<circle cx="32" cy="32" r="28" stroke-width="2"/>
<path d="M32 3v58" stroke-width="3"/>
<ellipse cx="32" cy="18" rx="12" ry="5" stroke-width="2" transform="rotate(22 32 18)"/>
<ellipse cx="32" cy="46" rx="12" ry="5" stroke-width="2" transform="rotate(-22 32 46)"/>
<ellipse cx="32" cy="32" rx="8" ry="8" stroke-width="1.5" opacity=".6" transform="rotate(45 32 32)"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 534 B

After

Width:  |  Height:  |  Size: 543 B

+948 -724
View File
File diff suppressed because it is too large Load Diff
+10 -10
View File
@@ -1,10 +1,10 @@
{
"name": "ep-mail",
"short_name": "ep-mail",
"description": "Eternity Project mail, calendar, and contacts.",
"start_url": "./",
"display": "standalone",
"background_color": "#f4f5f1",
"theme_color": "#f4f5f1",
"icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]
}
{
"name": "ep-mail",
"short_name": "ep-mail",
"description": "Eternity Project mail, calendar, and contacts.",
"start_url": "./",
"display": "standalone",
"background_color": "#f4f5f1",
"theme_color": "#f4f5f1",
"icons": [{"src":"icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any maskable"}]
}
+5382 -5375
View File
File diff suppressed because it is too large Load Diff
+112 -108
View File
@@ -1,108 +1,112 @@
{
"name": "ep-mail",
"version": "0.4.39",
"private": true,
"description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
"author": {
"name": "Eternity Project",
"email": "tero.huttunen@eternityproject.fi"
},
"desktopName": "ep-mail",
"main": "desktop/main.cjs",
"scripts": {
"start": "electron .",
"dev": "electron .",
"dist:win": "electron-builder --win",
"dist:win:installer": "electron-builder --win nsis",
"dist:win:portable": "electron-builder --win portable",
"dist:linux": "electron-builder --linux AppImage deb",
"dist:linux:appimage": "electron-builder --linux AppImage",
"dist:linux:deb": "electron-builder --linux deb",
"bump:build": "npm version patch --no-git-tag-version",
"test": "node --test tests/",
"build:android-web": "node scripts/prepare-android-web.cjs",
"android:sync": "npm run build:android-web && cap sync android",
"android:open": "npm run android:sync && cap open android",
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
},
"devDependencies": {
"@capacitor/cli": "^8.5.2",
"electron": "44.5.1",
"electron-builder": "26.17.0",
"esbuild": "^0.28.2"
},
"build": {
"appId": "studio.daybreak.mail",
"productName": "ep-mail",
"asar": true,
"files": [
"index.html",
"platform-bridge.js",
"styles.css",
"branding.css",
"renderer-state.js",
"mail-content-security.js",
"renderer-mail-api.js",
"app.js",
"mail-ui.js",
"productivity.js",
"account-ui.js",
"dav-ui.js",
"shortcuts.js",
"attachments.js",
"pgp-ui.js",
"pgp-mail-ui.js",
"icon.svg",
"icon.ico",
"logo-ep-daylight.svg",
"logo-ep-wasteland.svg",
"manifest.webmanifest",
"service-worker.js",
"snooze-ui.js",
"desktop/**/*"
],
"directories": {
"output": "release"
},
"win": {
"icon": "icon.ico",
"target": [
"nsis",
"portable"
]
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"createStartMenuShortcut": true
},
"linux": {
"category": "Office",
"syncDesktopName": true,
"target": [
"AppImage",
"deb"
],
"maintainer": "Tero Huttunen <tero.huttunen@eternityproject.fi>",
"synopsis": "A calmer place for mail, people, and plans"
}
},
"allowScripts": {
"electron@44.5.1": true,
"electron-winstaller@5.4.0": true,
"esbuild@0.28.2": true
},
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
"ical.js": "^2.2.1",
"imapflow": "2.2.1",
"mailparser": "3.9.33",
"nodemailer": "10.0.9",
"openpgp": "^6.3.2",
"tsdav": "^2.3.4"
}
}
{
"name": "ep-mail",
"version": "0.5.23",
"private": true,
"description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
"author": {
"name": "Eternity Project",
"email": "tero.huttunen@eternityproject.fi"
},
"desktopName": "ep-mail",
"main": "desktop/main.cjs",
"scripts": {
"start": "electron .",
"dev": "electron .",
"dist:win": "electron-builder --win",
"dist:win:installer": "electron-builder --win nsis",
"dist:win:portable": "electron-builder --win portable",
"dist:linux": "electron-builder --linux AppImage deb",
"dist:linux:appimage": "electron-builder --linux AppImage",
"dist:linux:deb": "electron-builder --linux deb",
"bump:build": "npm version patch --no-git-tag-version",
"test": "node --test tests/",
"build:android-web": "node scripts/prepare-android-web.cjs",
"android:sync": "npm run build:android-web && cap sync android",
"android:open": "npm run android:sync && cap open android",
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
"android:release-apk": "npm run android:sync && node scripts/build-android-release-apk.cjs",
"build": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1",
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
},
"devDependencies": {
"@capacitor/cli": "^8.5.2",
"electron": "44.5.1",
"electron-builder": "26.17.0",
"esbuild": "^0.28.2"
},
"build": {
"appId": "studio.daybreak.mail",
"productName": "ep-mail",
"asar": true,
"files": [
"index.html",
"platform-bridge.js",
"platform-bridge-loader.js",
"styles.css",
"branding.css",
"renderer-state.js",
"mail-content-security.js",
"renderer-mail-api.js",
"app.js",
"mail-ui.js",
"productivity.js",
"account-ui.js",
"dav-ui.js",
"shortcuts.js",
"attachments.js",
"pgp-ui.js",
"pgp-mail-ui.js",
"icon.svg",
"icon.ico",
"logo-ep-daylight.svg",
"logo-ep-wasteland.svg",
"manifest.webmanifest",
"service-worker.js",
"snooze-ui.js",
"desktop/**/*"
],
"directories": {
"output": "release"
},
"win": {
"icon": "icon.ico",
"target": [
"nsis",
"portable"
]
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"createDesktopShortcut": true,
"createStartMenuShortcut": true
},
"linux": {
"category": "Office",
"syncDesktopName": true,
"target": [
"AppImage",
"deb"
],
"maintainer": "Tero Huttunen <tero.huttunen@eternityproject.fi>",
"synopsis": "A calmer place for mail, people, and plans"
}
},
"allowScripts": {
"electron@44.5.1": true,
"electron-winstaller@5.4.0": true,
"esbuild@0.28.2": true
},
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
"ical.js": "^2.2.1",
"imapflow": "2.2.1",
"mailparser": "3.9.33",
"nodemailer": "10.0.9",
"openpgp": "6.3.2",
"tsdav": "^2.3.4",
"v8-compile-cache": "^2.4.0"
}
}
+41 -9
View File
@@ -74,6 +74,12 @@ 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>`;
} else if (message.encrypted) {
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) {
html = pgpSignatureHtml(message.pgpSignatures, false);
}
@@ -104,9 +110,14 @@ async function pgpUnlockMessage(message, interactive) {
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
return;
}
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') {
if (!interactive) { pgpRenderReaderState(message); return; }
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
const prompt = result.code === 'BAD_PASSPHRASE'
? 'That passphrase was incorrect. Try again.'
: result.code === 'BIOMETRIC_INVALIDATED'
? `${result.message} Enter the passphrase to continue.`
: `Enter the passphrase for ${result.email || 'your key'}.`;
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
if (passphrase === null) return;
continue;
}
@@ -117,6 +128,20 @@ async function pgpUnlockMessage(message, interactive) {
}
}
async function pgpVerifyMessage(message) {
try {
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);
const message = pgpMailUi.state.messages.find(item => item.id === id);
@@ -126,16 +151,20 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
message.pgpAutoTried = true;
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.
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
baseShowCompose(reply, forward);
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false, draft = null) {
baseShowCompose(reply, forward, draft);
const footer = selectPgpMailUi('#modal-root .compose-footer');
if (!footer || !pgpApi()) return;
const box = document.createElement('div');
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);
let touched = false;
const encrypt = selectPgpMailUi('#pgp-encrypt');
@@ -155,7 +184,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
if (!selectPgpMailUi('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
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 !== 'verified') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
if (!touched && !encrypt.checked) encrypt.checked = true;
}
} catch { hint.textContent = ''; }
@@ -169,6 +198,9 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
async function prepareSend(to, cc) {
if (!pgpApi()) return null;
const plaintextFallback = () => pgpApi().platform === 'android'
? { encrypt: false, sign: false, plaintextFallback: true }
: null;
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
@@ -176,7 +208,7 @@ async function prepareSend(to, cc) {
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return null;
if (!sign) return plaintextFallback();
} else return false;
}
if (!encrypt && !sign) return null;
@@ -184,12 +216,12 @@ async function prepareSend(to, cc) {
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
if (!sendPlain) return false;
encrypt = false;
if (!sign) return null;
if (!sign) return plaintextFallback();
}
let passphrase = null;
if (sign) {
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 && !status.signer.biometricUnlockEnabled) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false;
}
+83 -37
View File
@@ -6,12 +6,34 @@ const selectAllPgpKeyUi = pgpKeyMailUi.selectAll;
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
const toastPgpKeyUi = pgpKeyMailUi.toast;
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() {
const root = selectPgpKeyUi('#modal-root');
const account = window.epMailFeatures.mail.connectedAccount || {};
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>
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
const serverSettings = `<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 pgp-keys-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">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Optional biometric unlock stores the passphrase in a Keystore key requiring user authentication. 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>
<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>
@@ -21,19 +43,7 @@ function openEncryptionKeys() {
<h3 class="pgp-heading">Contact public keys</h3>
<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>
<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>
${serverSettings}
<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>
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
@@ -42,7 +52,7 @@ function openEncryptionKeys() {
<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="${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>
<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">${androidPgp ? 'Import private key from file…' : 'Import private key…'}</button>${androidPgp ? '<button class="discard" id="pgp-import-paste">Paste private key…</button>' : ''}</div>
<p class="account-note" id="pgp-status" role="status"></p>
</div></div></div>`;
const close = () => { root.innerHTML = ''; };
@@ -126,6 +136,42 @@ function openEncryptionKeys() {
}
};
row.append(changePassphrase);
if (androidPgp) {
const biometric = document.createElement('button');
biometric.className = 'discard';
biometric.textContent = 'Checking biometric unlock…';
biometric.disabled = true;
row.append(biometric);
window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => {
if (!biometric.isConnected) return;
biometric.dataset.enabled = String(enabled);
biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…';
biometric.disabled = false;
}).catch(error => {
if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.');
});
biometric.onclick = async () => {
biometric.disabled = true;
try {
if (biometric.dataset.enabled === 'true') {
if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return;
await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint);
status('Biometric unlock disabled.');
} else {
const passphrase = needPassphrase();
if (!passphrase) return;
await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase });
passphraseField().value = '';
status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.');
}
await render();
} catch (error) {
status(error.message || 'Could not update biometric key unlock.');
} finally {
biometric.disabled = false;
}
};
}
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
actions.push(['Delete', async () => {
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
@@ -140,7 +186,7 @@ function openEncryptionKeys() {
button.onclick = async () => {
if (secret && !passphraseField().value) { needPassphrase(); return; }
try {
const result = await run();
const result = await saveAndroidPgpExport(label, await run());
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
} catch (error) { status(error.message || 'That action failed.'); }
};
@@ -183,15 +229,17 @@ function openEncryptionKeys() {
} catch (error) { status(error.message || 'Could not create the key.'); }
button.disabled = false;
};
selectPgpKeyUi('#pgp-import').onclick = async () => {
const importPrivateKey = async source => {
const passphrase = needPassphrase();
if (!passphrase) return;
try {
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
status(result.canceled ? '' : 'Key imported.');
await render();
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null, ...(androidPgp ? { source } : {}) });
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.');
if (!result.canceled) await render();
} catch (error) { status(error.message || 'Could not import the key.'); }
};
selectPgpKeyUi('#pgp-import').onclick = () => importPrivateKey(androidPgp ? 'file' : undefined);
if (androidPgp) selectPgpKeyUi('#pgp-import-paste').onclick = () => importPrivateKey('paste');
async function renderContacts() {
const list = selectPgpKeyUi('#pgp-contact-list');
let contacts = [];
@@ -241,7 +289,7 @@ function openEncryptionKeys() {
button.className = 'discard';
button.textContent = label;
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.'); }
};
row.append(button);
@@ -311,19 +359,17 @@ function openEncryptionKeys() {
};
enabledLabel.append(enabledText, enabled);
row.append(info, enabledLabel);
if (!server.builtin) {
const remove = document.createElement('button');
remove.className = 'discard';
remove.textContent = 'Remove';
remove.onclick = async () => {
try {
await window.daybreakMail.pgp.removeKeyServer(server.id);
await renderKeyServers();
status('Custom key server removed.');
} catch (error) { status(error.message || 'Could not remove the key server.'); }
};
row.append(remove);
}
const remove = document.createElement('button');
remove.className = 'discard';
remove.textContent = 'Remove';
remove.onclick = async () => {
try {
await window.daybreakMail.pgp.removeKeyServer(server.id);
await renderKeyServers();
status(`${server.name} removed.`);
} catch (error) { status(error.message || 'Could not remove the key server.'); }
};
row.append(remove);
list.append(row);
});
}
@@ -408,8 +454,8 @@ function openEncryptionKeys() {
void render();
}
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
baseOpenPreferences();
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => async function () {
await baseOpenPreferences();
const fields = selectPgpKeyUi('#modal-root .compose-fields');
if (!fields || !pgpAvailable()) return;
const button = document.createElement('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>');
})();
+10863 -26
View File
File diff suppressed because one or more lines are too long
+15 -4
View File
@@ -27,16 +27,27 @@ function openAccountSettings() {
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')};
selectProductivityUi('#profile-name').focus();
}
function openPreferences() {
async function openPreferences() {
const root=selectProductivityUi('#modal-root');
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
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?.setAppLockDelay?window.daybreakMail:null;
const localDataBridge=window.daybreakMail?.deleteAllLocalData?window.daybreakMail:null;
let notificationPrivacy={showDetails:false};
let appLockSettings={enabled:false,deviceSecure:false,lockDelaySeconds:0};
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><label class="compose-line"><span>Lock delay</span><select class="settings-select" id="app-lock-delay"><option value="0"${appLockSettings.lockDelaySeconds===0?' selected':''}>Immediately</option><option value="30"${appLockSettings.lockDelaySeconds===30?' selected':''}>30 seconds</option><option value="60"${appLockSettings.lockDelaySeconds===60?' selected':''}>1 minute</option><option value="300"${appLockSettings.lockDelaySeconds===300?' selected':''}>5 minutes</option></select></label><p class="account-note">Requires a secure Android screen lock. Screenshots are hidden as soon as you leave; mail sync continues in the background.</p>`:'';
const localDataSetting=localDataBridge?`<h3 class="pgp-heading">Local data</h3><p class="account-note">Delete saved accounts, cached mail, drafts, queued sends, OpenPGP keys, app settings, and attachments saved by ep-mail to Downloads.</p><button class="discard" id="delete-all-local-data">Delete all local data…</button>`:'';
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}${localDataSetting}</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='';
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
selectProductivityUi('#save-appearance').onclick=()=>{productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('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.setAppLockDelay(Number(selectProductivityUi('#app-lock-delay').value));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')}};
if(localDataBridge)selectProductivityUi('#delete-all-local-data').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await localDataBridge.deleteAllLocalData();if(!result?.deleted){button.disabled=false;return}if('serviceWorker'in navigator){const registrations=await navigator.serviceWorker.getRegistrations();await Promise.all(registrations.map(registration=>registration.unregister()))}if('caches'in window){const names=await caches.keys();await Promise.all(names.map(name=>caches.delete(name)))}localStorage.clear();window.location.reload()}catch(error){button.disabled=false;toastProductivityUi(error.message||'Native data was deleted, but browser data cleanup did not finish. Restart ep-mail to complete cleanup.')}};
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=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(); }
@@ -72,7 +83,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
}
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}if(!message?.uid||!window.daybreakMail?.saveAttachment){toastProductivityUi('Attachment download is available for connected mailbox messages');return}window.daybreakMail.saveAttachment({uid:message.uid,folder:productivityMailUi.state.activeFolder,filename}).then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
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; },

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