Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ada3c2ce8 | ||
|
|
9b0009faef | ||
|
|
57e194562b | ||
|
|
28d63156fb | ||
|
|
e3b3a9bb52 | ||
|
|
d165fdc4b4 | ||
|
|
a42774dcf1 | ||
|
|
0250743250 | ||
|
|
3d5eb5517f | ||
|
|
b9d46fde1e | ||
|
|
1f550dc5c3 | ||
|
|
3963778da1 |
+41
-30
@@ -1,14 +1,24 @@
|
|||||||
# Android security plan for ep-mail
|
# Android security plan for ep-mail
|
||||||
|
|
||||||
Status: **Plan**. Android already has several useful protections, but it does not yet provide Android OpenPGP support, an app lock, or a release security assurance process. This document turns the remaining Android security work into an incremental plan. It is not a security certification or a substitute for an independent review.
|
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).
|
Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECURITY_REVIEW.md), and [TODO.md](./TODO.md).
|
||||||
|
|
||||||
## Implementation progress (2026-11-03)
|
## Implementation progress (2026-11-03)
|
||||||
|
|
||||||
- Implemented: explicit Android cleartext denial and backup/data-extraction exclusions; removed the wildcard Cordova origin and unused broad `FileProvider`; DAV now requires HTTPS, rejects embedded credentials/fragments, stays on the configured origin, and does not follow redirects; saved attachment names are sanitized; notification previews and native logs no longer expose mailbox content; debug APKs are labeled as debug and signed release builds require environment-provided signing credentials.
|
- **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.
|
||||||
- Tested: DAV URL policy and attachment-name policy have Android unit tests. The debug Android build and unit tests pass, as does the Node test suite.
|
- **Phase 1 — Local data/privacy:** Notification privacy, immediate background app locking, `FLAG_SECURE` while locked, account-removal disclosure, and a fail-closed missing-key recovery screen are implemented. Vault lifecycle, complete deletion semantics, and app-lock lifecycle/biometric follow-up remain open.
|
||||||
- Still open: invalid-certificate integration tests, device-level review of the merged release APK, private notification preference UI, app lock/biometric unlock, full vault lifecycle testing, and Android OpenPGP. OpenPGP work remains gated on an independent cryptography/security review.
|
- **Phase 2 — Android OpenPGP:** Experimental test implementation is present. It is not security-reviewed or release-complete.
|
||||||
|
- **Phase 3 — WebView/bridge:** Important protections are implemented; complete bridge review and device/content testing remain open.
|
||||||
|
- **Phase 4 — Assurance:** Open; independent review, release assurance, and vulnerability/maintenance work remain.
|
||||||
|
|
||||||
|
Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed.
|
||||||
|
|
||||||
|
OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, and on-demand PGP/MIME or inline-encrypted-message decryption. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**.
|
||||||
|
|
||||||
|
**Validation evidence:** DAV URL, attachment-name, notification privacy, Android OpenPGP policy decisions, one-shot confirmation callbacks, and the missing-vault-key policy have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock/unlock; with the lock active, emulator screenshots were fully obscured, and unlocking/turning the setting off restored the app. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Current validation: 153 Node tests and 21 Android unit tests pass; the Android debug build and release-manifest task succeed. Device testing of vault-corruption/key-loss recovery, invalid-certificate integration tests, production-signed APK review, and automated instrumentation of the actual confirmation dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android.
|
||||||
|
|
||||||
|
**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric design; invalid-certificate integration tests; production-signed APK/manifest review; app-lock recovery polish; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain.
|
||||||
|
|
||||||
## Goals and limits
|
## Goals and limits
|
||||||
|
|
||||||
@@ -29,52 +39,53 @@ These are implementation observations, not proof that all paths are safe. In par
|
|||||||
|
|
||||||
### Phase 0 — Android security baseline and release gate (P0)
|
### Phase 0 — Android security baseline and release gate (P0)
|
||||||
|
|
||||||
1. Establish a repeatable security checklist for the actual merged manifest and release APK: permissions, exported components, backup/data-extraction rules, cleartext policy, WebView debugging, file access, and Capacitor plugin exposure.
|
- [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.
|
||||||
2. Audit all native network clients. Require TLS, certificate-chain and hostname validation for IMAP/SMTP STARTTLS and DAV HTTPS; reject downgrade and insecure schemes. Add negative tests using invalid, expired, and mismatched certificates. Do not add certificate pinning by default; it creates rotation and recovery risks.
|
- [~] 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.
|
||||||
3. Review all `EpMailPlugin` methods as an untrusted-input boundary. Validate IDs, folders, URLs, attachment sizes/types, and state transitions natively; return only data needed by the UI. Ensure external navigation permits only explicitly supported safe schemes and is always user initiated.
|
- [~] 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.
|
||||||
4. Ensure release builds disable WebView debugging and do not include debug-only configuration. Keep signing keys outside the repository and CI logs. Publish only signed release artifacts, not the current debug APK output.
|
- [~] 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.
|
||||||
5. Remove or sanitize sensitive diagnostics. Logs must not contain credentials, message bodies, subjects, recipient lists, attachment contents, passphrases, or raw protocol errors containing secrets. Use opaque IDs where correlation is needed.
|
- [~] 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.
|
**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)
|
### Phase 1 — Local data and privacy controls (P0)
|
||||||
|
|
||||||
1. Harden the encrypted vault: document the Keystore key's security properties and fallback behavior; use authenticated encryption with unique IVs; handle corruption, reinstall, lock-screen/key invalidation, and upgrades without plaintext fallback. Confirm all cached bodies, drafts, attachments, pending sends, DAV credentials, and account passwords remain inside the encrypted store or are deleted safely.
|
- [~] 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.
|
||||||
2. Add explicit account removal and app-data deletion behavior, including queued messages, caches, downloaded attachments, and encryption keys. Test that deletion is complete within app-controlled storage and explain that exported files/backups are outside app control.
|
- [~] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation now says downloaded attachment files and global OpenPGP keys are retained. Decide/test whether a separate app-data wipe should remove app-created Downloads and PGP keys; account removal intentionally leaves those user data intact.
|
||||||
3. Add a privacy setting for notification content. Default to generic “New mail” text without sender or subject; allow a user choice to show details. Apply the same rule to snooze reminders. Keep foreground-service notifications non-sensitive.
|
- [x] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting.
|
||||||
4. Add optional app-lock behavior (immediate, after a delay, or off) using Android biometric/device credential authentication. Lock on background/resume and process recreation according to the chosen timeout; obscure sensitive UI in the task switcher. Make screenshot/screen-recording blocking an optional policy rather than an unconditional default.
|
- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` while locked to hide task-switcher content and block screenshots; emulator smoke testing confirmed screenshots are obscured. Background sync continues and the setting is off unless enabled. Delayed lock, automated lifecycle/process-recreation tests, biometric UX, and recovery polish remain open.
|
||||||
5. Keep background sync semantics separate from UI lock. Do not require biometric auth for every background sync if that would break notifications; instead define which credential/key material is available to background work, minimize it, and ensure the UI lock prevents reading local mail. Document that a UI lock is not equivalent to encrypting against a rooted or already-unlocked device.
|
- [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.
|
**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)
|
### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity)
|
||||||
|
|
||||||
1. Reuse the desktop OpenPGP.js protocol and MIME behavior only after the independent cryptography review is complete. Confirm the selected library/version and generated key formats interoperate with GnuPG and Thunderbird on Android too.
|
- [~] 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. Independent review and GnuPG/Thunderbird interoperability on Android are release blockers.
|
||||||
2. Add an Android key store for private keys, public contacts, fingerprints, trust, and preferences. Protect the store with a random Android Keystore-wrapped encryption key. Private keys must additionally remain passphrase-protected; never persist passphrases. Support a bounded in-memory passphrase cache and wipe it on expiry, lock, and process teardown where practical.
|
- [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized. Biometric wrapping-key release, lifecycle/recovery handling, and automated checks against unprotected-key persistence remain open.
|
||||||
3. Support biometric/device-credential unlock as an optional way to release the store-wrapping key. Design background sync so it never needs private-key access. Handle biometric enrollment/key invalidation without silently destroying or regenerating the user's key store; provide explicit recovery/export guidance.
|
- [ ] Add optional biometric/device-credential release of PGP key access and test Keystore invalidation/recovery. Background sync does not use PGP private keys.
|
||||||
4. Add the narrow Android bridge and settings UI for key generation, import/export/delete, revocation certificate export, contact-key import, fingerprint comparison, and trust changes. Keep security decisions out of renderer-only code.
|
- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, and trust. Native prompts now guard trust elevation and replacement; automated cancel/confirm regression tests remain open.
|
||||||
5. Implement read and send paths: detect/decrypt PGP/MIME and supported inline PGP; verify signatures and show clear unknown/bad/changed-key states; encrypt/sign recipients and the sender's Sent copy; include attachments inside the encrypted MIME payload. Do not cache decrypted bodies or put plaintext/passphrases in drafts, logs, notifications, or offline outbox.
|
- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, and ciphertext-before-queueing are implemented. Signed-only/clear-signed/inline signature parity, full hostile-input/tampering suite, and Android interoperability remain open.
|
||||||
6. Enforce key replacement, trust elevation, and plaintext downgrade confirmations in native code (or another boundary the renderer cannot bypass). Show recipient addresses and full fingerprints; cancellation must leave state unchanged. Never silently send plaintext when encryption was requested or keys exist.
|
- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open.
|
||||||
7. Leave key-server lookup/publication disabled/out of initial Android scope. If added later, make it opt-in, disclose address lookup, require explicit publish destination and confirmation, and never treat server results as verified.
|
- [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.
|
**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)
|
### Phase 3 — WebView, native bridge, and content hardening (P1)
|
||||||
|
|
||||||
1. Verify the production CSP and generated `www` assets match the reviewed source. Keep mail HTML inert and sanitized; do not allow remote script, CSS, frames, forms, or arbitrary navigation. Continue blocking remote images by default and reset approval per message.
|
- [~] Mail HTML is sanitized, remote images are blocked until per-message approval, and CSP restrictions are in place. Verify the generated release assets/CSP against the reviewed source on supported devices.
|
||||||
2. Restrict WebView navigation to the packaged app origin. External links must be parsed and scheme/host checked, shown to the user, and opened outside the WebView; reject `javascript:`, `file:`, `content:`, `intent:`, and unknown schemes.
|
- [x] External URLs are constrained and require user confirmation before opening outside the WebView; unsafe schemes are rejected.
|
||||||
3. Review every Capacitor plugin/method and remove unused permissions/plugins. No generic filesystem, arbitrary intent, or unrestricted URL capability should be exposed to the renderer.
|
- [~] Broad unused filesystem/navigation capabilities have been removed, but a complete review of every Capacitor plugin/method and permission remains open.
|
||||||
4. Treat message HTML, headers, attachment names, filenames, sender data, key user IDs, and decrypted content as hostile input. Add sanitizer and UI regression cases for DOM injection, oversized payloads, spoofed signature indicators, and malicious filenames.
|
- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open.
|
||||||
|
|
||||||
**Exit criteria:** automated CSP/navigation/bridge tests, sanitizer regressions, and a manual WebView inspection on the minimum and target Android versions.
|
**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)
|
### Phase 4 — Assurance, maintenance, and incident readiness (P1)
|
||||||
|
|
||||||
1. Add Android dependency vulnerability checks and update policy for Capacitor, AndroidX, mail libraries, OpenPGP.js, and Gradle plugins. Review licenses and lock versions for security-critical dependencies.
|
- [ ] 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.
|
||||||
2. Run static analysis and Android-focused checks (including merged-manifest review and OWASP MASVS-aligned test cases) on release builds. Keep test evidence tied to the exact APK version/hash.
|
- [ ] Run static analysis, merged-manifest review, and Android/MASVS-aligned checks against a production release; bind evidence to that APK's version and hash.
|
||||||
3. Perform independent reviews of the Android Keystore/vault, Capacitor bridge, network/TLS configuration, and OpenPGP integration before describing Android as security-reviewed.
|
- [ ] Obtain independent human review of the Keystore/vault, bridge, TLS, and OpenPGP implementation before making security-reviewed claims.
|
||||||
4. Publish a concise Android security and recovery page: device-lock assumptions, notification/image privacy, TLS, local encryption, OpenPGP limits, key backup/revocation, and what account/key deletion does.
|
- [ ] Publish user-facing Android security, key-backup, and recovery guidance.
|
||||||
5. Define a private vulnerability-reporting contact, triage process, supported Android version range, and security-fix release process.
|
- [ ] Define a vulnerability-reporting contact, triage process, supported Android versions, and security-fix release process.
|
||||||
|
|
||||||
## Minimum release criteria for Android OpenPGP
|
## Minimum release criteria for Android OpenPGP
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
# Encryption plan: OpenPGP mail encryption for ep-mail
|
# Encryption plan: OpenPGP mail encryption for ep-mail
|
||||||
|
|
||||||
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android OpenPGP support and an independent human security review are still open. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for the broader Android security roadmap. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
|
Status: **Desktop implementation is complete; an experimental Android Phase 2 path is available for local testing only.** Native confirmation prompts are implemented in that test path, but automated bypass testing, Android interoperability, independent security review, and release assurance remain open. The Android test path must not be used for sensitive mail. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for details. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
|
||||||
|
|
||||||
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
|
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
|
||||||
|
|
||||||
@@ -63,7 +63,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend.
|
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend.
|
||||||
- [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs.
|
- [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs.
|
||||||
- [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`.
|
- [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`.
|
||||||
- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Hidden on platforms without a key store (Android until Phase 4).
|
- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Desktop key management is production functionality; Android exposes an experimental test UI.
|
||||||
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
|
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
|
||||||
|
|
||||||
## 7. Phases 2–5 implementation notes
|
## 7. Phases 2–5 implementation notes
|
||||||
@@ -72,7 +72,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting.
|
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting.
|
||||||
- Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload.
|
- Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload.
|
||||||
- Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key.
|
- Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key.
|
||||||
- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android does not yet implement OpenPGP.
|
- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android's test path supports this format up to 25 MiB, but it has not completed desktop parity, independent review, or release assurance.
|
||||||
- Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply.
|
- Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply.
|
||||||
- A signature from a key that differs from the one on file for the sender is flagged as a changed key.
|
- A signature from a key that differs from the one on file for the sender is flagged as a changed key.
|
||||||
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
|
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
|
||||||
|
|||||||
@@ -18,14 +18,14 @@ See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
|
|||||||
|
|
||||||
## Android app
|
## Android app
|
||||||
|
|
||||||
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, encrypted account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Android Settings can enable an app lock that covers the WebView and disables its JavaScript bridge when the app leaves the foreground; it also hides the locked screen from screenshots and recent-app previews. Unlock requires the device PIN, pattern, or password, while background mail sync continues. Configure a secure Android screen lock before enabling it. This is a local privacy control, not protection against a compromised or rooted device. Android OpenPGP is now present as an **experimental test-only feature** for key and message testing. It has not had an independent cryptography/security review and is not approved for sensitive or production mail; do not rely on it to protect important messages. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
npm install
|
npm install
|
||||||
npm run android:apk
|
npm run android:apk
|
||||||
```
|
```
|
||||||
|
|
||||||
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` 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 previews contain generic text rather than mailbox addresses or message subjects. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
||||||
|
|
||||||
## Run on Windows or Linux
|
## Run on Windows or Linux
|
||||||
|
|
||||||
@@ -39,4 +39,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
|
|||||||
|
|
||||||
## Current scope
|
## Current scope
|
||||||
|
|
||||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`.
|
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop supports encrypted and signed OpenPGP mail. Android has an experimental test implementation for key management and PGP/MIME send/read; it is not independently reviewed and is not suitable for sensitive mail (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)). Run the tests with `npm test`.
|
||||||
|
|||||||
+2
-2
@@ -63,8 +63,8 @@ Applied fixes:
|
|||||||
|
|
||||||
- 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.
|
- 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.
|
- 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.
|
- 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 has no OpenPGP implementation and is outside the reviewed desktop scope.
|
- 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)
|
## Third review pass (2026-10-17)
|
||||||
|
|
||||||
|
|||||||
@@ -26,20 +26,35 @@
|
|||||||
|
|
||||||
## Mail security
|
## 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] Add desktop support for encrypting and decrypting mail with OpenPGP (PGP/MIME); Android has a separate experimental implementation for local testing only. See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md).
|
||||||
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
|
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
|
||||||
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
|
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
|
||||||
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
|
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
|
||||||
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
|
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
|
||||||
- [ ] Phase 4 (Android): add Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
|
- [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption.
|
||||||
|
- [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation.
|
||||||
|
- [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions.
|
||||||
|
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, full parity/interoperability tests, independent human cryptography/security review, and signed release review.
|
||||||
|
- [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, signed/inline verification parity, and dependency advisory remediation.
|
||||||
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
||||||
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
|
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
|
||||||
- [x] Phase 6: documentation and release.
|
- [x] Phase 6: documentation and release.
|
||||||
- [x] Manual interoperability check with Thunderbird.
|
- [x] Manual interoperability check with Thunderbird.
|
||||||
- [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)).
|
- [x] Address findings from the automated OpenPGP security reviews (see [SECURITY_REVIEW.md](./SECURITY_REVIEW.md)).
|
||||||
- [ ] Complete an independent human security review of the encryption code before expanding OpenPGP support to Android.
|
- [ ] Complete an independent human security review of 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.
|
- [ ] Add direct IPC-handler tests for both accept and cancel paths of the main-process plaintext-send confirmation.
|
||||||
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
|
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
|
||||||
|
- [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews.
|
||||||
|
- [x] Add an optional native Android app lock using the device credential while leaving background mail sync available.
|
||||||
|
- [x] Set `FLAG_SECURE` while the optional app lock is engaged to hide the screen from screenshots and recents previews.
|
||||||
|
- [x] Exercise background lock, credential unlock, and screenshot obscuring on an Android emulator.
|
||||||
|
- [x] Disclose in account-removal confirmation that downloaded files and global OpenPGP keys are retained.
|
||||||
|
- [x] Refuse to generate a replacement Keystore key when encrypted vault data already exists; show a fail-closed recovery screen with clear-data guidance.
|
||||||
|
- [ ] Device-test missing/invalidated Keystore keys, corrupted vault data, migration/reinstall behavior, and recovery instructions.
|
||||||
|
- [ ] Define/test full app-data deletion and downloaded-file/OpenPGP-key retention or removal behavior.
|
||||||
|
- [ ] Add app-lock timeout/delay options and decide whether to add biometric unlock; test process recreation and lifecycle transitions.
|
||||||
|
|
||||||
## Appearance and settings
|
## Appearance and settings
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ async function openAccountManager(){
|
|||||||
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}
|
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
||||||
const removeButton=event.target.closest('[data-remove-account]');
|
const removeButton=event.target.closest('[data-remove-account]');
|
||||||
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;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}
|
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')}
|
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ internal object AndroidAccountVault {
|
|||||||
|
|
||||||
fun initialize(context: Context) {
|
fun initialize(context: Context) {
|
||||||
appContext = context.applicationContext
|
appContext = context.applicationContext
|
||||||
secretKey()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
@@ -57,6 +56,80 @@ internal object AndroidAccountVault {
|
|||||||
|
|
||||||
fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray()
|
fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray()
|
||||||
|
|
||||||
|
fun notificationDetailsEnabled(): Boolean =
|
||||||
|
read().optBoolean("showNotificationDetails", NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS)
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun setNotificationDetailsEnabled(enabled: Boolean): Boolean {
|
||||||
|
val store = read().put("showNotificationDetails", enabled)
|
||||||
|
write(store)
|
||||||
|
return enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false)
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun setAppLockEnabled(enabled: Boolean): Boolean {
|
||||||
|
val store = read().put("appLockEnabled", enabled)
|
||||||
|
write(store)
|
||||||
|
return enabled
|
||||||
|
}
|
||||||
|
|
||||||
|
fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) }
|
||||||
|
?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject())
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun savePgpStore(candidate: JSONObject) {
|
||||||
|
validatePgpStore(candidate)
|
||||||
|
val store = read().put("pgpStore", JSONObject(candidate.toString()))
|
||||||
|
write(store)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validatePgpStore(candidate: JSONObject) {
|
||||||
|
require(candidate.toString().length <= 3_000_000) { "The OpenPGP key store is too large." }
|
||||||
|
require(!hasPassphraseField(candidate)) { "Passphrases must never be stored." }
|
||||||
|
val keys = candidate.optJSONArray("keys") ?: JSONArray()
|
||||||
|
val contacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
||||||
|
require(keys.length() <= 20 && contacts.length() <= 500) { "The OpenPGP key store has too many entries." }
|
||||||
|
val fingerprint = Regex("^[0-9A-Fa-f]{40,64}$")
|
||||||
|
for (index in 0 until keys.length()) {
|
||||||
|
val entry = keys.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP key entry is invalid.")
|
||||||
|
val privateKey = entry.optString("privateKey")
|
||||||
|
val publicKey = entry.optString("publicKey")
|
||||||
|
require(fingerprint.matches(entry.optString("fingerprint")) &&
|
||||||
|
privateKey.length in 1..200_000 && privateKey.contains("BEGIN PGP PRIVATE KEY BLOCK") &&
|
||||||
|
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK")) {
|
||||||
|
"An OpenPGP key entry is invalid."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (index in 0 until contacts.length()) {
|
||||||
|
val entry = contacts.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP contact entry is invalid.")
|
||||||
|
val publicKey = entry.optString("publicKey")
|
||||||
|
require(fingerprint.matches(entry.optString("fingerprint")) &&
|
||||||
|
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK") &&
|
||||||
|
!publicKey.contains("BEGIN PGP PRIVATE KEY BLOCK")) {
|
||||||
|
"An OpenPGP contact entry is invalid."
|
||||||
|
}
|
||||||
|
require(entry.optString("trust") in setOf("unknown", "trusted", "verified")) {
|
||||||
|
"An OpenPGP contact trust value is invalid."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasPassphraseField(value: Any?): Boolean = when (value) {
|
||||||
|
is JSONObject -> {
|
||||||
|
val keys = value.keys()
|
||||||
|
var found = false
|
||||||
|
while (keys.hasNext() && !found) {
|
||||||
|
val key = keys.next()
|
||||||
|
found = key.contains("passphrase", ignoreCase = true) || hasPassphraseField(value.opt(key))
|
||||||
|
}
|
||||||
|
found
|
||||||
|
}
|
||||||
|
is JSONArray -> (0 until value.length()).any { hasPassphraseField(value.opt(it)) }
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
|
||||||
fun account(id: String? = null): JSONObject? {
|
fun account(id: String? = null): JSONObject? {
|
||||||
val store = read()
|
val store = read()
|
||||||
val accounts = store.optJSONArray("accounts") ?: return null
|
val accounts = store.optJSONArray("accounts") ?: return null
|
||||||
@@ -432,6 +505,10 @@ internal object AndroidAccountVault {
|
|||||||
.put("displayName", account.optString("displayName"))
|
.put("displayName", account.optString("displayName"))
|
||||||
.put("imapHost", account.optString("imapHost"))
|
.put("imapHost", account.optString("imapHost"))
|
||||||
.put("smtpHost", account.optString("smtpHost"))
|
.put("smtpHost", account.optString("smtpHost"))
|
||||||
|
.put("imapPort", account.optInt("imapPort", 143))
|
||||||
|
.put("smtpPort", account.optInt("smtpPort", 587))
|
||||||
|
.put("imapSecure", account.optBoolean("imapSecure", false))
|
||||||
|
.put("smtpSecure", account.optBoolean("smtpSecure", false))
|
||||||
.put("signature", account.optString("signature"))
|
.put("signature", account.optString("signature"))
|
||||||
.put("notificationsEnabled", account.optBoolean("notificationsEnabled", true))
|
.put("notificationsEnabled", account.optBoolean("notificationsEnabled", true))
|
||||||
.put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2))
|
.put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2))
|
||||||
@@ -523,6 +600,11 @@ internal object AndroidAccountVault {
|
|||||||
private fun secretKey(): SecretKey {
|
private fun secretKey(): SecretKey {
|
||||||
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
||||||
|
val hasEncryptedData = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
.contains(ENCRYPTED_VALUE)
|
||||||
|
check(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData)) {
|
||||||
|
AndroidVaultKeyPolicy.MISSING_KEY_MESSAGE
|
||||||
|
}
|
||||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
||||||
generator.init(
|
generator.init(
|
||||||
KeyGenParameterSpec.Builder(
|
KeyGenParameterSpec.Builder(
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import com.sun.mail.imap.IMAPFolder
|
|||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
import java.text.DateFormat
|
import java.text.DateFormat
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Calendar
|
import java.util.Calendar
|
||||||
@@ -263,11 +265,24 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun send(account: JSONObject, input: JSONObject): JSONObject {
|
fun send(account: JSONObject, input: JSONObject): JSONObject {
|
||||||
|
val rawBase64 = input.optString("rawBase64")
|
||||||
|
val session = Session.getInstance(smtpProperties(account), credentials(account))
|
||||||
|
val message: MimeMessage
|
||||||
|
if (rawBase64.isNotBlank()) {
|
||||||
|
require(rawBase64.length <= 36_000_000 && rawBase64.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
|
||||||
|
"The encrypted message is too large or invalid."
|
||||||
|
}
|
||||||
|
val bytes = Base64.decode(rawBase64, Base64.DEFAULT)
|
||||||
|
require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." }
|
||||||
|
message = MimeMessage(session, ByteArrayInputStream(bytes))
|
||||||
|
validateOpenPgpMime(message)
|
||||||
|
require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) {
|
||||||
|
"The encrypted message needs a sender and at least one recipient."
|
||||||
|
}
|
||||||
|
} else {
|
||||||
val recipient = input.optString("to").trim()
|
val recipient = input.optString("to").trim()
|
||||||
require(recipient.isNotEmpty()) { "Add at least one recipient." }
|
require(recipient.isNotEmpty()) { "Add at least one recipient." }
|
||||||
val properties = smtpProperties(account)
|
message = MimeMessage(session)
|
||||||
val session = Session.getInstance(properties, credentials(account))
|
|
||||||
val message = MimeMessage(session)
|
|
||||||
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
|
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
|
||||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
|
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
|
||||||
val cc = input.optString("cc").trim()
|
val cc = input.optString("cc").trim()
|
||||||
@@ -309,6 +324,7 @@ internal object AndroidMailService {
|
|||||||
message.sentDate = Date()
|
message.sentDate = Date()
|
||||||
message.saveChanges()
|
message.saveChanges()
|
||||||
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
|
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
|
||||||
|
}
|
||||||
|
|
||||||
val transport = session.getTransport("smtp")
|
val transport = session.getTransport("smtp")
|
||||||
try {
|
try {
|
||||||
@@ -337,6 +353,61 @@ internal object AndroidMailService {
|
|||||||
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
|
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun pgpMessageSource(account: JSONObject, folderName: String, uid: Long): JSONObject = withStore(account) { _, store ->
|
||||||
|
require(uid > 0) { "That message could not be identified." }
|
||||||
|
val folder = resolveFolder(store, folderName) ?: throw IllegalStateException("That mail folder could not be found.")
|
||||||
|
folder.open(Folder.READ_ONLY)
|
||||||
|
try {
|
||||||
|
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
|
||||||
|
?: throw IllegalStateException("The message is no longer available.")
|
||||||
|
val output = ByteArrayOutputStream()
|
||||||
|
message.writeTo(output)
|
||||||
|
val bytes = output.toByteArray()
|
||||||
|
require(bytes.size <= 25 * 1024 * 1024) { "This encrypted message is too large to open on Android testing builds." }
|
||||||
|
JSONObject().put("rawBase64", Base64.encodeToString(bytes, Base64.NO_WRAP))
|
||||||
|
} finally {
|
||||||
|
folder.close(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validateOpenPgpMime(message: MimeMessage) {
|
||||||
|
val contentType = message.contentType.lowercase(Locale.ROOT)
|
||||||
|
val multipart = message.content as? Multipart
|
||||||
|
?: throw IllegalArgumentException("The OpenPGP MIME message is malformed.")
|
||||||
|
require(multipart.count == 2) { "The OpenPGP MIME message has an unexpected structure." }
|
||||||
|
if (contentType.startsWith("multipart/encrypted")) {
|
||||||
|
val versionPart = multipart.getBodyPart(0)
|
||||||
|
val encryptedPart = multipart.getBodyPart(1)
|
||||||
|
val version = runCatching { versionPart.content.toString().trim() }.getOrDefault("")
|
||||||
|
val armor = runCatching { String(encryptedPart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
|
||||||
|
require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" &&
|
||||||
|
encryptedPart.isMimeType("application/octet-stream") &&
|
||||||
|
armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) {
|
||||||
|
"The encrypted OpenPGP payload is missing or malformed."
|
||||||
|
}
|
||||||
|
} else if (contentType.startsWith("multipart/signed")) {
|
||||||
|
val signaturePart = multipart.getBodyPart(1)
|
||||||
|
val armor = runCatching { String(signaturePart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
|
||||||
|
require(signaturePart.isMimeType("application/pgp-signature") &&
|
||||||
|
armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) {
|
||||||
|
"The OpenPGP signature is missing or malformed."
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw IllegalArgumentException("Only an OpenPGP MIME message can use the protected send path.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun savePgpAttachment(context: Context, input: JSONObject): JSONObject {
|
||||||
|
val filename = input.optString("filename").replace(Regex("[\\\\/\\r\\n\\u0000]"), "").take(255).ifBlank { "attachment" }
|
||||||
|
val contentType = input.optString("contentType", "application/octet-stream").lowercase(Locale.ROOT)
|
||||||
|
require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) { "The attachment content type is invalid." }
|
||||||
|
val encoded = input.optString("contentBase64")
|
||||||
|
require(encoded.length <= 36_000_000 && encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
|
||||||
|
"The attachment is too large or invalid."
|
||||||
|
}
|
||||||
|
return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT))
|
||||||
|
}
|
||||||
|
|
||||||
fun flushOutbox(account: JSONObject) {
|
fun flushOutbox(account: JSONObject) {
|
||||||
val accountId = account.optString("id")
|
val accountId = account.optString("id")
|
||||||
val queued = AndroidAccountVault.pendingMailOperations(accountId)
|
val queued = AndroidAccountVault.pendingMailOperations(accountId)
|
||||||
@@ -491,14 +562,15 @@ internal object AndroidMailService {
|
|||||||
shouldStop: () -> Boolean,
|
shouldStop: () -> Boolean,
|
||||||
onConnection: (Store?, Folder?) -> Unit
|
onConnection: (Store?, Folder?) -> Unit
|
||||||
) {
|
) {
|
||||||
|
val protocol = imapProtocol(account)
|
||||||
val props = imapProperties(account).apply {
|
val props = imapProperties(account).apply {
|
||||||
setProperty("mail.imap.timeout", "0")
|
setProperty("mail.$protocol.timeout", "0")
|
||||||
setProperty("mail.imap.writetimeout", "60000")
|
setProperty("mail.$protocol.writetimeout", "60000")
|
||||||
}
|
}
|
||||||
val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
|
val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
|
||||||
.coerceIn(2, 60) * 60_000L
|
.coerceIn(2, 60) * 60_000L
|
||||||
val session = Session.getInstance(props, credentials(account))
|
val session = Session.getInstance(props, credentials(account))
|
||||||
val store = session.getStore("imap")
|
val store = session.getStore(protocol)
|
||||||
try {
|
try {
|
||||||
store.connect(
|
store.connect(
|
||||||
account.optString("imapHost"),
|
account.optString("imapHost"),
|
||||||
@@ -596,7 +668,9 @@ internal object AndroidMailService {
|
|||||||
val links = linkedSetOf<String>()
|
val links = linkedSetOf<String>()
|
||||||
collectParts(message, body, htmlBodies, attachments, links)
|
collectParts(message, body, htmlBodies, attachments, links)
|
||||||
val bodyText = body.joinToString("\n\n").trim().take(8000)
|
val bodyText = body.joinToString("\n\n").trim().take(8000)
|
||||||
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----")
|
||||||
|
val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText
|
||||||
|
val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
||||||
val date = message.receivedDate ?: message.sentDate ?: Date()
|
val date = message.receivedDate ?: message.sentDate ?: Date()
|
||||||
val tags = JSONArray().put(requestedFolder)
|
val tags = JSONArray().put(requestedFolder)
|
||||||
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
|
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
|
||||||
@@ -619,6 +693,7 @@ internal object AndroidMailService {
|
|||||||
.put("email", senderEmail)
|
.put("email", senderEmail)
|
||||||
.put("subject", subject)
|
.put("subject", subject)
|
||||||
.put("snippet", snippet)
|
.put("snippet", snippet)
|
||||||
|
.put("encrypted", encrypted)
|
||||||
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
|
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
|
||||||
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
|
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
|
||||||
.put("timestamp", date.time)
|
.put("timestamp", date.time)
|
||||||
@@ -631,7 +706,7 @@ internal object AndroidMailService {
|
|||||||
.put("sourceFolder", labelFolder)
|
.put("sourceFolder", labelFolder)
|
||||||
.put("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
|
.put("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
|
||||||
.put("body", JSONArray().apply {
|
.put("body", JSONArray().apply {
|
||||||
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
val paragraphs = visibleBody.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
||||||
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
||||||
})
|
})
|
||||||
.put("links", JSONArray().apply { links.take(30).forEach(::put) })
|
.put("links", JSONArray().apply { links.take(30).forEach(::put) })
|
||||||
@@ -640,6 +715,15 @@ internal object AndroidMailService {
|
|||||||
.put("size", files.firstOrNull()?.optString("size") ?: "")
|
.put("size", files.firstOrNull()?.optString("size") ?: "")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun isEncryptedMessage(part: javax.mail.Part): Boolean {
|
||||||
|
if (part.isMimeType("multipart/encrypted")) return true
|
||||||
|
val content = try { part.content } catch (_: Exception) { return false }
|
||||||
|
if (content is Multipart) {
|
||||||
|
for (index in 0 until content.count) if (isEncryptedMessage(content.getBodyPart(index))) return true
|
||||||
|
} else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
||||||
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
||||||
|
|
||||||
@@ -784,7 +868,7 @@ internal object AndroidMailService {
|
|||||||
|
|
||||||
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
|
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
|
||||||
val session = Session.getInstance(imapProperties(account), credentials(account))
|
val session = Session.getInstance(imapProperties(account), credentials(account))
|
||||||
val store = session.getStore("imap")
|
val store = session.getStore(imapProtocol(account))
|
||||||
try {
|
try {
|
||||||
store.connect(
|
store.connect(
|
||||||
account.optString("imapHost"),
|
account.optString("imapHost"),
|
||||||
@@ -806,29 +890,20 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun imapProperties(account: JSONObject) = Properties().apply {
|
private fun imapProperties(account: JSONObject) = Properties().apply {
|
||||||
setProperty("mail.store.protocol", "imap")
|
putAll(AndroidMailTransport.imapProperties(MailServerConnection(
|
||||||
setProperty("mail.imap.host", account.optString("imapHost"))
|
account.optString("imapHost"),
|
||||||
setProperty("mail.imap.port", account.optInt("imapPort", 143).toString())
|
account.optInt("imapPort", 143),
|
||||||
setProperty("mail.imap.auth", "true")
|
account.optBoolean("imapSecure", false)
|
||||||
setProperty("mail.imap.starttls.enable", "true")
|
)))
|
||||||
setProperty("mail.imap.starttls.required", "true")
|
|
||||||
setProperty("mail.imap.ssl.checkserveridentity", "true")
|
|
||||||
setProperty("mail.imap.connectiontimeout", "20000")
|
|
||||||
setProperty("mail.imap.timeout", "30000")
|
|
||||||
setProperty("mail.imap.writetimeout", "30000")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun smtpProperties(account: JSONObject) = Properties().apply {
|
private fun imapProtocol(account: JSONObject) = if (account.optBoolean("imapSecure", false)) "imaps" else "imap"
|
||||||
setProperty("mail.smtp.host", account.optString("smtpHost"))
|
|
||||||
setProperty("mail.smtp.port", account.optInt("smtpPort", 587).toString())
|
private fun smtpProperties(account: JSONObject) = AndroidMailTransport.smtpProperties(MailServerConnection(
|
||||||
setProperty("mail.smtp.auth", "true")
|
account.optString("smtpHost"),
|
||||||
setProperty("mail.smtp.starttls.enable", "true")
|
account.optInt("smtpPort", 587),
|
||||||
setProperty("mail.smtp.starttls.required", "true")
|
account.optBoolean("smtpSecure", false)
|
||||||
setProperty("mail.smtp.ssl.checkserveridentity", "true")
|
))
|
||||||
setProperty("mail.smtp.connectiontimeout", "20000")
|
|
||||||
setProperty("mail.smtp.timeout", "30000")
|
|
||||||
setProperty("mail.smtp.writetimeout", "30000")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun displayName(account: JSONObject) =
|
private fun displayName(account: JSONObject) =
|
||||||
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
|
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.util.Properties
|
||||||
|
|
||||||
|
internal data class MailServerConnection(
|
||||||
|
val host: String,
|
||||||
|
val port: Int,
|
||||||
|
val secure: Boolean
|
||||||
|
)
|
||||||
|
|
||||||
|
internal object AndroidMailTransport {
|
||||||
|
fun imapProperties(server: MailServerConnection): Properties = Properties().apply {
|
||||||
|
val protocol = if (server.secure) "imaps" else "imap"
|
||||||
|
setProperty("mail.store.protocol", protocol)
|
||||||
|
setProperty("mail.$protocol.host", server.host)
|
||||||
|
setProperty("mail.$protocol.port", server.port.toString())
|
||||||
|
setProperty("mail.$protocol.auth", "true")
|
||||||
|
setProperty("mail.$protocol.ssl.checkserveridentity", "true")
|
||||||
|
if (server.secure) {
|
||||||
|
setProperty("mail.$protocol.ssl.enable", "true")
|
||||||
|
} else {
|
||||||
|
setProperty("mail.$protocol.starttls.enable", "true")
|
||||||
|
setProperty("mail.$protocol.starttls.required", "true")
|
||||||
|
}
|
||||||
|
setProperty("mail.$protocol.connectiontimeout", "20000")
|
||||||
|
setProperty("mail.$protocol.timeout", "30000")
|
||||||
|
setProperty("mail.$protocol.writetimeout", "30000")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun smtpProperties(server: MailServerConnection): Properties = Properties().apply {
|
||||||
|
setProperty("mail.smtp.host", server.host)
|
||||||
|
setProperty("mail.smtp.port", server.port.toString())
|
||||||
|
setProperty("mail.smtp.auth", "true")
|
||||||
|
setProperty("mail.smtp.ssl.checkserveridentity", "true")
|
||||||
|
if (server.secure) {
|
||||||
|
setProperty("mail.smtp.ssl.enable", "true")
|
||||||
|
} else {
|
||||||
|
setProperty("mail.smtp.starttls.enable", "true")
|
||||||
|
setProperty("mail.smtp.starttls.required", "true")
|
||||||
|
}
|
||||||
|
setProperty("mail.smtp.connectiontimeout", "20000")
|
||||||
|
setProperty("mail.smtp.timeout", "30000")
|
||||||
|
setProperty("mail.smtp.writetimeout", "30000")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
/** Makes native confirmations fail closed and guarantees each plugin call gets one decision. */
|
||||||
|
internal class AndroidPgpConfirmationGate(
|
||||||
|
private val showPrompt: (Prompt) -> Unit,
|
||||||
|
private val dispatch: ((() -> Unit) -> Unit)
|
||||||
|
) {
|
||||||
|
data class Prompt(
|
||||||
|
val title: String,
|
||||||
|
val message: String,
|
||||||
|
val confirmLabel: String,
|
||||||
|
val cancelLabel: String,
|
||||||
|
val confirm: () -> Unit,
|
||||||
|
val cancel: () -> Unit
|
||||||
|
)
|
||||||
|
|
||||||
|
fun request(
|
||||||
|
title: String,
|
||||||
|
message: String,
|
||||||
|
confirmLabel: String,
|
||||||
|
cancelLabel: String = "Cancel",
|
||||||
|
onConfirmed: () -> Unit,
|
||||||
|
onCancelled: () -> Unit
|
||||||
|
) {
|
||||||
|
val decided = AtomicBoolean(false)
|
||||||
|
showPrompt(
|
||||||
|
Prompt(
|
||||||
|
title = title,
|
||||||
|
message = message,
|
||||||
|
confirmLabel = confirmLabel,
|
||||||
|
cancelLabel = cancelLabel,
|
||||||
|
confirm = { if (decided.compareAndSet(false, true)) dispatch(onConfirmed) },
|
||||||
|
cancel = { if (decided.compareAndSet(false, true)) dispatch(onCancelled) }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
internal object AndroidPgpPolicy {
|
||||||
|
data class ContactKey(
|
||||||
|
val fingerprint: String,
|
||||||
|
val emails: List<String>,
|
||||||
|
val trust: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class RecipientKey(
|
||||||
|
val email: String,
|
||||||
|
val fingerprint: String
|
||||||
|
)
|
||||||
|
|
||||||
|
private val trustOrder = mapOf("unknown" to 0, "trusted" to 1, "verified" to 2)
|
||||||
|
|
||||||
|
fun storeChangeWarning(previous: List<ContactKey>, candidate: List<ContactKey>): String? {
|
||||||
|
val oldByFingerprint = previous.associateBy { it.fingerprint.uppercase(Locale.ROOT) }
|
||||||
|
val warnings = ArrayList<String>()
|
||||||
|
|
||||||
|
for (current in candidate) {
|
||||||
|
val fingerprint = current.fingerprint.uppercase(Locale.ROOT)
|
||||||
|
val old = oldByFingerprint[fingerprint]
|
||||||
|
if (old != null && (trustOrder[current.trust] ?: 0) > (trustOrder[old.trust] ?: 0)) {
|
||||||
|
warnings.add(
|
||||||
|
"Trust change for ${safeLabel(current.emails)}\n" +
|
||||||
|
"Fingerprint: ${formatFingerprint(fingerprint)}\n" +
|
||||||
|
"New trust: ${current.trust}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (old == null) {
|
||||||
|
val newEmails = current.emails.map { it.lowercase(Locale.ROOT) }.toSet()
|
||||||
|
for (previousKey in previous) {
|
||||||
|
val oldFingerprint = previousKey.fingerprint.uppercase(Locale.ROOT)
|
||||||
|
val overlaps = previousKey.emails.any { it.lowercase(Locale.ROOT) in newEmails }
|
||||||
|
if (overlaps && oldFingerprint != fingerprint) {
|
||||||
|
warnings.add(
|
||||||
|
"A different key is already stored for ${safeLabel(current.emails)}.\n" +
|
||||||
|
"New fingerprint: ${formatFingerprint(fingerprint)}\n" +
|
||||||
|
"Existing fingerprint: ${formatFingerprint(oldFingerprint)}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return warnings.take(MAX_WARNINGS).takeIf { it.isNotEmpty() }?.joinToString("\n\n")?.let {
|
||||||
|
"$it\n\nOnly confirm trust or a replacement after comparing fingerprints with the key owner through another channel."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun plaintextSendWarning(
|
||||||
|
recipients: List<String>,
|
||||||
|
availableKeys: List<RecipientKey>,
|
||||||
|
encryptionWasRequested: Boolean
|
||||||
|
): String? {
|
||||||
|
val uniqueRecipients = recipients.map { it.trim().lowercase(Locale.ROOT) }.filter(String::isNotBlank).distinct()
|
||||||
|
if (uniqueRecipients.isEmpty()) return null
|
||||||
|
val matchedKeys = availableKeys.filter { key -> key.email.trim().lowercase(Locale.ROOT) in uniqueRecipients }
|
||||||
|
if (!encryptionWasRequested && matchedKeys.isEmpty()) return null
|
||||||
|
|
||||||
|
val recipientLines = uniqueRecipients.take(MAX_RECIPIENTS).map { email ->
|
||||||
|
val fingerprints = matchedKeys.filter { it.email.trim().equals(email, ignoreCase = true) }
|
||||||
|
.map { formatFingerprint(it.fingerprint.uppercase()) }.distinct()
|
||||||
|
if (fingerprints.isEmpty()) "$email — no key stored" else "$email\n${fingerprints.joinToString("\n")}"
|
||||||
|
}.joinToString("\n\n")
|
||||||
|
val prefix = if (encryptionWasRequested) {
|
||||||
|
"OpenPGP was requested, but this message will be sent in plaintext."
|
||||||
|
} else {
|
||||||
|
"A stored OpenPGP key is available for at least one recipient."
|
||||||
|
}
|
||||||
|
return "$prefix\n\nRecipients and stored key fingerprints:\n$recipientLines\n\n" +
|
||||||
|
"The message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun safeLabel(values: List<String>): String =
|
||||||
|
values.joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" }
|
||||||
|
|
||||||
|
private fun formatFingerprint(value: String): String = value.chunked(4).joinToString(" ").take(200)
|
||||||
|
|
||||||
|
private const val MAX_WARNINGS = 6
|
||||||
|
private const val MAX_RECIPIENTS = 10
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
internal object AndroidVaultKeyPolicy {
|
||||||
|
fun shouldCreateKey(hasEncryptedData: Boolean): Boolean = !hasEncryptedData
|
||||||
|
|
||||||
|
const val MISSING_KEY_MESSAGE =
|
||||||
|
"The Android Keystore key for saved app data is missing. Existing encrypted data was not reset or replaced."
|
||||||
|
}
|
||||||
@@ -16,6 +16,7 @@ import java.util.Locale
|
|||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
import javax.mail.internet.InternetAddress
|
||||||
|
|
||||||
@CapacitorPlugin(name = "EpMail")
|
@CapacitorPlugin(name = "EpMail")
|
||||||
class EpMailPlugin : Plugin() {
|
class EpMailPlugin : Plugin() {
|
||||||
@@ -37,11 +38,20 @@ class EpMailPlugin : Plugin() {
|
|||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
context.registerReceiver(receiver, filter)
|
context.registerReceiver(receiver, filter)
|
||||||
}
|
}
|
||||||
MailIdleService.start(context)
|
ensureVaultAvailableAndStartSync()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun handleOnResume() {
|
override fun handleOnResume() {
|
||||||
|
ensureVaultAvailableAndStartSync()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureVaultAvailableAndStartSync() {
|
||||||
|
try {
|
||||||
|
AndroidAccountVault.read()
|
||||||
MailIdleService.start(context)
|
MailIdleService.start(context)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
android.util.Log.e("EpMailStorage", "Secure local storage is unavailable (${error.javaClass.simpleName})")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun handleOnDestroy() {
|
override fun handleOnDestroy() {
|
||||||
@@ -56,6 +66,160 @@ class EpMailPlugin : Plugin() {
|
|||||||
call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME))
|
call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun getNotificationPrivacy(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
call.resolve(JSObject().put("showDetails", AndroidAccountVault.notificationDetailsEnabled()))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not read notification privacy settings.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun setNotificationDetails(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val enabled = call.getBoolean("enabled")
|
||||||
|
?: throw IllegalArgumentException("Choose whether notifications may show details.")
|
||||||
|
AndroidAccountVault.setNotificationDetailsEnabled(enabled)
|
||||||
|
call.resolve(JSObject().put("showDetails", enabled))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save notification privacy settings.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun getAppLockSettings(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
||||||
|
call.resolve(JSObject()
|
||||||
|
.put("enabled", AndroidAccountVault.appLockEnabled())
|
||||||
|
.put("deviceSecure", keyguard.isDeviceSecure))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not read app-lock settings.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun setAppLockEnabled(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val enabled = call.getBoolean("enabled")
|
||||||
|
?: throw IllegalArgumentException("Choose whether to lock ep-mail when you leave it.")
|
||||||
|
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
||||||
|
require(!enabled || keyguard.isDeviceSecure) {
|
||||||
|
"Set a screen lock in Android Settings before enabling the app lock."
|
||||||
|
}
|
||||||
|
AndroidAccountVault.setAppLockEnabled(enabled)
|
||||||
|
(activity as? MainActivity)?.onAppLockSettingChanged(enabled)
|
||||||
|
call.resolve(JSObject().put("enabled", enabled).put("deviceSecure", keyguard.isDeviceSecure))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save app-lock settings.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun pgpLoadStore(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
call.resolve(AndroidAccountVault.pgpStore().toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not load the Android OpenPGP key store.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun pgpSaveStore(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.")
|
||||||
|
val next = JSONObject(candidate.toString())
|
||||||
|
val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next)
|
||||||
|
if (warning == null) {
|
||||||
|
AndroidAccountVault.savePgpStore(next)
|
||||||
|
call.resolve(JSObject().put("ok", true))
|
||||||
|
} else {
|
||||||
|
showPgpConfirmation(
|
||||||
|
title = "Confirm OpenPGP key changes",
|
||||||
|
message = warning,
|
||||||
|
confirmLabel = "Confirm changes",
|
||||||
|
onConfirmed = {
|
||||||
|
try {
|
||||||
|
AndroidAccountVault.savePgpStore(next)
|
||||||
|
call.resolve(JSObject().put("ok", true))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onCancelled = { call.reject("OpenPGP key change cancelled.") }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? {
|
||||||
|
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
|
||||||
|
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
||||||
|
return AndroidPgpPolicy.storeChangeWarning(pgpContacts(oldContacts), pgpContacts(newContacts))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pgpContacts(values: JSONArray): List<AndroidPgpPolicy.ContactKey> =
|
||||||
|
(0 until values.length()).mapNotNull { values.optJSONObject(it) }.map { contact ->
|
||||||
|
AndroidPgpPolicy.ContactKey(
|
||||||
|
fingerprint = contact.optString("fingerprint"),
|
||||||
|
emails = jsonStrings(contact.optJSONArray("emails")),
|
||||||
|
trust = contact.optString("trust")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun jsonStrings(values: JSONArray?): List<String> =
|
||||||
|
values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
||||||
|
|
||||||
|
private fun showPgpConfirmation(
|
||||||
|
title: String,
|
||||||
|
message: String,
|
||||||
|
confirmLabel: String,
|
||||||
|
onConfirmed: () -> Unit,
|
||||||
|
onCancelled: () -> Unit
|
||||||
|
) {
|
||||||
|
val gate = AndroidPgpConfirmationGate(
|
||||||
|
showPrompt = { prompt ->
|
||||||
|
val host = activity
|
||||||
|
host.runOnUiThread {
|
||||||
|
AlertDialog.Builder(host)
|
||||||
|
.setTitle(prompt.title)
|
||||||
|
.setMessage(prompt.message)
|
||||||
|
.setNegativeButton(prompt.cancelLabel) { _, _ -> prompt.cancel() }
|
||||||
|
.setPositiveButton(prompt.confirmLabel) { _, _ -> prompt.confirm() }
|
||||||
|
.setOnCancelListener { prompt.cancel() }
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dispatch = { action -> bridge.execute(action) }
|
||||||
|
)
|
||||||
|
gate.request(title, message, confirmLabel, onConfirmed = onConfirmed, onCancelled = onCancelled)
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun pgpGetMessageSource(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val account = AndroidAccountVault.account()
|
||||||
|
?: throw IllegalStateException("Add a mail account before opening messages.")
|
||||||
|
val folder = call.getString("folder") ?: "Inbox"
|
||||||
|
val uid = call.getLong("uid") ?: 0L
|
||||||
|
call.resolve(AndroidMailService.pgpMessageSource(account, folder, uid).toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not load the encrypted message.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun savePgpAttachment(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
call.resolve(AndroidMailService.savePgpAttachment(context, JSONObject(call.data.toString())).toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save the decrypted attachment.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun getAccount(call: PluginCall) {
|
fun getAccount(call: PluginCall) {
|
||||||
val account = AndroidAccountVault.account()
|
val account = AndroidAccountVault.account()
|
||||||
@@ -292,6 +456,26 @@ class EpMailPlugin : Plugin() {
|
|||||||
val input = JSONObject(call.data.toString()).apply {
|
val input = JSONObject(call.data.toString()).apply {
|
||||||
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
|
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
|
||||||
}
|
}
|
||||||
|
val warning = try { plaintextSendWarning(input) } catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not check the OpenPGP send policy.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (warning == null) {
|
||||||
|
sendPrepared(call, input)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
showPgpConfirmation(
|
||||||
|
title = "Send without OpenPGP encryption?",
|
||||||
|
message = warning,
|
||||||
|
confirmLabel = "Send plaintext",
|
||||||
|
onConfirmed = { sendPrepared(call, input) },
|
||||||
|
onCancelled = {
|
||||||
|
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendPrepared(call: PluginCall, input: JSONObject) {
|
||||||
try {
|
try {
|
||||||
val account = AndroidAccountVault.account()
|
val account = AndroidAccountVault.account()
|
||||||
?: throw IllegalStateException("Add a mail account before sending.")
|
?: throw IllegalStateException("Add a mail account before sending.")
|
||||||
@@ -308,6 +492,33 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun plaintextSendWarning(input: JSONObject): String? {
|
||||||
|
if (input.optString("rawBase64").isNotBlank()) return null
|
||||||
|
val recipients = (listOf(input.optString("to"), input.optString("cc"))
|
||||||
|
.filter(String::isNotBlank)
|
||||||
|
.flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } })
|
||||||
|
.distinct()
|
||||||
|
val data = AndroidAccountVault.pgpStore()
|
||||||
|
val contacts = data.optJSONArray("contacts") ?: JSONArray()
|
||||||
|
val keys = data.optJSONArray("keys") ?: JSONArray()
|
||||||
|
val available = ArrayList<AndroidPgpPolicy.RecipientKey>()
|
||||||
|
for (address in recipients) {
|
||||||
|
for (index in 0 until contacts.length()) {
|
||||||
|
val contact = contacts.optJSONObject(index) ?: continue
|
||||||
|
if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) {
|
||||||
|
available.add(AndroidPgpPolicy.RecipientKey(address, contact.optString("fingerprint")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (index in 0 until keys.length()) {
|
||||||
|
val key = keys.optJSONObject(index) ?: continue
|
||||||
|
if (key.optString("email").equals(address, true)) {
|
||||||
|
available.add(AndroidPgpPolicy.RecipientKey(address, key.optString("fingerprint")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return AndroidPgpPolicy.plaintextSendWarning(recipients, available, input.optBoolean("pgpRequested"))
|
||||||
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun listDrafts(call: PluginCall) {
|
fun listDrafts(call: PluginCall) {
|
||||||
try {
|
try {
|
||||||
@@ -458,9 +669,14 @@ class EpMailPlugin : Plugin() {
|
|||||||
val displayName = input.optString("displayName").trim().take(80)
|
val displayName = input.optString("displayName").trim().take(80)
|
||||||
val imapHost = input.optString("imapHost").trim()
|
val imapHost = input.optString("imapHost").trim()
|
||||||
val smtpHost = input.optString("smtpHost").trim()
|
val smtpHost = input.optString("smtpHost").trim()
|
||||||
|
val imapPort = input.optInt("imapPort", 143)
|
||||||
|
val smtpPort = input.optInt("smtpPort", 587)
|
||||||
require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) {
|
require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) {
|
||||||
"Enter a valid email, account display name, password, and both mail server names."
|
"Enter a valid email, account display name, password, and both mail server names."
|
||||||
}
|
}
|
||||||
|
require(imapPort in 1..65535 && smtpPort in 1..65535) {
|
||||||
|
"Enter valid IMAP and SMTP ports (1–65535)."
|
||||||
|
}
|
||||||
return JSONObject()
|
return JSONObject()
|
||||||
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
|
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
|
||||||
.put("email", email)
|
.put("email", email)
|
||||||
@@ -474,8 +690,10 @@ class EpMailPlugin : Plugin() {
|
|||||||
require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." }
|
require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." }
|
||||||
})
|
})
|
||||||
.put("rules", normalizeRules(input.optJSONArray("rules")))
|
.put("rules", normalizeRules(input.optJSONArray("rules")))
|
||||||
.put("imapPort", input.optInt("imapPort", 143))
|
.put("imapPort", imapPort)
|
||||||
.put("smtpPort", input.optInt("smtpPort", 587))
|
.put("smtpPort", smtpPort)
|
||||||
|
.put("imapSecure", input.optBoolean("imapSecure", false))
|
||||||
|
.put("smtpSecure", input.optBoolean("smtpSecure", false))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun normalizeRules(input: JSONArray?): JSONArray {
|
private fun normalizeRules(input: JSONArray?): JSONArray {
|
||||||
|
|||||||
@@ -136,6 +136,7 @@ class MailIdleService : Service() {
|
|||||||
.setContentIntent(appPendingIntent())
|
.setContentIntent(appPendingIntent())
|
||||||
.setOngoing(true)
|
.setOngoing(true)
|
||||||
.setPriority(NotificationCompat.PRIORITY_LOW)
|
.setPriority(NotificationCompat.PRIORITY_LOW)
|
||||||
|
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
private fun appPendingIntent(): PendingIntent {
|
private fun appPendingIntent(): PendingIntent {
|
||||||
@@ -219,13 +220,20 @@ class MailIdleService : Service() {
|
|||||||
appContext, 0, launchIntent,
|
appContext, 0, launchIntent,
|
||||||
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
|
||||||
)
|
)
|
||||||
val title = if (count == 1) "New mail" else "$count new messages"
|
val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false)
|
||||||
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||||
.setContentTitle(title)
|
.setContentTitle("New mail")
|
||||||
.setContentText("Open ep-mail to check your inbox")
|
.setContentText(NotificationPrivacyPolicy.newMailText(showDetails, email, count))
|
||||||
.setAutoCancel(true)
|
.setAutoCancel(true)
|
||||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||||
|
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||||
|
.setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||||
|
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||||
|
.setContentTitle("ep-mail")
|
||||||
|
.setContentText("New mail")
|
||||||
|
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||||
|
.build())
|
||||||
.setContentIntent(pendingIntent)
|
.setContentIntent(pendingIntent)
|
||||||
.build()
|
.build()
|
||||||
try {
|
try {
|
||||||
@@ -256,12 +264,20 @@ class MailIdleService : Service() {
|
|||||||
NotificationManager.IMPORTANCE_DEFAULT
|
NotificationManager.IMPORTANCE_DEFAULT
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
val showDetails = runCatching { AndroidAccountVault.notificationDetailsEnabled() }.getOrDefault(false)
|
||||||
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
val notification = NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||||
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||||
.setContentTitle("Mail reminder")
|
.setContentTitle("Mail reminder")
|
||||||
.setContentText("A snoozed message is due")
|
.setContentText(NotificationPrivacyPolicy.reminderText(showDetails, reminder.optString("subject")))
|
||||||
.setAutoCancel(true)
|
.setAutoCancel(true)
|
||||||
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
|
||||||
|
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
|
||||||
|
.setPublicVersion(NotificationCompat.Builder(appContext, MAIL_CHANNEL_ID)
|
||||||
|
.setSmallIcon(android.R.drawable.ic_dialog_email)
|
||||||
|
.setContentTitle("ep-mail")
|
||||||
|
.setContentText("A mail reminder is due")
|
||||||
|
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
|
||||||
|
.build())
|
||||||
.setContentIntent(appPendingIntentFor(appContext))
|
.setContentIntent(appPendingIntentFor(appContext))
|
||||||
.build()
|
.build()
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,19 +1,296 @@
|
|||||||
package studio.daybreak.mail;
|
package studio.daybreak.mail;
|
||||||
|
|
||||||
import android.Manifest;
|
import android.Manifest;
|
||||||
|
import android.app.KeyguardManager;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
import android.content.pm.PackageManager;
|
import android.content.pm.PackageManager;
|
||||||
|
import android.graphics.Color;
|
||||||
|
import android.net.Uri;
|
||||||
import android.os.Build;
|
import android.os.Build;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
|
import android.view.Gravity;
|
||||||
|
import android.view.View;
|
||||||
|
import android.view.ViewGroup;
|
||||||
|
import android.view.WindowManager;
|
||||||
|
import android.webkit.WebView;
|
||||||
|
import android.widget.Button;
|
||||||
|
import android.widget.FrameLayout;
|
||||||
|
import android.widget.LinearLayout;
|
||||||
|
import android.widget.TextView;
|
||||||
import androidx.core.app.ActivityCompat;
|
import androidx.core.app.ActivityCompat;
|
||||||
import com.getcapacitor.BridgeActivity;
|
import com.getcapacitor.BridgeActivity;
|
||||||
|
|
||||||
public class MainActivity extends BridgeActivity {
|
public class MainActivity extends BridgeActivity {
|
||||||
|
private static final int UNLOCK_REQUEST_CODE = 705;
|
||||||
|
private FrameLayout appLockOverlay;
|
||||||
|
private TextView appLockMessage;
|
||||||
|
private Button appLockButton;
|
||||||
|
private boolean appLocked;
|
||||||
|
private boolean awaitingUnlockResult;
|
||||||
|
private boolean activityResumed;
|
||||||
|
private boolean vaultRecoveryRequired;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCreate(Bundle savedInstanceState) {
|
public void onCreate(Bundle savedInstanceState) {
|
||||||
super.onCreate(savedInstanceState);
|
|
||||||
registerPlugin(EpMailPlugin.class);
|
registerPlugin(EpMailPlugin.class);
|
||||||
|
super.onCreate(savedInstanceState);
|
||||||
|
hardenWebView();
|
||||||
|
AndroidAccountVault.INSTANCE.initialize(getApplicationContext());
|
||||||
|
try {
|
||||||
|
AndroidAccountVault.INSTANCE.read();
|
||||||
|
} catch (Exception storageError) {
|
||||||
|
vaultRecoveryRequired = true;
|
||||||
|
createVaultRecoveryOverlay();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
createAppLockOverlay();
|
||||||
|
if (isAppLockEnabled()) lockWebView();
|
||||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||||
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
|
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onResume() {
|
||||||
|
super.onResume();
|
||||||
|
if (vaultRecoveryRequired) return;
|
||||||
|
activityResumed = true;
|
||||||
|
if (isAppLockEnabled() && appLocked) {
|
||||||
|
lockWebView();
|
||||||
|
configureUnlockButton();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onPause() {
|
||||||
|
activityResumed = false;
|
||||||
|
if (!vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
|
||||||
|
super.onPause();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||||
|
super.onActivityResult(requestCode, resultCode, data);
|
||||||
|
if (requestCode != UNLOCK_REQUEST_CODE) return;
|
||||||
|
awaitingUnlockResult = false;
|
||||||
|
if (resultCode == RESULT_OK && isAppLockEnabled()) unlockWebView(true);
|
||||||
|
else updateAppLockMessage("Unlock with your Android screen lock to view mail.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void onAppLockSettingChanged(boolean enabled) {
|
||||||
|
runOnUiThread(() -> {
|
||||||
|
if (!enabled) {
|
||||||
|
awaitingUnlockResult = false;
|
||||||
|
unlockWebView(false);
|
||||||
|
} else if (activityResumed) {
|
||||||
|
appLocked = false;
|
||||||
|
} else {
|
||||||
|
lockWebView();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isAppLockEnabled() {
|
||||||
|
try {
|
||||||
|
return AndroidAccountVault.INSTANCE.appLockEnabled();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// If the encrypted setting cannot be read, prefer locking over exposing stale UI.
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void hardenWebView() {
|
||||||
|
if (getBridge() == null || getBridge().getWebView() == null) return;
|
||||||
|
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
|
||||||
|
WebView webView = getBridge().getWebView();
|
||||||
|
android.webkit.WebSettings settings = webView.getSettings();
|
||||||
|
settings.setAllowFileAccess(false);
|
||||||
|
settings.setAllowContentAccess(false);
|
||||||
|
settings.setAllowFileAccessFromFileURLs(false);
|
||||||
|
settings.setAllowUniversalAccessFromFileURLs(false);
|
||||||
|
settings.setGeolocationEnabled(false);
|
||||||
|
settings.setJavaScriptCanOpenWindowsAutomatically(false);
|
||||||
|
settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createVaultRecoveryOverlay() {
|
||||||
|
View content = findViewById(android.R.id.content);
|
||||||
|
if (!(content instanceof FrameLayout)) return;
|
||||||
|
FrameLayout overlay = new FrameLayout(this);
|
||||||
|
overlay.setBackgroundColor(Color.rgb(25, 21, 18));
|
||||||
|
overlay.setClickable(true);
|
||||||
|
overlay.setFocusable(true);
|
||||||
|
|
||||||
|
LinearLayout panel = new LinearLayout(this);
|
||||||
|
panel.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
panel.setGravity(Gravity.CENTER);
|
||||||
|
panel.setPadding(dp(28), dp(28), dp(28), dp(28));
|
||||||
|
|
||||||
|
TextView title = new TextView(this);
|
||||||
|
title.setText("Saved data could not be opened");
|
||||||
|
title.setTextColor(Color.rgb(238, 230, 215));
|
||||||
|
title.setTextSize(21);
|
||||||
|
title.setGravity(Gravity.CENTER);
|
||||||
|
panel.addView(title, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||||
|
|
||||||
|
TextView details = new TextView(this);
|
||||||
|
details.setText("ep-mail could not decrypt its saved local data. It has not been reset or replaced. Try restoring the same device/app state if available. If you cannot recover it, open Android App info and clear ep-mail data to start fresh; this permanently removes saved accounts, cached mail, drafts, queued sends, DAV settings, and OpenPGP keys. Attachments already saved to Downloads remain there.");
|
||||||
|
details.setTextColor(Color.rgb(210, 199, 181));
|
||||||
|
details.setTextSize(14);
|
||||||
|
details.setGravity(Gravity.CENTER);
|
||||||
|
LinearLayout.LayoutParams detailsParams = new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
detailsParams.topMargin = dp(16);
|
||||||
|
panel.addView(details, detailsParams);
|
||||||
|
|
||||||
|
Button settingsButton = new Button(this);
|
||||||
|
settingsButton.setText("Open Android App info");
|
||||||
|
settingsButton.setOnClickListener(view -> {
|
||||||
|
try {
|
||||||
|
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||||
|
Uri.parse("package:" + getPackageName())));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// Keep the recovery instructions visible if Settings cannot be launched.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
buttonParams.gravity = Gravity.CENTER_HORIZONTAL;
|
||||||
|
buttonParams.topMargin = dp(24);
|
||||||
|
panel.addView(settingsButton, buttonParams);
|
||||||
|
|
||||||
|
overlay.addView(panel, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
|
||||||
|
((FrameLayout) content).addView(overlay, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||||
|
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
if (getBridge() != null && getBridge().getWebView() != null) {
|
||||||
|
getBridge().getWebView().getSettings().setJavaScriptEnabled(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createAppLockOverlay() {
|
||||||
|
View content = findViewById(android.R.id.content);
|
||||||
|
if (!(content instanceof FrameLayout)) return;
|
||||||
|
|
||||||
|
appLockOverlay = new FrameLayout(this);
|
||||||
|
appLockOverlay.setBackgroundColor(Color.rgb(25, 21, 18));
|
||||||
|
appLockOverlay.setClickable(true);
|
||||||
|
appLockOverlay.setFocusable(true);
|
||||||
|
|
||||||
|
LinearLayout panel = new LinearLayout(this);
|
||||||
|
panel.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
panel.setGravity(Gravity.CENTER);
|
||||||
|
panel.setPadding(dp(28), dp(28), dp(28), dp(28));
|
||||||
|
|
||||||
|
TextView title = new TextView(this);
|
||||||
|
title.setText("ep-mail is locked");
|
||||||
|
title.setTextColor(Color.rgb(238, 230, 215));
|
||||||
|
title.setTextSize(22);
|
||||||
|
title.setGravity(Gravity.CENTER);
|
||||||
|
panel.addView(title, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||||
|
|
||||||
|
appLockMessage = new TextView(this);
|
||||||
|
appLockMessage.setText("Unlock with your Android screen lock to view mail.");
|
||||||
|
appLockMessage.setTextColor(Color.rgb(185, 171, 151));
|
||||||
|
appLockMessage.setTextSize(15);
|
||||||
|
appLockMessage.setGravity(Gravity.CENTER);
|
||||||
|
LinearLayout.LayoutParams messageParams = new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
messageParams.topMargin = dp(12);
|
||||||
|
panel.addView(appLockMessage, messageParams);
|
||||||
|
|
||||||
|
appLockButton = new Button(this);
|
||||||
|
appLockButton.setText("Unlock");
|
||||||
|
appLockButton.setOnClickListener(view -> requestDeviceUnlock());
|
||||||
|
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
buttonParams.gravity = Gravity.CENTER_HORIZONTAL;
|
||||||
|
buttonParams.topMargin = dp(24);
|
||||||
|
panel.addView(appLockButton, buttonParams);
|
||||||
|
|
||||||
|
FrameLayout.LayoutParams panelParams = new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
|
||||||
|
appLockOverlay.addView(panel, panelParams);
|
||||||
|
appLockOverlay.setVisibility(View.GONE);
|
||||||
|
((FrameLayout) content).addView(appLockOverlay, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requestDeviceUnlock() {
|
||||||
|
if (awaitingUnlockResult) return;
|
||||||
|
KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
|
||||||
|
if (keyguard == null || !keyguard.isDeviceSecure()) {
|
||||||
|
updateAppLockMessage("Set a PIN, pattern, or password in Android Settings to unlock ep-mail.");
|
||||||
|
configureUnlockButton();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
configureUnlockButton();
|
||||||
|
Intent confirmIntent = keyguard.createConfirmDeviceCredentialIntent(
|
||||||
|
"Unlock ep-mail",
|
||||||
|
"Confirm your Android screen lock to view mail."
|
||||||
|
);
|
||||||
|
if (confirmIntent == null) {
|
||||||
|
updateAppLockMessage("Android could not start screen-lock verification. Try again after unlocking your device.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
awaitingUnlockResult = true;
|
||||||
|
try {
|
||||||
|
startActivityForResult(confirmIntent, UNLOCK_REQUEST_CODE);
|
||||||
|
} catch (Exception error) {
|
||||||
|
awaitingUnlockResult = false;
|
||||||
|
updateAppLockMessage("Could not start Android screen-lock verification. Try again.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void configureUnlockButton() {
|
||||||
|
if (appLockButton == null) return;
|
||||||
|
KeyguardManager keyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
|
||||||
|
if (keyguard != null && keyguard.isDeviceSecure()) {
|
||||||
|
appLockButton.setText("Unlock");
|
||||||
|
appLockButton.setOnClickListener(view -> requestDeviceUnlock());
|
||||||
|
} else {
|
||||||
|
appLockButton.setText("Open security settings");
|
||||||
|
appLockButton.setOnClickListener(view -> startActivity(
|
||||||
|
new Intent(android.provider.Settings.ACTION_SECURITY_SETTINGS)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void lockWebView() {
|
||||||
|
appLocked = true;
|
||||||
|
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE);
|
||||||
|
if (getBridge() != null) {
|
||||||
|
WebView webView = getBridge().getWebView();
|
||||||
|
webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
|
||||||
|
webView.getSettings().setJavaScriptEnabled(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void unlockWebView(boolean reload) {
|
||||||
|
appLocked = false;
|
||||||
|
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
if (getBridge() != null) {
|
||||||
|
WebView webView = getBridge().getWebView();
|
||||||
|
webView.getSettings().setJavaScriptEnabled(true);
|
||||||
|
webView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO);
|
||||||
|
if (reload) webView.reload();
|
||||||
|
}
|
||||||
|
if (appLockOverlay != null) appLockOverlay.setVisibility(View.GONE);
|
||||||
|
if (appLockButton != null) {
|
||||||
|
appLockButton.setText("Unlock");
|
||||||
|
appLockButton.setOnClickListener(view -> requestDeviceUnlock());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateAppLockMessage(String message) {
|
||||||
|
if (appLockMessage != null) appLockMessage.setText(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private int dp(int value) {
|
||||||
|
return Math.round(value * getResources().getDisplayMetrics().density);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
internal object NotificationPrivacyPolicy {
|
||||||
|
const val DEFAULT_SHOW_DETAILS = false
|
||||||
|
|
||||||
|
fun newMailText(showDetails: Boolean, email: String, count: Int): String =
|
||||||
|
if (showDetails) {
|
||||||
|
if (count == 1) email else "$count new messages · $email"
|
||||||
|
} else {
|
||||||
|
"Open ep-mail to check your inbox"
|
||||||
|
}
|
||||||
|
|
||||||
|
fun reminderText(showDetails: Boolean, subject: String): String =
|
||||||
|
if (showDetails && subject.isNotBlank()) subject else "A snoozed message is due"
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidMailTransportTest {
|
||||||
|
@Test
|
||||||
|
fun imapUsesRequiredStarttlsWhenImplicitTlsIsOff() {
|
||||||
|
val properties = AndroidMailTransport.imapProperties(
|
||||||
|
MailServerConnection("imap.example.test", 143, false)
|
||||||
|
)
|
||||||
|
assertEquals("imap", properties.getProperty("mail.store.protocol"))
|
||||||
|
assertEquals("true", properties.getProperty("mail.imap.starttls.enable"))
|
||||||
|
assertEquals("true", properties.getProperty("mail.imap.starttls.required"))
|
||||||
|
assertEquals("true", properties.getProperty("mail.imap.ssl.checkserveridentity"))
|
||||||
|
assertNull(properties.getProperty("mail.imap.ssl.trust"))
|
||||||
|
assertNull(properties.getProperty("mail.imap.ssl.socketFactory"))
|
||||||
|
assertNull(properties.getProperty("mail.imap.ssl.enable"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun imapUsesImplicitTlsForSecurePort() {
|
||||||
|
val properties = AndroidMailTransport.imapProperties(
|
||||||
|
MailServerConnection("imap.example.test", 993, true)
|
||||||
|
)
|
||||||
|
assertEquals("imaps", properties.getProperty("mail.store.protocol"))
|
||||||
|
assertEquals("true", properties.getProperty("mail.imaps.ssl.enable"))
|
||||||
|
assertEquals("true", properties.getProperty("mail.imaps.ssl.checkserveridentity"))
|
||||||
|
assertNull(properties.getProperty("mail.imaps.ssl.trust"))
|
||||||
|
assertNull(properties.getProperty("mail.imaps.ssl.socketFactory"))
|
||||||
|
assertNull(properties.getProperty("mail.imaps.starttls.required"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun smtpSupportsStarttlsAndImplicitTlsWithoutDowngrade() {
|
||||||
|
val startTls = AndroidMailTransport.smtpProperties(
|
||||||
|
MailServerConnection("smtp.example.test", 587, false)
|
||||||
|
)
|
||||||
|
assertEquals("true", startTls.getProperty("mail.smtp.starttls.enable"))
|
||||||
|
assertEquals("true", startTls.getProperty("mail.smtp.starttls.required"))
|
||||||
|
assertNull(startTls.getProperty("mail.smtp.ssl.trust"))
|
||||||
|
assertNull(startTls.getProperty("mail.smtp.ssl.socketFactory"))
|
||||||
|
|
||||||
|
val implicitTls = AndroidMailTransport.smtpProperties(
|
||||||
|
MailServerConnection("smtp.example.test", 465, true)
|
||||||
|
)
|
||||||
|
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.enable"))
|
||||||
|
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.checkserveridentity"))
|
||||||
|
assertNull(implicitTls.getProperty("mail.smtp.ssl.trust"))
|
||||||
|
assertNull(implicitTls.getProperty("mail.smtp.ssl.socketFactory"))
|
||||||
|
assertNull(implicitTls.getProperty("mail.smtp.starttls.required"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidPgpConfirmationGateTest {
|
||||||
|
@Test
|
||||||
|
fun cancelDoesNotRunProtectedActionAndCannotBeOverriddenLater() {
|
||||||
|
var prompt: AndroidPgpConfirmationGate.Prompt? = null
|
||||||
|
var protectedActionCount = 0
|
||||||
|
var cancelCount = 0
|
||||||
|
val gate = AndroidPgpConfirmationGate(
|
||||||
|
showPrompt = { prompt = it },
|
||||||
|
dispatch = { action -> action() }
|
||||||
|
)
|
||||||
|
|
||||||
|
gate.request(
|
||||||
|
title = "Confirm key change",
|
||||||
|
message = "Check the fingerprint",
|
||||||
|
confirmLabel = "Confirm",
|
||||||
|
onConfirmed = { protectedActionCount += 1 },
|
||||||
|
onCancelled = { cancelCount += 1 }
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(0, protectedActionCount)
|
||||||
|
assertEquals(0, cancelCount)
|
||||||
|
assertNotNull(prompt)
|
||||||
|
prompt!!.cancel()
|
||||||
|
prompt!!.confirm()
|
||||||
|
prompt!!.cancel()
|
||||||
|
|
||||||
|
assertEquals(0, protectedActionCount)
|
||||||
|
assertEquals(1, cancelCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun confirmRunsProtectedActionExactlyOnce() {
|
||||||
|
var prompt: AndroidPgpConfirmationGate.Prompt? = null
|
||||||
|
var protectedActionCount = 0
|
||||||
|
var cancelCount = 0
|
||||||
|
val gate = AndroidPgpConfirmationGate(
|
||||||
|
showPrompt = { prompt = it },
|
||||||
|
dispatch = { action -> action() }
|
||||||
|
)
|
||||||
|
|
||||||
|
gate.request(
|
||||||
|
title = "Send plaintext?",
|
||||||
|
message = "The message will not be encrypted",
|
||||||
|
confirmLabel = "Send plaintext",
|
||||||
|
onConfirmed = { protectedActionCount += 1 },
|
||||||
|
onCancelled = { cancelCount += 1 }
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNotNull(prompt)
|
||||||
|
assertEquals("Send plaintext", prompt!!.confirmLabel)
|
||||||
|
prompt!!.confirm()
|
||||||
|
prompt!!.confirm()
|
||||||
|
prompt!!.cancel()
|
||||||
|
|
||||||
|
assertEquals(1, protectedActionCount)
|
||||||
|
assertEquals(0, cancelCount)
|
||||||
|
assertTrue(prompt!!.message.contains("not be encrypted"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidPgpPolicyTest {
|
||||||
|
private val firstFingerprint = "0123456789ABCDEF0123456789ABCDEF01234567"
|
||||||
|
private val secondFingerprint = "89ABCDEF0123456789ABCDEF0123456789ABCDEF"
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun unchangedOrLoweredTrustDoesNotPrompt() {
|
||||||
|
val verified = contact(firstFingerprint, "alice@example.test", "verified")
|
||||||
|
assertNull(AndroidPgpPolicy.storeChangeWarning(listOf(verified), listOf(verified)))
|
||||||
|
assertNull(AndroidPgpPolicy.storeChangeWarning(listOf(verified), listOf(verified.copy(trust = "unknown"))))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun trustElevationRequiresTheFullFingerprintWarning() {
|
||||||
|
val previous = contact(firstFingerprint, "alice@example.test", "unknown")
|
||||||
|
val warning = AndroidPgpPolicy.storeChangeWarning(
|
||||||
|
listOf(previous),
|
||||||
|
listOf(previous.copy(trust = "verified"))
|
||||||
|
)
|
||||||
|
|
||||||
|
assertTrue(warning!!.contains("alice@example.test"))
|
||||||
|
assertTrue(warning.contains("0123 4567 89AB CDEF"))
|
||||||
|
assertTrue(warning.contains("New trust: verified"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun addingAKeyForAnExistingAddressRequiresReplacementWarning() {
|
||||||
|
val previous = contact(firstFingerprint, "alice@example.test", "unknown")
|
||||||
|
val replacement = contact(secondFingerprint, "ALICE@example.test", "unknown")
|
||||||
|
val warning = AndroidPgpPolicy.storeChangeWarning(listOf(previous), listOf(previous, replacement))
|
||||||
|
|
||||||
|
assertTrue(warning!!.contains("different key is already stored"))
|
||||||
|
assertTrue(warning.contains("0123 4567 89AB CDEF"))
|
||||||
|
assertTrue(warning.contains("89AB CDEF 0123 4567"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun plaintextPromptNamesRecipientsAndMatchingKeyFingerprints() {
|
||||||
|
val warning = AndroidPgpPolicy.plaintextSendWarning(
|
||||||
|
recipients = listOf("Alice@example.test", "bob@example.test"),
|
||||||
|
availableKeys = listOf(AndroidPgpPolicy.RecipientKey("alice@example.test", firstFingerprint)),
|
||||||
|
encryptionWasRequested = false
|
||||||
|
)
|
||||||
|
|
||||||
|
assertTrue(warning!!.contains("alice@example.test"))
|
||||||
|
assertTrue(warning.contains("0123 4567 89AB CDEF"))
|
||||||
|
assertTrue(warning.contains("bob@example.test — no key stored"))
|
||||||
|
assertTrue(warning.contains("readable by the mail provider"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun noPlaintextPromptWhenNoKeyExistsAndEncryptionWasNotRequested() {
|
||||||
|
assertNull(
|
||||||
|
AndroidPgpPolicy.plaintextSendWarning(
|
||||||
|
recipients = listOf("alice@example.test"),
|
||||||
|
availableKeys = emptyList(),
|
||||||
|
encryptionWasRequested = false
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun explicitEncryptionRequestPromptsEvenWhenNoRecipientKeyExists() {
|
||||||
|
val warning = AndroidPgpPolicy.plaintextSendWarning(
|
||||||
|
recipients = listOf("alice@example.test"),
|
||||||
|
availableKeys = emptyList(),
|
||||||
|
encryptionWasRequested = true
|
||||||
|
)
|
||||||
|
|
||||||
|
assertTrue(warning!!.contains("OpenPGP was requested"))
|
||||||
|
assertTrue(warning.contains("alice@example.test — no key stored"))
|
||||||
|
assertFalse(warning.contains("Fingerprint:"))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun contact(fingerprint: String, email: String, trust: String) =
|
||||||
|
AndroidPgpPolicy.ContactKey(fingerprint, listOf(email), trust)
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidVaultKeyPolicyTest {
|
||||||
|
@Test
|
||||||
|
fun newKeyMayBeCreatedOnlyWhenThereIsNoEncryptedStore() {
|
||||||
|
assertTrue(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = false))
|
||||||
|
assertFalse(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = true))
|
||||||
|
assertTrue(AndroidVaultKeyPolicy.MISSING_KEY_MESSAGE.contains("not reset or replaced"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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, " "))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,11 +4,12 @@ const state = window.epMailState;
|
|||||||
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
||||||
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
||||||
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
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()}
|
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){
|
function openMessage(id){
|
||||||
state.activeMessage=id;
|
state.activeMessage=id;
|
||||||
const m=state.messages.find(x=>x.id===id);
|
const m=state.messages.find(x=>x.id===id);
|
||||||
if(!m)return;
|
if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
|
||||||
|
document.body.classList.add('reader-open');
|
||||||
m.unread=false;
|
m.unread=false;
|
||||||
renderList();
|
renderList();
|
||||||
let safeHtml={html:'',remoteImageCount:0};
|
let safeHtml={html:'',remoteImageCount:0};
|
||||||
@@ -16,7 +17,8 @@ function openMessage(id){
|
|||||||
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
|
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
|
||||||
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
|
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
|
||||||
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
|
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
|
||||||
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;
|
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><button class="reader-back" id="reader-back" type="button" aria-label="Back to messages">Back</button><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;
|
||||||
|
$('#reader-back').onclick=()=>{state.activeMessage=null;document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader();renderList()};
|
||||||
$('#load-remote-images')?.addEventListener('click',()=>{
|
$('#load-remote-images')?.addEventListener('click',()=>{
|
||||||
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
||||||
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
||||||
@@ -25,8 +27,8 @@ function openMessage(id){
|
|||||||
});
|
});
|
||||||
$('.remote-image-notice')?.remove();
|
$('.remote-image-notice')?.remove();
|
||||||
});
|
});
|
||||||
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
$('#reader-archive').onclick=()=>{m.archived=true;state.activeMessage=null;document.body.classList.remove('reader-open');toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
$('#reader-delete').onclick=()=>{m.deleted=true;state.activeMessage=null;document.body.classList.remove('reader-open');toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
||||||
$('#reply').onclick=()=>showCompose(m);
|
$('#reply').onclick=()=>showCompose(m);
|
||||||
$('#forward').onclick=()=>showCompose(m,true);
|
$('#forward').onclick=()=>showCompose(m,true);
|
||||||
@@ -35,7 +37,7 @@ function emptyReader(){return `<div class="reader-empty"><div><div class="empty-
|
|||||||
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 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 ↗</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 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 ↗</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();}
|
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({
|
window.epMailShell = Object.freeze({
|
||||||
state,
|
state,
|
||||||
|
|||||||
+1
-1
@@ -60,7 +60,7 @@ function downloadAttachment(details) {
|
|||||||
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message?.uid) return;
|
if (!message?.uid || message.pgpDecrypted) return;
|
||||||
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
|
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
|
||||||
const download = row.querySelector('.download');
|
const download = row.querySelector('.download');
|
||||||
if (!download || row.querySelector('.preview-attachment')) return;
|
if (!download || row.querySelector('.preview-attachment')) return;
|
||||||
|
|||||||
+24
-2
@@ -228,7 +228,7 @@ function openMailAccount(existingAccount = null) {
|
|||||||
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${escapeMailUi(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
|
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${escapeMailUi(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
|
||||||
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
||||||
</div>`).join('');
|
</div>`).join('');
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Credentials are stored encrypted. Choose the server's advertised TLS mode and ports.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password / app password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>IMAP port</span><input id="mail-account-imap-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.imapPort || (existingAccount?.authMethod === 'oauth2' ? 993 : 143)}"></label><label class="compose-line mail-security-option"><span>IMAP implicit SSL/TLS (usually port 993)</span><input id="mail-account-imap-secure" type="checkbox"${existingAccount?.imapSecure ? ' checked' : ''}></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>SMTP port</span><input id="mail-account-smtp-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.smtpPort || 587}"></label><label class="compose-line mail-security-option"><span>SMTP implicit SSL/TLS (usually port 465)</span><input id="mail-account-smtp-secure" type="checkbox"${existingAccount?.smtpSecure ? ' checked' : ''}></label><p class="account-note">For IMAP port 143 and SMTP port 587, leave implicit SSL/TLS off to use required STARTTLS. Common Gmail settings are IMAP SSL/TLS on port 993 and SMTP STARTTLS on port 587; use an app password if required by your provider.</p><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
||||||
const authMethodRow = document.createElement('label');
|
const authMethodRow = document.createElement('label');
|
||||||
authMethodRow.className = 'compose-line';
|
authMethodRow.className = 'compose-line';
|
||||||
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
|
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
|
||||||
@@ -249,7 +249,11 @@ function openMailAccount(existingAccount = null) {
|
|||||||
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
|
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
|
||||||
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
|
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
|
||||||
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
|
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
|
||||||
|
const imapPortRow = selectMailUi('#mail-account-imap-port').closest('.compose-line');
|
||||||
|
const imapSecureRow = selectMailUi('#mail-account-imap-secure').closest('.compose-line');
|
||||||
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
|
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
|
||||||
|
const smtpPortRow = selectMailUi('#mail-account-smtp-port').closest('.compose-line');
|
||||||
|
const smtpSecureRow = selectMailUi('#mail-account-smtp-secure').closest('.compose-line');
|
||||||
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
|
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
|
||||||
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
|
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
|
||||||
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
|
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
|
||||||
@@ -258,7 +262,11 @@ function openMailAccount(existingAccount = null) {
|
|||||||
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
|
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
|
||||||
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
|
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
|
||||||
selectMailUi('#mail-account-imap').value = servers.imap;
|
selectMailUi('#mail-account-imap').value = servers.imap;
|
||||||
|
selectMailUi('#mail-account-imap-port').value = '993';
|
||||||
|
selectMailUi('#mail-account-imap-secure').checked = true;
|
||||||
selectMailUi('#mail-account-smtp').value = servers.smtp;
|
selectMailUi('#mail-account-smtp').value = servers.smtp;
|
||||||
|
selectMailUi('#mail-account-smtp-port').value = '587';
|
||||||
|
selectMailUi('#mail-account-smtp-secure').checked = false;
|
||||||
};
|
};
|
||||||
const updateAuthFields = () => {
|
const updateAuthFields = () => {
|
||||||
const oauth = authMethodSelect.value === 'oauth2';
|
const oauth = authMethodSelect.value === 'oauth2';
|
||||||
@@ -267,12 +275,16 @@ function openMailAccount(existingAccount = null) {
|
|||||||
reauthorizeRow.hidden = !oauth || !editing;
|
reauthorizeRow.hidden = !oauth || !editing;
|
||||||
passwordRow.hidden = oauth;
|
passwordRow.hidden = oauth;
|
||||||
imapRow.hidden = oauth;
|
imapRow.hidden = oauth;
|
||||||
|
imapPortRow.hidden = oauth;
|
||||||
|
imapSecureRow.hidden = oauth;
|
||||||
smtpRow.hidden = oauth;
|
smtpRow.hidden = oauth;
|
||||||
|
smtpPortRow.hidden = oauth;
|
||||||
|
smtpSecureRow.hidden = oauth;
|
||||||
authNote.textContent = oauth
|
authNote.textContent = oauth
|
||||||
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
|
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
|
||||||
: configuredOAuthProviders && configuredOAuthProviders.size === 0
|
: configuredOAuthProviders && configuredOAuthProviders.size === 0
|
||||||
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
|
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
|
||||||
: 'Your password is encrypted with this computer\'s credential storage. Connections require TLS.';
|
: 'Credentials are stored encrypted. Connections require verified TLS.';
|
||||||
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
|
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
|
||||||
? 'Leave blank to keep current password' : 'Enter mailbox password';
|
? 'Leave blank to keep current password' : 'Enter mailbox password';
|
||||||
};
|
};
|
||||||
@@ -332,6 +344,12 @@ function openMailAccount(existingAccount = null) {
|
|||||||
const name = selectMailUi('#mail-account-display-name').value.trim();
|
const name = selectMailUi('#mail-account-display-name').value.trim();
|
||||||
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
||||||
if (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
if (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
||||||
|
const imapPort = Number(selectMailUi('#mail-account-imap-port').value);
|
||||||
|
const smtpPort = Number(selectMailUi('#mail-account-smtp-port').value);
|
||||||
|
if (authMethod === 'password' && (![imapPort, smtpPort].every(port => Number.isInteger(port) && port >= 1 && port <= 65535))) {
|
||||||
|
status.textContent = 'Enter valid IMAP and SMTP ports (1–65535).';
|
||||||
|
return;
|
||||||
|
}
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
|
const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
|
||||||
button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
||||||
@@ -347,7 +365,11 @@ function openMailAccount(existingAccount = null) {
|
|||||||
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
|
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
|
||||||
displayName: name,
|
displayName: name,
|
||||||
imapHost: selectMailUi('#mail-account-imap').value,
|
imapHost: selectMailUi('#mail-account-imap').value,
|
||||||
|
imapPort,
|
||||||
|
imapSecure: selectMailUi('#mail-account-imap-secure').checked,
|
||||||
smtpHost: selectMailUi('#mail-account-smtp').value,
|
smtpHost: selectMailUi('#mail-account-smtp').value,
|
||||||
|
smtpPort,
|
||||||
|
smtpSecure: selectMailUi('#mail-account-smtp-secure').checked,
|
||||||
signature: selectMailUi('#mail-account-signature').value,
|
signature: selectMailUi('#mail-account-signature').value,
|
||||||
notificationsEnabled: selectMailUi('#mail-account-notifications').checked,
|
notificationsEnabled: selectMailUi('#mail-account-notifications').checked,
|
||||||
syncIntervalMinutes: Number(selectMailUi('#mail-account-sync-interval').value),
|
syncIntervalMinutes: Number(selectMailUi('#mail-account-sync-interval').value),
|
||||||
|
|||||||
Generated
+3
-3
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.2",
|
"version": "0.5.11",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.2",
|
"version": "0.5.11",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "^8.5.2",
|
"@capacitor/android": "^8.5.2",
|
||||||
"@capacitor/core": "^8.5.2",
|
"@capacitor/core": "^8.5.2",
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
"imapflow": "2.2.1",
|
"imapflow": "2.2.1",
|
||||||
"mailparser": "3.9.33",
|
"mailparser": "3.9.33",
|
||||||
"nodemailer": "10.0.9",
|
"nodemailer": "10.0.9",
|
||||||
"openpgp": "^6.3.2",
|
"openpgp": "6.3.2",
|
||||||
"tsdav": "^2.3.4",
|
"tsdav": "^2.3.4",
|
||||||
"v8-compile-cache": "^2.4.0"
|
"v8-compile-cache": "^2.4.0"
|
||||||
},
|
},
|
||||||
|
|||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.2",
|
"version": "0.5.11",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Eternity Project mail client",
|
"description": "Eternity Project mail client",
|
||||||
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
||||||
@@ -104,7 +104,7 @@
|
|||||||
"imapflow": "2.2.1",
|
"imapflow": "2.2.1",
|
||||||
"mailparser": "3.9.33",
|
"mailparser": "3.9.33",
|
||||||
"nodemailer": "10.0.9",
|
"nodemailer": "10.0.9",
|
||||||
"openpgp": "^6.3.2",
|
"openpgp": "6.3.2",
|
||||||
"tsdav": "^2.3.4",
|
"tsdav": "^2.3.4",
|
||||||
"v8-compile-cache": "^2.4.0"
|
"v8-compile-cache": "^2.4.0"
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-3
@@ -135,7 +135,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
|||||||
if (!footer || !pgpApi()) return;
|
if (!footer || !pgpApi()) return;
|
||||||
const box = document.createElement('div');
|
const box = document.createElement('div');
|
||||||
box.className = 'pgp-compose';
|
box.className = 'pgp-compose';
|
||||||
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
|
||||||
footer.prepend(box);
|
footer.prepend(box);
|
||||||
let touched = false;
|
let touched = false;
|
||||||
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
||||||
@@ -169,6 +169,9 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
|||||||
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
||||||
async function prepareSend(to, cc) {
|
async function prepareSend(to, cc) {
|
||||||
if (!pgpApi()) return null;
|
if (!pgpApi()) return null;
|
||||||
|
const plaintextFallback = () => pgpApi().platform === 'android'
|
||||||
|
? { encrypt: false, sign: false, plaintextFallback: true }
|
||||||
|
: null;
|
||||||
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
||||||
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
||||||
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
||||||
@@ -176,7 +179,7 @@ async function prepareSend(to, cc) {
|
|||||||
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
||||||
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
||||||
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
||||||
if (!sign) return null;
|
if (!sign) return plaintextFallback();
|
||||||
} else return false;
|
} else return false;
|
||||||
}
|
}
|
||||||
if (!encrypt && !sign) return null;
|
if (!encrypt && !sign) return null;
|
||||||
@@ -184,7 +187,7 @@ 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?`);
|
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
||||||
if (!sendPlain) return false;
|
if (!sendPlain) return false;
|
||||||
encrypt = false;
|
encrypt = false;
|
||||||
if (!sign) return null;
|
if (!sign) return plaintextFallback();
|
||||||
}
|
}
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
|
|||||||
@@ -6,22 +6,22 @@ const selectAllPgpKeyUi = pgpKeyMailUi.selectAll;
|
|||||||
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
||||||
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
||||||
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
||||||
|
async function saveAndroidPgpExport(label, value) {
|
||||||
|
if (window.daybreakMail?.pgp?.platform !== 'android' || typeof value !== 'string') return value;
|
||||||
|
const warning = /private|revocation/i.test(label) ? ' This contains secret key material; keep it private.' : '';
|
||||||
|
if (!confirm(`Copy this ${label.toLowerCase()} to the clipboard?${warning}`)) return { canceled: true };
|
||||||
|
if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(value);
|
||||||
|
else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true };
|
||||||
|
return { saved: true };
|
||||||
|
}
|
||||||
|
|
||||||
function openEncryptionKeys() {
|
function openEncryptionKeys() {
|
||||||
const root = selectPgpKeyUi('#modal-root');
|
const root = selectPgpKeyUi('#modal-root');
|
||||||
const account = window.epMailFeatures.mail.connectedAccount || {};
|
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">
|
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
|
||||||
<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 serverSettings = androidPgp
|
||||||
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
? '<h3 class="pgp-heading">Public key servers</h3><p class="account-note">Key-server lookup and publication are disabled in Android testing. Import a public key directly and compare its fingerprint with the owner.</p><div hidden><div id="pgp-server-list"></div><input id="pgp-search-email"><button id="pgp-find-key"></button><div id="pgp-found-keys"></div><select id="pgp-publish-server"></select><input id="pgp-server-name"><input id="pgp-server-url"><select id="pgp-server-protocol"></select><button id="pgp-add-server"></button></div>'
|
||||||
<h3 class="pgp-heading">Change a key passphrase</h3>
|
: `<h3 class="pgp-heading">Public key servers</h3>
|
||||||
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
|
||||||
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
|
||||||
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
|
||||||
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
|
||||||
<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>
|
<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>
|
<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>
|
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
@@ -33,7 +33,19 @@ function openEncryptionKeys() {
|
|||||||
<label class="compose-line"><span>Name</span><input id="pgp-server-name" maxlength="60" placeholder="My key server"></label>
|
<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>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>
|
<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>
|
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
|
||||||
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
||||||
|
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
||||||
|
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
||||||
|
<h3 class="pgp-heading">Change a key passphrase</h3>
|
||||||
|
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
||||||
|
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
|
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
||||||
|
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
||||||
|
<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>
|
||||||
|
${serverSettings}
|
||||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||||
@@ -140,7 +152,7 @@ function openEncryptionKeys() {
|
|||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||||
try {
|
try {
|
||||||
const result = await run();
|
const result = await saveAndroidPgpExport(label, await run());
|
||||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||||
} catch (error) { status(error.message || 'That action failed.'); }
|
} catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
@@ -188,7 +200,7 @@ function openEncryptionKeys() {
|
|||||||
if (!passphrase) return;
|
if (!passphrase) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
||||||
status(result.canceled ? '' : 'Key imported.');
|
status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.');
|
||||||
await render();
|
await render();
|
||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
@@ -241,7 +253,7 @@ function openEncryptionKeys() {
|
|||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.textContent = label;
|
button.textContent = label;
|
||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||||
catch (error) { status(error.message || 'That action failed.'); }
|
catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
@@ -403,7 +415,7 @@ function openEncryptionKeys() {
|
|||||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||||
void renderKeyServers();
|
if (!androidPgp) void renderKeyServers();
|
||||||
void renderContacts();
|
void renderContacts();
|
||||||
void render();
|
void render();
|
||||||
}
|
}
|
||||||
|
|||||||
+10007
-26
File diff suppressed because one or more lines are too long
+12
-4
@@ -27,16 +27,24 @@ 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('#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();
|
selectProductivityUi('#profile-name').focus();
|
||||||
}
|
}
|
||||||
function openPreferences() {
|
async function openPreferences() {
|
||||||
const root=selectProductivityUi('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
||||||
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
||||||
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
|
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
|
||||||
|
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled?window.daybreakMail:null;
|
||||||
|
let notificationPrivacy={showDetails:false};
|
||||||
|
let appLockSettings={enabled:false,deviceSecure:false};
|
||||||
|
if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}}
|
||||||
|
if(appLockBridge){try{appLockSettings=await appLockBridge.getAppLockSettings()}catch(error){toastProductivityUi(error.message||'Could not load app-lock settings');return}}
|
||||||
|
const notificationSetting=notificationBridge?`<label class="compose-line"><span>Show sender and subject in notifications</span><input id="show-notification-details" type="checkbox"${notificationPrivacy.showDetails?' checked':''}></label><p class="account-note">Off by default. Android still hides private details from lock-screen previews.</p>`:'';
|
||||||
|
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><p class="account-note">Requires a secure Android screen lock. Mail sync continues in the background; unlock with your device PIN, pattern, or password when you return.</p>`:'';
|
||||||
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
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.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')}};
|
||||||
selectProductivityUi('#theme-select').focus();
|
selectProductivityUi('#theme-select').focus();
|
||||||
}
|
}
|
||||||
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
|
function 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 +80,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
|||||||
}
|
}
|
||||||
return baseMessageRenderer();
|
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({
|
window.epMailFeatures.productivity = Object.freeze({
|
||||||
get events() { return savedEvents; },
|
get events() { return savedEvents; },
|
||||||
|
|||||||
@@ -1,10 +1,15 @@
|
|||||||
import { Capacitor, registerPlugin } from '@capacitor/core';
|
import { Capacitor, registerPlugin } from '@capacitor/core';
|
||||||
|
import { createAndroidPgp } from './android-pgp.js';
|
||||||
|
|
||||||
const EpMail = registerPlugin('EpMail');
|
const EpMail = registerPlugin('EpMail');
|
||||||
|
|
||||||
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
||||||
window.daybreakMail = {
|
const daybreakMail = {
|
||||||
getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
|
getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
|
||||||
|
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
|
||||||
|
setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }),
|
||||||
|
getAppLockSettings: () => EpMail.getAppLockSettings(),
|
||||||
|
setAppLockEnabled: enabled => EpMail.setAppLockEnabled({ enabled }),
|
||||||
getAccount: () => EpMail.getAccount(),
|
getAccount: () => EpMail.getAccount(),
|
||||||
listAccounts: () => EpMail.listAccounts(),
|
listAccounts: () => EpMail.listAccounts(),
|
||||||
selectAccount: id => EpMail.selectAccount({ id }),
|
selectAccount: id => EpMail.selectAccount({ id }),
|
||||||
@@ -25,7 +30,24 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
|||||||
previewAttachment: details => EpMail.previewAttachment(details),
|
previewAttachment: details => EpMail.previewAttachment(details),
|
||||||
saveAttachment: details => EpMail.saveAttachment(details),
|
saveAttachment: details => EpMail.saveAttachment(details),
|
||||||
openExternal: url => EpMail.openExternal({ url }),
|
openExternal: url => EpMail.openExternal({ url }),
|
||||||
send: message => EpMail.send(message),
|
send: async message => {
|
||||||
|
if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) {
|
||||||
|
if (message?.pgp?.plaintextFallback) {
|
||||||
|
const { pgp: _options, ...plainMessage } = message;
|
||||||
|
return EpMail.send({ ...plainMessage, pgpRequested: true });
|
||||||
|
}
|
||||||
|
return EpMail.send(message);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { rawBase64, to, from } = await daybreakMail.pgp.buildOutgoing(message);
|
||||||
|
const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message;
|
||||||
|
return await EpMail.send({ ...headers, rawBase64, envelope: { from, to }, text: '', attachments: [] });
|
||||||
|
} catch (error) {
|
||||||
|
return { failed: true, code: error.code || 'PGP_ERROR', message: error.message || 'Could not encrypt this message.' };
|
||||||
|
}
|
||||||
|
},
|
||||||
|
pgpGetMessageSource: details => EpMail.pgpGetMessageSource(details),
|
||||||
|
savePgpAttachment: details => EpMail.savePgpAttachment(details),
|
||||||
disconnect: id => EpMail.removeAccount({ id }),
|
disconnect: id => EpMail.removeAccount({ id }),
|
||||||
davList: () => EpMail.davList(),
|
davList: () => EpMail.davList(),
|
||||||
davConnect: config => EpMail.davConnect(config),
|
davConnect: config => EpMail.davConnect(config),
|
||||||
@@ -37,4 +59,6 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
|||||||
davSaveContact: contact => EpMail.davSaveContact(contact),
|
davSaveContact: contact => EpMail.davSaveContact(contact),
|
||||||
davDeleteContact: remote => EpMail.davDeleteContact(remote)
|
davDeleteContact: remote => EpMail.davDeleteContact(remote)
|
||||||
};
|
};
|
||||||
|
daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount() });
|
||||||
|
window.daybreakMail = daybreakMail;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,466 @@
|
|||||||
|
import * as openpgp from 'openpgp';
|
||||||
|
|
||||||
|
const MAX_KEY_LENGTH = 200000;
|
||||||
|
const MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
|
||||||
|
const TRUST = ['unknown', 'trusted', 'verified'];
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
|
||||||
|
function parseAddresses(value) {
|
||||||
|
return String(value || '').split(',').map(part => {
|
||||||
|
const text = part.trim();
|
||||||
|
if (!text) return null;
|
||||||
|
const match = /^(.*?)\s*<([^<>]+)>$/.exec(text);
|
||||||
|
const address = (match?.[2] || text).trim().toLowerCase();
|
||||||
|
const name = (match?.[1] || '').replace(/^"|"$/g, '').trim();
|
||||||
|
if (!/^[^\s@<>(),;]+@[^\s@<>(),;]+\.[^\s@<>(),;]+$/.test(address)) {
|
||||||
|
throw new Error(`"${text || 'recipient'}" is not a valid email address.`);
|
||||||
|
}
|
||||||
|
return { address, name };
|
||||||
|
}).filter(Boolean);
|
||||||
|
}
|
||||||
|
|
||||||
|
function emailsOf(key) {
|
||||||
|
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitEntity(value) {
|
||||||
|
const text = typeof value === 'string' ? value : decoder.decode(value);
|
||||||
|
const normalized = text.replace(/\r?\n/g, '\r\n');
|
||||||
|
const split = normalized.indexOf('\r\n\r\n');
|
||||||
|
if (split < 0) throw new Error('Malformed MIME message.');
|
||||||
|
const headerText = normalized.slice(0, split);
|
||||||
|
const body = normalized.slice(split + 4);
|
||||||
|
const headers = {};
|
||||||
|
let current = '';
|
||||||
|
for (const line of headerText.split('\r\n')) {
|
||||||
|
if (/^[ \t]/.test(line) && current) headers[current] += ` ${line.trim()}`;
|
||||||
|
else {
|
||||||
|
const colon = line.indexOf(':');
|
||||||
|
if (colon > 0) {
|
||||||
|
current = line.slice(0, colon).trim().toLowerCase();
|
||||||
|
headers[current] = line.slice(colon + 1).trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { headers, body };
|
||||||
|
}
|
||||||
|
|
||||||
|
function parameter(value, name) {
|
||||||
|
const match = new RegExp(`(?:^|;)\\s*${name}\\s*=\\s*(?:"([^"]+)"|([^;\\s]+))`, 'i').exec(value || '');
|
||||||
|
return match?.[1] || match?.[2] || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodePart(body, transferEncoding) {
|
||||||
|
const value = body.replace(/\r\n--[^\r\n]*$/, '').replace(/\r\n$/, '');
|
||||||
|
if (/base64/i.test(transferEncoding || '')) {
|
||||||
|
const compact = value.replace(/[\r\n\t ]/g, '');
|
||||||
|
const binary = atob(compact);
|
||||||
|
return Uint8Array.from(binary, char => char.charCodeAt(0));
|
||||||
|
}
|
||||||
|
if (/quoted-printable/i.test(transferEncoding || '')) {
|
||||||
|
const bytes = [];
|
||||||
|
for (let index = 0; index < value.length; index += 1) {
|
||||||
|
if (value[index] === '=' && value[index + 1] === '\r' && value[index + 2] === '\n') { index += 2; continue; }
|
||||||
|
if (value[index] === '=' && /^[0-9a-f]{2}$/i.test(value.slice(index + 1, index + 3))) {
|
||||||
|
bytes.push(parseInt(value.slice(index + 1, index + 3), 16));
|
||||||
|
index += 2;
|
||||||
|
} else bytes.push(value.charCodeAt(index) & 255);
|
||||||
|
}
|
||||||
|
return Uint8Array.from(bytes);
|
||||||
|
}
|
||||||
|
return encoder.encode(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitMultipart(body, boundary) {
|
||||||
|
if (!boundary || boundary.length > 200) return [];
|
||||||
|
const mark = `--${boundary}`;
|
||||||
|
return body.split(mark).slice(1).filter(part => !part.startsWith('--'))
|
||||||
|
.map(part => part.replace(/^\r?\n/, '').replace(/\r?\n$/, ''))
|
||||||
|
.filter(part => part.trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseInnerMime(bytes) {
|
||||||
|
const result = { body: '', html: '', attachments: [] };
|
||||||
|
const visit = (source, depth = 0) => {
|
||||||
|
if (depth > 8) return;
|
||||||
|
const entity = splitEntity(source);
|
||||||
|
const type = entity.headers['content-type'] || 'text/plain; charset=utf-8';
|
||||||
|
const transfer = entity.headers['content-transfer-encoding'] || '';
|
||||||
|
const disposition = entity.headers['content-disposition'] || '';
|
||||||
|
const boundary = parameter(type, 'boundary');
|
||||||
|
if (/^multipart\//i.test(type) && boundary) {
|
||||||
|
for (const part of splitMultipart(entity.body, boundary)) visit(part, depth + 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const data = decodePart(entity.body, transfer);
|
||||||
|
const filename = parameter(disposition, 'filename') || parameter(type, 'name');
|
||||||
|
if (filename || /^attachment/i.test(disposition)) {
|
||||||
|
if (result.attachments.length < 50 && data.length <= 25 * 1024 * 1024) {
|
||||||
|
let binary = '';
|
||||||
|
for (let index = 0; index < data.length; index += 0x8000) {
|
||||||
|
binary += String.fromCharCode(...data.subarray(index, index + 0x8000));
|
||||||
|
}
|
||||||
|
result.attachments.push({
|
||||||
|
filename: (filename || 'attachment').replace(/[\\/\r\n\u0000]/g, '').slice(0, 255) || 'attachment',
|
||||||
|
contentType: type.split(';')[0].trim() || 'application/octet-stream',
|
||||||
|
size: data.length,
|
||||||
|
contentBase64: btoa(binary)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const text = decoder.decode(data);
|
||||||
|
if (/^text\/html/i.test(type) && !result.html) result.html = text.slice(0, 100000);
|
||||||
|
else if (/^text\/plain/i.test(type) && !result.body) result.body = text.slice(0, 500000);
|
||||||
|
};
|
||||||
|
visit(bytes);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
function randomBoundary() {
|
||||||
|
const bytes = crypto.getRandomValues(new Uint8Array(18));
|
||||||
|
return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeHeader(value, max = 900) {
|
||||||
|
return String(value || '').replace(/[\r\n\u0000]+/g, ' ').trim().slice(0, max);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatAddress(entry) {
|
||||||
|
const address = entry.address;
|
||||||
|
const name = safeHeader(entry.name, 100).replace(/["\\]/g, ' ');
|
||||||
|
return name ? `${encodeHeader(name)} <${address}>` : address;
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeHeader(value) {
|
||||||
|
const clean = safeHeader(value, 998);
|
||||||
|
if (/^[\x20-\x7e]*$/.test(clean)) return clean;
|
||||||
|
return `=?UTF-8?B?${toBase64(encoder.encode(clean))}?=`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mimeInner(text, attachments) {
|
||||||
|
const files = Array.isArray(attachments) ? attachments : [];
|
||||||
|
if (files.length > 50 || files.reduce((total, file) => total + String(file?.contentBase64 || '').length, 0) > 36_000_000) {
|
||||||
|
throw new Error('The encrypted message attachments exceed the Android testing size limit.');
|
||||||
|
}
|
||||||
|
if (!files.length) {
|
||||||
|
const bytes = encoder.encode(String(text || ''));
|
||||||
|
let binary = '';
|
||||||
|
for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
|
||||||
|
const base64 = btoa(binary).replace(/.{1,76}/g, '$&\r\n').trim();
|
||||||
|
return `Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${base64}\r\n`;
|
||||||
|
}
|
||||||
|
const mark = randomBoundary();
|
||||||
|
const parts = [`--${mark}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n${String(text || '').replace(/\r?\n/g, '\r\n')}\r\n`];
|
||||||
|
for (const file of files) {
|
||||||
|
const filename = safeHeader(file.filename || 'attachment', 180).replace(/["\\]/g, '_') || 'attachment';
|
||||||
|
const type = String(file.contentType || 'application/octet-stream').toLowerCase();
|
||||||
|
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(type)) throw new Error(`The content type for ${filename} is invalid.`);
|
||||||
|
const base64 = String(file.contentBase64 || '').replace(/\s/g, '');
|
||||||
|
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(base64)) throw new Error(`The contents of ${filename} are invalid.`);
|
||||||
|
parts.push(`--${mark}\r\nContent-Type: ${type}; name="${filename}"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename="${filename}"\r\n\r\n${base64.replace(/.{1,76}/g, '$&\r\n').trim()}\r\n`);
|
||||||
|
}
|
||||||
|
parts.push(`--${mark}--\r\n`);
|
||||||
|
return `Content-Type: multipart/mixed; boundary="${mark}"\r\n\r\n${parts.join('')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toBase64(bytes) {
|
||||||
|
let binary = '';
|
||||||
|
for (let index = 0; index < bytes.length; index += 0x8000) binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
|
||||||
|
return btoa(binary);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAndroidPgp({ EpMail, getAccount }) {
|
||||||
|
let storePromise;
|
||||||
|
const passphrases = new Map();
|
||||||
|
let cacheMinutes = 10;
|
||||||
|
|
||||||
|
async function store() {
|
||||||
|
if (!storePromise) storePromise = EpMail.pgpLoadStore().then(value => {
|
||||||
|
const savedMinutes = Number(value?.settings?.cacheMinutes);
|
||||||
|
if (Number.isFinite(savedMinutes) && savedMinutes >= 0 && savedMinutes <= 1440) cacheMinutes = Math.round(savedMinutes);
|
||||||
|
return value;
|
||||||
|
}).catch(error => { storePromise = null; throw error; });
|
||||||
|
return storePromise.then(value => JSON.parse(JSON.stringify(value)));
|
||||||
|
}
|
||||||
|
async function persist(value) {
|
||||||
|
await EpMail.pgpSaveStore({ store: value });
|
||||||
|
storePromise = Promise.resolve(JSON.parse(JSON.stringify(value)));
|
||||||
|
}
|
||||||
|
function cache(fingerprint, passphrase) {
|
||||||
|
if (!cacheMinutes) { passphrases.delete(fingerprint); return; }
|
||||||
|
passphrases.set(fingerprint, { passphrase, expires: Date.now() + cacheMinutes * 60000 });
|
||||||
|
}
|
||||||
|
function cached(fingerprint) {
|
||||||
|
const item = passphrases.get(fingerprint);
|
||||||
|
if (!item) return null;
|
||||||
|
if (item.expires <= Date.now()) { passphrases.delete(fingerprint); return null; }
|
||||||
|
return item.passphrase;
|
||||||
|
}
|
||||||
|
function clear(fingerprint) { if (fingerprint) passphrases.delete(fingerprint); else passphrases.clear(); }
|
||||||
|
function publicInfo(entry) {
|
||||||
|
return { fingerprint: entry.fingerprint, name: entry.name, email: entry.email, accountId: entry.accountId || null,
|
||||||
|
createdAt: entry.createdAt, algorithm: entry.algorithm, hasRevocationCertificate: Boolean(entry.revocationCertificate) };
|
||||||
|
}
|
||||||
|
async function verificationKeys(data) {
|
||||||
|
const output = [];
|
||||||
|
for (const entry of [...data.contacts, ...data.keys.map(key => ({ ...key, emails: [String(key.email).toLowerCase()], trust: 'verified', own: true }))]) {
|
||||||
|
try { output.push({ entry, key: await openpgp.readKey({ armoredKey: entry.publicKey }) }); } catch { /* malformed records are ignored, never trusted */ }
|
||||||
|
}
|
||||||
|
return output;
|
||||||
|
}
|
||||||
|
async function addContact({ armoredKey, source = 'import' }) {
|
||||||
|
const armored = String(armoredKey || '').trim();
|
||||||
|
if (!armored || armored.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('Import a valid public key (maximum 200 KB).');
|
||||||
|
const key = await openpgp.readKey({ armoredKey: armored }).catch(() => { throw new Error('That is not a valid OpenPGP public key.'); });
|
||||||
|
await key.getPrimaryUser().catch(() => { throw new Error('That key is expired, revoked or has no valid user ID.'); });
|
||||||
|
const fingerprint = key.getFingerprint().toUpperCase();
|
||||||
|
const emails = emailsOf(key);
|
||||||
|
const data = await store();
|
||||||
|
if (data.keys.some(entry => entry.fingerprint === fingerprint)) throw new Error('That is one of your own keys.');
|
||||||
|
if (data.contacts.some(entry => entry.fingerprint === fingerprint)) throw new Error('That public key is already in your contacts.');
|
||||||
|
const keyChangedFrom = data.contacts.filter(entry => entry.emails.some(email => emails.includes(email))).map(entry => entry.fingerprint);
|
||||||
|
if (keyChangedFrom.length && !confirm(`A different public key is already stored for ${emails.join(', ')}.\n\nNew fingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nExisting fingerprint(s):\n${keyChangedFrom.map(value => value.match(/.{1,4}/g).join(' ')).join('\n')}\n\nAdd the new key as an unverified key? Compare fingerprints with the owner before trusting it.`)) {
|
||||||
|
return { canceled: true, keyChangedFrom };
|
||||||
|
}
|
||||||
|
const user = await key.getPrimaryUser();
|
||||||
|
data.contacts.push({ fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown',
|
||||||
|
source: ['import', 'message', 'paste'].includes(source) ? source : 'import', addedAt: Date.now(), publicKey: key.armor() });
|
||||||
|
await persist(data);
|
||||||
|
return { contact: { fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source, addedAt: Date.now() }, keyChangedFrom };
|
||||||
|
}
|
||||||
|
async function resolveRecipients(addresses) {
|
||||||
|
const data = await store();
|
||||||
|
const pool = [
|
||||||
|
...data.contacts.map(entry => ({ ...entry, own: false })),
|
||||||
|
...data.keys.map(entry => ({ ...entry, emails: [String(entry.email).toLowerCase()], trust: 'verified', own: true }))
|
||||||
|
];
|
||||||
|
const resolved = [];
|
||||||
|
const missing = [];
|
||||||
|
for (const address of addresses) {
|
||||||
|
const candidates = pool.filter(entry => entry.emails.includes(address)).sort((a, b) => TRUST.indexOf(b.trust) - TRUST.indexOf(a.trust) || b.addedAt - a.addedAt);
|
||||||
|
let found = null;
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
try { const key = await openpgp.readKey({ armoredKey: candidate.publicKey }); await key.getEncryptionKey(); found = { address, key, fingerprint: candidate.fingerprint, trust: candidate.trust }; break; } catch { /* try next usable key */ }
|
||||||
|
}
|
||||||
|
if (found) resolved.push(found); else missing.push(address);
|
||||||
|
}
|
||||||
|
return { keys: resolved, missing };
|
||||||
|
}
|
||||||
|
async function unlock(fingerprint, passphrase) {
|
||||||
|
const entry = (await store()).keys.find(item => item.fingerprint === fingerprint);
|
||||||
|
if (!entry) throw new Error('That key was not found.');
|
||||||
|
try { return await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: entry.privateKey }), passphrase }); }
|
||||||
|
catch { throw new Error('The passphrase is incorrect.'); }
|
||||||
|
}
|
||||||
|
async function signerFor(account, passphrase) {
|
||||||
|
const data = await store();
|
||||||
|
const entry = data.keys.find(item => item.email.toLowerCase() === String(account.email).toLowerCase());
|
||||||
|
if (!entry) throw Object.assign(new Error('Create or import an encryption key for this address first.'), { code: 'NO_SIGNING_KEY' });
|
||||||
|
const secret = passphrase || cached(entry.fingerprint);
|
||||||
|
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email} to sign this message.`), { code: 'PASSPHRASE_REQUIRED', fingerprint: entry.fingerprint, email: entry.email });
|
||||||
|
try { const key = await unlock(entry.fingerprint, secret); cache(entry.fingerprint, secret); return { key, entry }; }
|
||||||
|
catch { clear(entry.fingerprint); throw Object.assign(new Error('The passphrase is incorrect.'), { code: 'BAD_PASSPHRASE', fingerprint: entry.fingerprint, email: entry.email }); }
|
||||||
|
}
|
||||||
|
async function buildOutgoing(message) {
|
||||||
|
const account = await getAccount();
|
||||||
|
if (!account?.email) throw new Error('Add a mail account before encrypting messages.');
|
||||||
|
const to = parseAddresses(message.to);
|
||||||
|
const cc = parseAddresses(message.cc);
|
||||||
|
const everyone = [...to, ...cc];
|
||||||
|
if (!to.length) throw new Error('Add at least one recipient.');
|
||||||
|
const from = { name: safeHeader(account.displayName || message.displayName || account.email, 100), address: account.email };
|
||||||
|
const pgp = message.pgp || {};
|
||||||
|
const data = await store();
|
||||||
|
let signer = null;
|
||||||
|
if (pgp.sign) signer = await signerFor(account, pgp.passphrase || null);
|
||||||
|
const recipientKeys = pgp.encrypt ? await resolveRecipients(everyone.map(item => item.address)) : { keys: [], missing: [] };
|
||||||
|
if (pgp.encrypt && recipientKeys.missing.length) {
|
||||||
|
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(', ')}.`), { code: 'NO_RECIPIENT_KEY', missing: recipientKeys.missing });
|
||||||
|
}
|
||||||
|
let inner = mimeInner(`${String(message.text || '').slice(0, 500000)}${account.signature ? `\n\n${String(account.signature).slice(0, 5000)}` : ''}`, message.attachments || []);
|
||||||
|
const headers = [
|
||||||
|
`From: ${formatAddress(from)}`,
|
||||||
|
`To: ${to.map(formatAddress).join(', ')}`,
|
||||||
|
...(cc.length ? [`Cc: ${cc.map(formatAddress).join(', ')}`] : []),
|
||||||
|
`Subject: ${encodeHeader(message.subject || '(no subject)')}`,
|
||||||
|
`Date: ${new Date().toUTCString().replace('GMT', '+0000')}`,
|
||||||
|
`Message-ID: ${safeHeader(message.messageId || `<${crypto.randomUUID()}@ep-mail.local>`, 200)}`,
|
||||||
|
'MIME-Version: 1.0'
|
||||||
|
];
|
||||||
|
let contentType;
|
||||||
|
let body;
|
||||||
|
const boundary = randomBoundary();
|
||||||
|
if (pgp.encrypt) {
|
||||||
|
const own = data.keys.find(entry => entry.email.toLowerCase() === account.email.toLowerCase());
|
||||||
|
const encryptionKeys = [...recipientKeys.keys.map(item => item.key)];
|
||||||
|
if (own) encryptionKeys.push(await openpgp.readKey({ armoredKey: own.publicKey }));
|
||||||
|
if (signer && !encryptionKeys.some(key => key.getFingerprint().toUpperCase() === signer.entry.fingerprint)) encryptionKeys.push(await openpgp.readKey({ armoredKey: signer.entry.publicKey }));
|
||||||
|
const encrypted = await openpgp.encrypt({
|
||||||
|
message: await openpgp.createMessage({ binary: encoder.encode(inner) }),
|
||||||
|
encryptionKeys,
|
||||||
|
signingKeys: signer?.key,
|
||||||
|
format: 'armored'
|
||||||
|
});
|
||||||
|
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`;
|
||||||
|
body = `--${boundary}\r\nContent-Type: application/pgp-encrypted\r\nContent-Description: PGP/MIME version identification\r\n\r\nVersion: 1\r\n--${boundary}\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\nContent-Description: OpenPGP encrypted message\r\nContent-Disposition: inline; filename="encrypted.asc"\r\n\r\n${String(encrypted).replace(/\r?\n/g, '\r\n')}\r\n--${boundary}--\r\n`;
|
||||||
|
} else {
|
||||||
|
if (!pgp.sign || !signer) throw new Error('Choose encryption or signing for this message.');
|
||||||
|
const signedBytes = encoder.encode(inner.replace(/\r?\n/g, '\r\n'));
|
||||||
|
const signature = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signer.key, detached: true, format: 'armored' });
|
||||||
|
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${boundary}"`;
|
||||||
|
body = `--${boundary}\r\n${decoder.decode(signedBytes)}\r\n--${boundary}\r\nContent-Type: application/pgp-signature; name="signature.asc"\r\nContent-Description: OpenPGP digital signature\r\nContent-Disposition: attachment; filename="signature.asc"\r\n\r\n${String(signature).replace(/\r?\n/g, '\r\n')}\r\n--${boundary}--\r\n`;
|
||||||
|
}
|
||||||
|
const raw = encoder.encode(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`);
|
||||||
|
if (raw.byteLength > MAX_MESSAGE_BYTES) throw new Error('This encrypted message is too large to send.');
|
||||||
|
return { rawBase64: toBase64(raw), to: everyone.map(item => item.address), from: account.email };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function decryptMessage({ folder = 'Inbox', uid, passphrase = null }) {
|
||||||
|
try {
|
||||||
|
const source = await EpMail.pgpGetMessageSource({ folder, uid });
|
||||||
|
const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0));
|
||||||
|
if (raw.byteLength > MAX_MESSAGE_BYTES) return { failed: true, code: 'TOO_LARGE', message: 'This encrypted message is too large to open.' };
|
||||||
|
const text = decoder.decode(raw);
|
||||||
|
const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(text)?.[0];
|
||||||
|
if (!armor) return { failed: true, code: 'CORRUPT', message: 'The encrypted part of this message is missing or damaged.' };
|
||||||
|
const message = await openpgp.readMessage({ armoredMessage: armor }).catch(() => null);
|
||||||
|
if (!message) return { failed: true, code: 'CORRUPT', message: 'The encrypted part of this message is damaged.' };
|
||||||
|
const wanted = new Set(message.getEncryptionKeyIDs().map(item => item.toHex().toUpperCase()));
|
||||||
|
const data = await store();
|
||||||
|
const candidates = [];
|
||||||
|
for (const entry of data.keys) {
|
||||||
|
const key = await openpgp.readKey({ armoredKey: entry.publicKey }).catch(() => null);
|
||||||
|
if (key?.getKeys().some(item => wanted.has(item.getKeyID().toHex().toUpperCase()))) candidates.push(entry);
|
||||||
|
}
|
||||||
|
if (!candidates.length) return { failed: true, code: 'NO_KEY', message: 'None of your keys can decrypt this message.' };
|
||||||
|
let secret = passphrase;
|
||||||
|
let selected = candidates[0];
|
||||||
|
if (!secret) {
|
||||||
|
selected = candidates.find(entry => cached(entry.fingerprint)) || selected;
|
||||||
|
secret = cached(selected.fingerprint);
|
||||||
|
}
|
||||||
|
if (!secret) return { failed: true, code: 'PASSPHRASE_REQUIRED', fingerprint: selected.fingerprint, email: selected.email, message: 'Enter your key passphrase to read this message.' };
|
||||||
|
let privateKey;
|
||||||
|
try { privateKey = await unlock(selected.fingerprint, secret); }
|
||||||
|
catch { clear(selected.fingerprint); return { failed: true, code: 'BAD_PASSPHRASE', fingerprint: selected.fingerprint, email: selected.email, message: 'The passphrase is incorrect.' }; }
|
||||||
|
cache(selected.fingerprint, secret);
|
||||||
|
const verify = await verificationKeys(data);
|
||||||
|
let decrypted;
|
||||||
|
try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); }
|
||||||
|
catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; }
|
||||||
|
const content = parseInnerMime(decrypted.data);
|
||||||
|
const signatures = [];
|
||||||
|
for (const item of decrypted.signatures || []) {
|
||||||
|
const known = verify.find(candidate => candidate.key.getKeys().some(key => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
|
||||||
|
let status = 'valid';
|
||||||
|
try { await item.verified; } catch { status = known ? 'invalid' : 'unknown-key'; }
|
||||||
|
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || '';
|
||||||
|
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || '').toLowerCase();
|
||||||
|
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
|
||||||
|
const changed = Boolean(sender && data.contacts.some(entry => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
|
||||||
|
const matchesSender = Boolean(sender && keyEmails.includes(sender));
|
||||||
|
signatures.push({ status, keyId: item.keyID.toHex().toUpperCase(), fingerprint: known?.entry.fingerprint || null,
|
||||||
|
trust: known?.entry.trust || null, email: keyEmails[0] || null, matchesSender, keyChanged: changed,
|
||||||
|
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {}) });
|
||||||
|
}
|
||||||
|
return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html,
|
||||||
|
links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null,
|
||||||
|
size: content.attachments[0]?.size || '', signatures, attachedKeys: [] };
|
||||||
|
} catch (error) {
|
||||||
|
return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const api = {
|
||||||
|
platform: 'android',
|
||||||
|
async list() { return (await store()).keys.map(publicInfo); },
|
||||||
|
async generate({ name, email, passphrase, accountId = null }) {
|
||||||
|
const cleanEmail = String(email || '').trim().toLowerCase();
|
||||||
|
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
|
||||||
|
if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.');
|
||||||
|
const generated = await openpgp.generateKey({ type: 'ecc', curve: 'curve25519Legacy', userIDs: [{ name: safeHeader(name, 100), email: cleanEmail }], passphrase, format: 'armored' });
|
||||||
|
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
|
||||||
|
const data = await store();
|
||||||
|
if (data.keys.some(item => item.fingerprint === key.getFingerprint().toUpperCase())) throw new Error('That key is already in your keyring.');
|
||||||
|
const entry = { fingerprint: key.getFingerprint().toUpperCase(), name: safeHeader(name, 100), email: cleanEmail, accountId,
|
||||||
|
createdAt: Date.now(), algorithm: 'Curve25519', privateKey: generated.privateKey, publicKey: generated.publicKey,
|
||||||
|
revocationCertificate: generated.revocationCertificate };
|
||||||
|
data.keys.push(entry);
|
||||||
|
await persist(data);
|
||||||
|
return { key: publicInfo(entry), revocationCertificate: generated.revocationCertificate };
|
||||||
|
},
|
||||||
|
async importKey({ armoredKey, passphrase, accountId = null }) {
|
||||||
|
if (!armoredKey) armoredKey = prompt('Paste an ASCII-armored OpenPGP private key (up to 200 KB):') || '';
|
||||||
|
const armored = String(armoredKey).trim();
|
||||||
|
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
|
||||||
|
if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.');
|
||||||
|
const parsed = await openpgp.readPrivateKey({ armoredKey: armored }).catch(() => { throw new Error('That is not a valid OpenPGP private key.'); });
|
||||||
|
const protectedKey = parsed.isDecrypted() ? await openpgp.encryptKey({ privateKey: parsed, passphrase }) : parsed;
|
||||||
|
if (!parsed.isDecrypted()) await openpgp.decryptKey({ privateKey: parsed, passphrase }).catch(() => { throw new Error('The passphrase is incorrect.'); });
|
||||||
|
const publicKey = protectedKey.toPublic();
|
||||||
|
const user = await protectedKey.getPrimaryUser().catch(() => null);
|
||||||
|
const entry = { fingerprint: protectedKey.getFingerprint().toUpperCase(), name: user?.user?.userID?.name || '',
|
||||||
|
email: user?.user?.userID?.email || '', accountId, createdAt: protectedKey.getCreationTime().getTime(),
|
||||||
|
algorithm: protectedKey.getAlgorithmInfo().algorithm, privateKey: protectedKey.armor(), publicKey: publicKey.armor(), revocationCertificate: null };
|
||||||
|
const data = await store();
|
||||||
|
if (data.keys.some(item => item.fingerprint === entry.fingerprint)) throw new Error('That key is already in your keyring.');
|
||||||
|
data.keys.push(entry); await persist(data); return { key: publicInfo(entry) };
|
||||||
|
},
|
||||||
|
async exportPublic(fingerprint) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); return entry.publicKey; },
|
||||||
|
async exportPrivate(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(fingerprint, passphrase); return entry.privateKey; },
|
||||||
|
async exportRevocation(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry?.revocationCertificate) throw new Error('No revocation certificate is stored for this key.'); await unlock(fingerprint, passphrase); return entry.revocationCertificate; },
|
||||||
|
async changePassphrase({ fingerprint, currentPassphrase, newPassphrase }) {
|
||||||
|
if (String(newPassphrase || '').length < 8) throw new Error('Use a new passphrase of at least 8 characters.');
|
||||||
|
const data = await store(); const entry = data.keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.');
|
||||||
|
const secret = await unlock(fingerprint, currentPassphrase); const protectedKey = await openpgp.encryptKey({ privateKey: secret, passphrase: newPassphrase });
|
||||||
|
entry.privateKey = protectedKey.armor(); await persist(data); clear(fingerprint); return { changed: true };
|
||||||
|
},
|
||||||
|
async remove(fingerprint, passphrase) { const data = await store(); const entry = data.keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(fingerprint, passphrase); data.keys = data.keys.filter(item => item.fingerprint !== fingerprint); await persist(data); clear(fingerprint); return { removed: true }; },
|
||||||
|
async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); },
|
||||||
|
async addContact(input = {}) {
|
||||||
|
const armoredKey = input.armoredKey || prompt('Paste an ASCII-armored OpenPGP public key (up to 200 KB):') || '';
|
||||||
|
return addContact({ ...input, armoredKey });
|
||||||
|
},
|
||||||
|
async setTrust(fingerprint, trust) {
|
||||||
|
if (!TRUST.includes(trust)) throw new Error('Unknown trust level.');
|
||||||
|
const data = await store(); const contact = data.contacts.find(item => item.fingerprint === fingerprint); if (!contact) throw new Error('That contact key was not found.');
|
||||||
|
if (TRUST.indexOf(trust) > TRUST.indexOf(contact.trust) && !confirm(`Mark ${contact.emails.join(', ')} as ${trust}?\n\nFingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nOnly continue if you checked this fingerprint with the owner.`)) throw new Error('Trust change cancelled.');
|
||||||
|
contact.trust = trust; await persist(data); return { ...contact };
|
||||||
|
},
|
||||||
|
async removeContact(fingerprint) { const data = await store(); if (!data.contacts.some(item => item.fingerprint === fingerprint)) throw new Error('That contact key was not found.'); data.contacts = data.contacts.filter(item => item.fingerprint !== fingerprint); await persist(data); return { removed: true }; },
|
||||||
|
async exportContact(fingerprint) { const entry = (await store()).contacts.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That contact key was not found.'); return entry.publicKey; },
|
||||||
|
async checkSend({ to, cc, sign = false }) {
|
||||||
|
const addresses = [...parseAddresses(to || ''), ...parseAddresses(cc || '')].map(item => item.address);
|
||||||
|
const { keys, missing } = await resolveRecipients(addresses);
|
||||||
|
const account = await getAccount();
|
||||||
|
const entry = sign ? (await store()).keys.find(item => item.email.toLowerCase() === String(account?.email || '').toLowerCase()) : null;
|
||||||
|
return { recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })), missing,
|
||||||
|
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null };
|
||||||
|
},
|
||||||
|
decryptMessage,
|
||||||
|
async getSettings() { const data = await store(); return { cacheMinutes }; },
|
||||||
|
async setSettings({ cacheMinutes: value }) {
|
||||||
|
const number = Number(value);
|
||||||
|
if (!Number.isFinite(number) || number < 0 || number > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
||||||
|
const data = await store();
|
||||||
|
cacheMinutes = Math.round(number);
|
||||||
|
data.settings = { ...(data.settings || {}), cacheMinutes };
|
||||||
|
await persist(data);
|
||||||
|
if (!cacheMinutes) clear();
|
||||||
|
return { cacheMinutes };
|
||||||
|
},
|
||||||
|
async forgetPassphrases() { clear(); return { cleared: true }; },
|
||||||
|
async keyServers() { return []; },
|
||||||
|
async findKey() { throw new Error('Key-server lookup is not included in Android testing. Import a public key directly.'); },
|
||||||
|
async addKeyServer() { throw new Error('Key-server support is not included in Android testing.'); },
|
||||||
|
async removeKeyServer() { throw new Error('Key-server support is not included in Android testing.'); },
|
||||||
|
async setKeyServerEnabled() { throw new Error('Key-server support is not included in Android testing.'); },
|
||||||
|
async publishKey() { throw new Error('Key-server support is not included in Android testing.'); },
|
||||||
|
clearPassphrases: clear,
|
||||||
|
buildOutgoing
|
||||||
|
};
|
||||||
|
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') clear(); });
|
||||||
|
return api;
|
||||||
|
}
|
||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
const CACHE='ep-mail-v12';
|
const CACHE='ep-mail-v18';
|
||||||
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
|
||||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
|
||||||
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
||||||
|
|||||||
+93
-2
File diff suppressed because one or more lines are too long
@@ -0,0 +1,77 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const esbuild = require('esbuild');
|
||||||
|
const { webcrypto } = require('node:crypto');
|
||||||
|
|
||||||
|
global.crypto ||= webcrypto;
|
||||||
|
global.document ||= { addEventListener() {} };
|
||||||
|
|
||||||
|
const bundled = esbuild.buildSync({
|
||||||
|
entryPoints: [path.join(__dirname, '..', 'scripts', 'android-pgp.js')],
|
||||||
|
bundle: true,
|
||||||
|
platform: 'browser',
|
||||||
|
format: 'iife',
|
||||||
|
globalName: 'AndroidPgpBundle',
|
||||||
|
write: false
|
||||||
|
}).outputFiles[0].text;
|
||||||
|
vm.runInThisContext(bundled);
|
||||||
|
const { createAndroidPgp } = global.AndroidPgpBundle;
|
||||||
|
|
||||||
|
function makeEndpoint(account) {
|
||||||
|
const vault = { keys: [], contacts: [], settings: {} };
|
||||||
|
let messageSource = null;
|
||||||
|
const EpMail = {
|
||||||
|
async pgpLoadStore() { return JSON.parse(JSON.stringify(vault)); },
|
||||||
|
async pgpSaveStore({ store }) { Object.assign(vault, JSON.parse(JSON.stringify(store))); return { ok: true }; },
|
||||||
|
async pgpGetMessageSource() { return messageSource; }
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
api: createAndroidPgp({ EpMail, getAccount: async () => account }),
|
||||||
|
setMessage(value) { messageSource = value; },
|
||||||
|
vault
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => {
|
||||||
|
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
|
||||||
|
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
|
||||||
|
const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
|
||||||
|
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
|
||||||
|
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
|
||||||
|
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) });
|
||||||
|
|
||||||
|
const built = await sender.api.buildOutgoing({
|
||||||
|
to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
|
||||||
|
messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
|
||||||
|
attachments: [{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') }]
|
||||||
|
});
|
||||||
|
assert.ok(built.rawBase64);
|
||||||
|
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
|
||||||
|
assert.match(raw, /multipart\/encrypted; protocol="application\/pgp-encrypted"/i);
|
||||||
|
assert.doesNotMatch(raw, /hello from Android|private attachment/);
|
||||||
|
recipient.setMessage({ rawBase64: built.rawBase64 });
|
||||||
|
|
||||||
|
const promptRequired = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7 });
|
||||||
|
assert.equal(promptRequired.code, 'PASSPHRASE_REQUIRED');
|
||||||
|
const badPassphrase = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7, passphrase: 'wrong passphrase' });
|
||||||
|
assert.equal(badPassphrase.code, 'BAD_PASSPHRASE');
|
||||||
|
const opened = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7, passphrase: 'bob test passphrase' });
|
||||||
|
assert.equal(opened.ok, true, opened.message);
|
||||||
|
assert.deepEqual(opened.body, ['hello from Android']);
|
||||||
|
assert.equal(opened.attachments[0].filename, 'note.txt');
|
||||||
|
assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment');
|
||||||
|
assert.equal(opened.signatures[0].status, 'valid');
|
||||||
|
await recipient.api.setSettings({ cacheMinutes: 0 });
|
||||||
|
assert.equal((await recipient.api.getSettings()).cacheMinutes, 0);
|
||||||
|
assert.equal((await recipient.api.decryptMessage({ folder: 'Inbox', uid: 7 })).code, 'PASSPHRASE_REQUIRED');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android OpenPGP refuses encryption when any recipient key is missing', async () => {
|
||||||
|
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
|
||||||
|
await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
|
||||||
|
await assert.rejects(sender.api.buildOutgoing({
|
||||||
|
to: 'nobody@example.test', text: 'must not escape as plaintext', pgp: { encrypt: true }, attachments: []
|
||||||
|
}), error => error.code === 'NO_RECIPIENT_KEY');
|
||||||
|
});
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const styles = fs.readFileSync(path.join(root, 'styles.css'), 'utf8');
|
||||||
|
const mailUi = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
|
||||||
|
const app = fs.readFileSync(path.join(root, 'app.js'), 'utf8');
|
||||||
|
const transport = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailTransport.kt'), 'utf8');
|
||||||
|
const mainActivity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8');
|
||||||
|
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
|
||||||
|
const vault = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidAccountVault.kt'), 'utf8');
|
||||||
|
const androidMailService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
|
||||||
|
const androidPgpPolicy = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpPolicy.kt'), 'utf8');
|
||||||
|
const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpConfirmationGate.kt'), 'utf8');
|
||||||
|
const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
||||||
|
const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8');
|
||||||
|
const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8');
|
||||||
|
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||||
|
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
|
||||||
|
|
||||||
|
test('mobile layout removes desktop minimum width and provides a compact reader flow', () => {
|
||||||
|
assert.match(styles, /min-width:320px/);
|
||||||
|
assert.match(styles, /@media\(max-width:1000px\),\(max-height:500px\) and \(orientation:landscape\)/);
|
||||||
|
assert.match(styles, /@media\(max-height:500px\) and \(orientation:landscape\)/);
|
||||||
|
assert.match(styles, /overflow-wrap:anywhere;word-break:break-word/);
|
||||||
|
assert.match(styles, /\.hidden,\[hidden\]\{display:none!important\}/);
|
||||||
|
assert.match(styles, /body\.reader-open \.mail-layout \.list-pane/);
|
||||||
|
assert.match(app, /id="reader-back"/);
|
||||||
|
assert.match(app, /classList\.add\('reader-open'\)/);
|
||||||
|
assert.match(app, /\$\$\('\.folder'\)\.forEach/);
|
||||||
|
assert.match(app, /if\(!m\)\{state\.activeMessage=null;document\.body\.classList\.remove\('reader-open'\);return;\}/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mailbox setup exposes ports and TLS modes and submits them to Android', () => {
|
||||||
|
for (const id of ['mail-account-imap-port', 'mail-account-imap-secure', 'mail-account-smtp-port', 'mail-account-smtp-secure']) {
|
||||||
|
assert.ok(mailUi.includes(`id="${id}"`), `missing account field ${id}`);
|
||||||
|
}
|
||||||
|
assert.match(mailUi, /imapPort,/);
|
||||||
|
assert.match(mailUi, /imapSecure:/);
|
||||||
|
assert.match(mailUi, /smtpPort,/);
|
||||||
|
assert.match(mailUi, /smtpSecure:/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android mail transport supports verified implicit TLS and required STARTTLS modes', () => {
|
||||||
|
assert.match(transport, /"imaps" else "imap"/);
|
||||||
|
assert.match(transport, /mail\.\$protocol\.starttls\.required/);
|
||||||
|
assert.match(transport, /mail\.smtp\.ssl\.enable/);
|
||||||
|
assert.match(transport, /mail\.smtp\.starttls\.required/);
|
||||||
|
assert.match(transport, /ssl\.checkserveridentity/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Capacitor mail plugin is registered before BridgeActivity creates the bridge', () => {
|
||||||
|
assert.ok(mainActivity.indexOf('registerPlugin(EpMailPlugin.class)') < mainActivity.indexOf('super.onCreate(savedInstanceState)'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OpenPGP.js is pinned to the exact version in the lockfile pending security review', () => {
|
||||||
|
assert.equal(packageJson.dependencies.openpgp, packageLock.packages['node_modules/openpgp'].version);
|
||||||
|
assert.match(packageJson.dependencies.openpgp, /^\d+\.\d+\.\d+$/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android app lock is native-enforced and requires a secure device credential', () => {
|
||||||
|
assert.match(plugin, /fun getAppLockSettings/);
|
||||||
|
assert.match(plugin, /fun setAppLockEnabled/);
|
||||||
|
assert.match(plugin, /keyguard\.isDeviceSecure/);
|
||||||
|
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
|
||||||
|
assert.match(mainActivity, /createConfirmDeviceCredentialIntent/);
|
||||||
|
assert.match(mainActivity, /android\.R\.id\.content/);
|
||||||
|
assert.match(mainActivity, /settings\.setAllowFileAccess\(false\)/);
|
||||||
|
assert.match(mainActivity, /settings\.setAllowContentAccess\(false\)/);
|
||||||
|
assert.match(mainActivity, /setJavaScriptCanOpenWindowsAutomatically\(false\)/);
|
||||||
|
assert.match(mainActivity, /MIXED_CONTENT_NEVER_ALLOW/);
|
||||||
|
assert.match(mainActivity, /setWebContentsDebuggingEnabled\(BuildConfig\.DEBUG\)/);
|
||||||
|
assert.match(mainActivity, /addFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
|
||||||
|
assert.match(mainActivity, /clearFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
|
||||||
|
assert.match(mainActivity, /createVaultRecoveryOverlay/);
|
||||||
|
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
|
||||||
|
assert.match(androidBridge, /getAppLockSettings/);
|
||||||
|
assert.match(androidBridge, /setAppLockEnabled/);
|
||||||
|
assert.match(productivity, /Lock when leaving ep-mail/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android OpenPGP uses the encrypted vault and queues only built MIME data', () => {
|
||||||
|
assert.match(plugin, /fun pgpLoadStore/);
|
||||||
|
assert.match(plugin, /fun pgpSaveStore/);
|
||||||
|
assert.match(plugin, /fun pgpGetMessageSource/);
|
||||||
|
assert.match(plugin, /pgpStoreChangeWarning/);
|
||||||
|
assert.match(plugin, /plaintextSendWarning/);
|
||||||
|
assert.match(plugin, /Send plaintext/);
|
||||||
|
assert.match(plugin, /showPgpConfirmation\(/);
|
||||||
|
assert.match(plugin, /onCancelled = \{ call\.reject\("OpenPGP key change cancelled\."\) \}/);
|
||||||
|
assert.match(plugin, /onConfirmed = \{ sendPrepared\(call, input\) \}/);
|
||||||
|
assert.match(plugin, /PLAINTEXT_CANCELLED/);
|
||||||
|
assert.match(androidPgpConfirmationGate, /compareAndSet\(false, true\)/);
|
||||||
|
assert.match(androidPgpPolicy, /fun storeChangeWarning/);
|
||||||
|
assert.match(androidPgpPolicy, /fun plaintextSendWarning/);
|
||||||
|
assert.match(androidPgp, /curve25519Legacy/);
|
||||||
|
assert.match(androidPgp, /multipart\/encrypted/);
|
||||||
|
assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/);
|
||||||
|
assert.match(androidBridge, /buildOutgoing\(message\)/);
|
||||||
|
assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/);
|
||||||
|
assert.match(androidMailService, /validateOpenPgpMime\(message\)/);
|
||||||
|
assert.match(androidMailService, /private fun validateOpenPgpMime/);
|
||||||
|
assert.match(androidMailService, /"send" -> send\(account, data\)/);
|
||||||
|
assert.match(androidMailService, /private fun isEncryptedMessage/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android vault refuses to replace a missing key when encrypted data exists', () => {
|
||||||
|
assert.match(vault, /shouldCreateKey\(hasEncryptedData\)/);
|
||||||
|
assert.match(vault, /MISSING_KEY_MESSAGE/);
|
||||||
|
assert.match(mainActivity, /AndroidAccountVault\.INSTANCE\.read\(\)/);
|
||||||
|
assert.match(mainActivity, /Saved data could not be opened/);
|
||||||
|
assert.match(mainActivity, /ACTION_APPLICATION_DETAILS_SETTINGS/);
|
||||||
|
});
|
||||||
@@ -80,6 +80,7 @@ test('account and snooze UI consume the explicit mail API instead of selected le
|
|||||||
const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8');
|
const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8');
|
||||||
const productivityUi = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
const productivityUi = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
||||||
assert.match(accountUi, /window\.epMailFeatures\.mail/);
|
assert.match(accountUi, /window\.epMailFeatures\.mail/);
|
||||||
|
assert.match(accountUi, /Downloaded attachment files and OpenPGP keys are kept/);
|
||||||
assert.match(attachmentUi, /^\(\(\) => \{/);
|
assert.match(attachmentUi, /^\(\(\) => \{/);
|
||||||
assert.match(snoozeUi, /window\.epMailFeatures\.mail/);
|
assert.match(snoozeUi, /window\.epMailFeatures\.mail/);
|
||||||
assert.match(snoozeUi, /^\(\(\) => \{/);
|
assert.match(snoozeUi, /^\(\(\) => \{/);
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ async function openAccountManager(){
|
|||||||
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}
|
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
||||||
const removeButton=event.target.closest('[data-remove-account]');
|
const removeButton=event.target.closest('[data-remove-account]');
|
||||||
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;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}
|
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')}
|
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
||||||
}
|
}
|
||||||
|
|||||||
+8
-6
@@ -4,11 +4,12 @@ const state = window.epMailState;
|
|||||||
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
|
||||||
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))}
|
||||||
const { safeRemoteImageUrl, sanitizeMailHtml } = window.epMailFeatures.contentSecurity;
|
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()}
|
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){
|
function openMessage(id){
|
||||||
state.activeMessage=id;
|
state.activeMessage=id;
|
||||||
const m=state.messages.find(x=>x.id===id);
|
const m=state.messages.find(x=>x.id===id);
|
||||||
if(!m)return;
|
if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
|
||||||
|
document.body.classList.add('reader-open');
|
||||||
m.unread=false;
|
m.unread=false;
|
||||||
renderList();
|
renderList();
|
||||||
let safeHtml={html:'',remoteImageCount:0};
|
let safeHtml={html:'',remoteImageCount:0};
|
||||||
@@ -16,7 +17,8 @@ function openMessage(id){
|
|||||||
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
|
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
|
||||||
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
|
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
|
||||||
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
|
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
|
||||||
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;
|
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><button class="reader-back" id="reader-back" type="button" aria-label="Back to messages">Back</button><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ Reply</button><button class="reply-button" id="forward">↗ Forward</button></div>`;
|
||||||
|
$('#reader-back').onclick=()=>{state.activeMessage=null;document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader();renderList()};
|
||||||
$('#load-remote-images')?.addEventListener('click',()=>{
|
$('#load-remote-images')?.addEventListener('click',()=>{
|
||||||
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
|
||||||
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
|
||||||
@@ -25,8 +27,8 @@ function openMessage(id){
|
|||||||
});
|
});
|
||||||
$('.remote-image-notice')?.remove();
|
$('.remote-image-notice')?.remove();
|
||||||
});
|
});
|
||||||
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
$('#reader-archive').onclick=()=>{m.archived=true;state.activeMessage=null;document.body.classList.remove('reader-open');toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
$('#reader-delete').onclick=()=>{m.deleted=true;state.activeMessage=null;document.body.classList.remove('reader-open');toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
|
||||||
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
|
||||||
$('#reply').onclick=()=>showCompose(m);
|
$('#reply').onclick=()=>showCompose(m);
|
||||||
$('#forward').onclick=()=>showCompose(m,true);
|
$('#forward').onclick=()=>showCompose(m,true);
|
||||||
@@ -35,7 +37,7 @@ function emptyReader(){return `<div class="reader-empty"><div><div class="empty-
|
|||||||
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 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 ↗</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 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 ↗</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();}
|
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({
|
window.epMailShell = Object.freeze({
|
||||||
state,
|
state,
|
||||||
|
|||||||
+1
-1
@@ -60,7 +60,7 @@ function downloadAttachment(details) {
|
|||||||
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
attachmentMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
const message = attachmentMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message?.uid) return;
|
if (!message?.uid || message.pgpDecrypted) return;
|
||||||
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
|
selectAllAttachmentUi('#reader-pane .attachment').forEach(row => {
|
||||||
const download = row.querySelector('.download');
|
const download = row.querySelector('.download');
|
||||||
if (!download || row.querySelector('.preview-attachment')) return;
|
if (!download || row.querySelector('.preview-attachment')) return;
|
||||||
|
|||||||
+24
-2
@@ -228,7 +228,7 @@ function openMailAccount(existingAccount = null) {
|
|||||||
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${escapeMailUi(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
|
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${escapeMailUi(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
|
||||||
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
||||||
</div>`).join('');
|
</div>`).join('');
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Your password is encrypted with this computer's credential storage. Connections require TLS.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${editing ? 'Edit mailbox' : 'Add a mailbox'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Credentials are stored encrypted. Choose the server's advertised TLS mode and ports.</p><label class="compose-line"><span>Email</span><input id="mail-account-email" type="email" autocomplete="username" value="${escapeMailUi(existingAccount?.email || '')}" placeholder="name@example.com"></label><label class="compose-line"><span>Account display name</span><input id="mail-account-display-name" maxlength="80" autocomplete="name" value="${escapeMailUi(displayName)}" placeholder="Your name" required></label><label class="compose-line"><span>Password / app password</span><input id="mail-account-password" type="password" autocomplete="${editing ? 'new-password' : 'current-password'}" placeholder="${editing ? 'Leave blank to keep current password' : 'Enter mailbox password'}"></label><label class="compose-line"><span>IMAP host</span><input id="mail-account-imap" value="${escapeMailUi(existingAccount?.imapHost || '')}" autocomplete="off" placeholder="imap.example.com"></label><label class="compose-line"><span>IMAP port</span><input id="mail-account-imap-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.imapPort || (existingAccount?.authMethod === 'oauth2' ? 993 : 143)}"></label><label class="compose-line mail-security-option"><span>IMAP implicit SSL/TLS (usually port 993)</span><input id="mail-account-imap-secure" type="checkbox"${existingAccount?.imapSecure ? ' checked' : ''}></label><label class="compose-line"><span>SMTP host</span><input id="mail-account-smtp" value="${escapeMailUi(existingAccount?.smtpHost || '')}" autocomplete="off" placeholder="smtp.example.com"></label><label class="compose-line"><span>SMTP port</span><input id="mail-account-smtp-port" type="number" inputmode="numeric" min="1" max="65535" value="${existingAccount?.smtpPort || 587}"></label><label class="compose-line mail-security-option"><span>SMTP implicit SSL/TLS (usually port 465)</span><input id="mail-account-smtp-secure" type="checkbox"${existingAccount?.smtpSecure ? ' checked' : ''}></label><p class="account-note">For IMAP port 143 and SMTP port 587, leave implicit SSL/TLS off to use required STARTTLS. Common Gmail settings are IMAP SSL/TLS on port 993 and SMTP STARTTLS on port 587; use an app password if required by your provider.</p><label class="compose-line"><span>Sync interval</span><select id="mail-account-sync-interval" class="settings-select">${[2,5,15,30,60].map(minutes=>`<option value="${minutes}"${Number(existingAccount?.syncIntervalMinutes||2)===minutes?' selected':''}>Every ${minutes} minutes</option>`).join('')}</select></label><label class="compose-line"><span>New-mail notifications</span><input id="mail-account-notifications" type="checkbox"${existingAccount?.notificationsEnabled!==false?' checked':''}></label><label class="compose-line" style="display:block;padding:8px 0"><span>Signature</span><textarea id="mail-account-signature" maxlength="5000" rows="3" placeholder="Add a signature for this mailbox" style="display:block;box-sizing:border-box;width:100%;margin-top:7px">${escapeMailUi(existingAccount?.signature || '')}</textarea></label><section class="mail-rules"><div class="section-label"><span>MAIL RULES</span><button type="button" class="tiny-plus" id="add-mail-rule" aria-label="Add mail rule">+</button></div><p class="account-note">Rules match the sender or subject of incoming mail. The first matching rule runs.</p><div id="mail-rule-list">${ruleMarkup}</div></section><p class="account-note">Signatures are appended to outgoing messages. Sync interval controls periodic checks when IMAP IDLE is unavailable; Android may apply its 15-minute minimum background interval.${editing ? ' Leave the password empty to keep the saved password.' : ''}</p><p id="mail-account-status" class="account-status" aria-live="polite"></p></div><div class="compose-footer"><button class="discard" id="disconnect-mail">Cancel</button><button class="send-button" id="connect-mail">${editing ? 'Save & reconnect' : 'Test & connect'}</button></div></div></div>`;
|
||||||
const authMethodRow = document.createElement('label');
|
const authMethodRow = document.createElement('label');
|
||||||
authMethodRow.className = 'compose-line';
|
authMethodRow.className = 'compose-line';
|
||||||
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
|
authMethodRow.innerHTML = '<span>Sign-in method</span><select id="mail-account-auth-method" class="settings-select"><option value="password">App password</option><option value="oauth2">OAuth2</option></select>';
|
||||||
@@ -249,7 +249,11 @@ function openMailAccount(existingAccount = null) {
|
|||||||
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
|
if (oauthMethodOption) oauthMethodOption.disabled = existingAccount?.authMethod !== 'oauth2';
|
||||||
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
|
const passwordRow = selectMailUi('#mail-account-password').closest('.compose-line');
|
||||||
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
|
const imapRow = selectMailUi('#mail-account-imap').closest('.compose-line');
|
||||||
|
const imapPortRow = selectMailUi('#mail-account-imap-port').closest('.compose-line');
|
||||||
|
const imapSecureRow = selectMailUi('#mail-account-imap-secure').closest('.compose-line');
|
||||||
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
|
const smtpRow = selectMailUi('#mail-account-smtp').closest('.compose-line');
|
||||||
|
const smtpPortRow = selectMailUi('#mail-account-smtp-port').closest('.compose-line');
|
||||||
|
const smtpSecureRow = selectMailUi('#mail-account-smtp-secure').closest('.compose-line');
|
||||||
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
|
const authNote = selectMailUi('#modal-root .compose-fields > .account-note');
|
||||||
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
|
authMethodSelect.value = existingAccount?.authMethod === 'oauth2' ? 'oauth2' : 'password';
|
||||||
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
|
if (existingAccount?.oauthProvider) oauthProviderSelect.value = existingAccount.oauthProvider;
|
||||||
@@ -258,7 +262,11 @@ function openMailAccount(existingAccount = null) {
|
|||||||
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
|
? { imap: 'imap.gmail.com', smtp: 'smtp.gmail.com' }
|
||||||
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
|
: { imap: 'outlook.office365.com', smtp: 'smtp.office365.com' };
|
||||||
selectMailUi('#mail-account-imap').value = servers.imap;
|
selectMailUi('#mail-account-imap').value = servers.imap;
|
||||||
|
selectMailUi('#mail-account-imap-port').value = '993';
|
||||||
|
selectMailUi('#mail-account-imap-secure').checked = true;
|
||||||
selectMailUi('#mail-account-smtp').value = servers.smtp;
|
selectMailUi('#mail-account-smtp').value = servers.smtp;
|
||||||
|
selectMailUi('#mail-account-smtp-port').value = '587';
|
||||||
|
selectMailUi('#mail-account-smtp-secure').checked = false;
|
||||||
};
|
};
|
||||||
const updateAuthFields = () => {
|
const updateAuthFields = () => {
|
||||||
const oauth = authMethodSelect.value === 'oauth2';
|
const oauth = authMethodSelect.value === 'oauth2';
|
||||||
@@ -267,12 +275,16 @@ function openMailAccount(existingAccount = null) {
|
|||||||
reauthorizeRow.hidden = !oauth || !editing;
|
reauthorizeRow.hidden = !oauth || !editing;
|
||||||
passwordRow.hidden = oauth;
|
passwordRow.hidden = oauth;
|
||||||
imapRow.hidden = oauth;
|
imapRow.hidden = oauth;
|
||||||
|
imapPortRow.hidden = oauth;
|
||||||
|
imapSecureRow.hidden = oauth;
|
||||||
smtpRow.hidden = oauth;
|
smtpRow.hidden = oauth;
|
||||||
|
smtpPortRow.hidden = oauth;
|
||||||
|
smtpSecureRow.hidden = oauth;
|
||||||
authNote.textContent = oauth
|
authNote.textContent = oauth
|
||||||
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
|
? 'Sign in in your browser. Configure the provider client ID in the desktop environment; OAuth refresh tokens are stored in encrypted credential storage.'
|
||||||
: configuredOAuthProviders && configuredOAuthProviders.size === 0
|
: configuredOAuthProviders && configuredOAuthProviders.size === 0
|
||||||
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
|
? 'Password sign-in is available. To enable OAuth2, configure EP_MAIL_GOOGLE_OAUTH_CLIENT_ID and/or EP_MAIL_MICROSOFT_OAUTH_CLIENT_ID, then restart ep-mail.'
|
||||||
: 'Your password is encrypted with this computer\'s credential storage. Connections require TLS.';
|
: 'Credentials are stored encrypted. Connections require verified TLS.';
|
||||||
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
|
selectMailUi('#mail-account-password').placeholder = editing && existingAccount?.authMethod !== 'oauth2'
|
||||||
? 'Leave blank to keep current password' : 'Enter mailbox password';
|
? 'Leave blank to keep current password' : 'Enter mailbox password';
|
||||||
};
|
};
|
||||||
@@ -332,6 +344,12 @@ function openMailAccount(existingAccount = null) {
|
|||||||
const name = selectMailUi('#mail-account-display-name').value.trim();
|
const name = selectMailUi('#mail-account-display-name').value.trim();
|
||||||
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
if (!name) { status.textContent = 'Enter a display name for this mail account.'; selectMailUi('#mail-account-display-name').focus(); return; }
|
||||||
if (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
if (authMethod === 'password' && !password && (!editing || existingAccount?.authMethod === 'oauth2')) { status.textContent = 'Enter the mailbox password to connect.'; selectMailUi('#mail-account-password').focus(); return; }
|
||||||
|
const imapPort = Number(selectMailUi('#mail-account-imap-port').value);
|
||||||
|
const smtpPort = Number(selectMailUi('#mail-account-smtp-port').value);
|
||||||
|
if (authMethod === 'password' && (![imapPort, smtpPort].every(port => Number.isInteger(port) && port >= 1 && port <= 65535))) {
|
||||||
|
status.textContent = 'Enter valid IMAP and SMTP ports (1–65535).';
|
||||||
|
return;
|
||||||
|
}
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
|
const reauthorizeOAuth = authMethod === 'oauth2' && editing && selectMailUi('#mail-account-reauthorize').checked;
|
||||||
button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
button.textContent = authMethod === 'oauth2' && (!editing || reauthorizeOAuth) ? 'Starting OAuth2 sign-in…' : editing ? 'Checking updated settings…' : 'Checking secure connections…';
|
||||||
@@ -347,7 +365,11 @@ function openMailAccount(existingAccount = null) {
|
|||||||
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
|
...(editing && authMethod === 'oauth2' ? { reauthorizeOAuth } : {}),
|
||||||
displayName: name,
|
displayName: name,
|
||||||
imapHost: selectMailUi('#mail-account-imap').value,
|
imapHost: selectMailUi('#mail-account-imap').value,
|
||||||
|
imapPort,
|
||||||
|
imapSecure: selectMailUi('#mail-account-imap-secure').checked,
|
||||||
smtpHost: selectMailUi('#mail-account-smtp').value,
|
smtpHost: selectMailUi('#mail-account-smtp').value,
|
||||||
|
smtpPort,
|
||||||
|
smtpSecure: selectMailUi('#mail-account-smtp-secure').checked,
|
||||||
signature: selectMailUi('#mail-account-signature').value,
|
signature: selectMailUi('#mail-account-signature').value,
|
||||||
notificationsEnabled: selectMailUi('#mail-account-notifications').checked,
|
notificationsEnabled: selectMailUi('#mail-account-notifications').checked,
|
||||||
syncIntervalMinutes: Number(selectMailUi('#mail-account-sync-interval').value),
|
syncIntervalMinutes: Number(selectMailUi('#mail-account-sync-interval').value),
|
||||||
|
|||||||
+6
-3
@@ -135,7 +135,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
|||||||
if (!footer || !pgpApi()) return;
|
if (!footer || !pgpApi()) return;
|
||||||
const box = document.createElement('div');
|
const box = document.createElement('div');
|
||||||
box.className = 'pgp-compose';
|
box.className = 'pgp-compose';
|
||||||
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
|
||||||
footer.prepend(box);
|
footer.prepend(box);
|
||||||
let touched = false;
|
let touched = false;
|
||||||
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
||||||
@@ -169,6 +169,9 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
|||||||
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
||||||
async function prepareSend(to, cc) {
|
async function prepareSend(to, cc) {
|
||||||
if (!pgpApi()) return null;
|
if (!pgpApi()) return null;
|
||||||
|
const plaintextFallback = () => pgpApi().platform === 'android'
|
||||||
|
? { encrypt: false, sign: false, plaintextFallback: true }
|
||||||
|
: null;
|
||||||
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
||||||
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
||||||
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
||||||
@@ -176,7 +179,7 @@ async function prepareSend(to, cc) {
|
|||||||
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
||||||
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
||||||
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
||||||
if (!sign) return null;
|
if (!sign) return plaintextFallback();
|
||||||
} else return false;
|
} else return false;
|
||||||
}
|
}
|
||||||
if (!encrypt && !sign) return null;
|
if (!encrypt && !sign) return null;
|
||||||
@@ -184,7 +187,7 @@ 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?`);
|
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
||||||
if (!sendPlain) return false;
|
if (!sendPlain) return false;
|
||||||
encrypt = false;
|
encrypt = false;
|
||||||
if (!sign) return null;
|
if (!sign) return plaintextFallback();
|
||||||
}
|
}
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
|
|||||||
+29
-17
@@ -6,22 +6,22 @@ const selectAllPgpKeyUi = pgpKeyMailUi.selectAll;
|
|||||||
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
const escapePgpKeyUi = pgpKeyMailUi.escapeHtml;
|
||||||
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
const toastPgpKeyUi = pgpKeyMailUi.toast;
|
||||||
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
||||||
|
async function saveAndroidPgpExport(label, value) {
|
||||||
|
if (window.daybreakMail?.pgp?.platform !== 'android' || typeof value !== 'string') return value;
|
||||||
|
const warning = /private|revocation/i.test(label) ? ' This contains secret key material; keep it private.' : '';
|
||||||
|
if (!confirm(`Copy this ${label.toLowerCase()} to the clipboard?${warning}`)) return { canceled: true };
|
||||||
|
if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(value);
|
||||||
|
else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true };
|
||||||
|
return { saved: true };
|
||||||
|
}
|
||||||
|
|
||||||
function openEncryptionKeys() {
|
function openEncryptionKeys() {
|
||||||
const root = selectPgpKeyUi('#modal-root');
|
const root = selectPgpKeyUi('#modal-root');
|
||||||
const account = window.epMailFeatures.mail.connectedAccount || {};
|
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">
|
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
|
||||||
<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 serverSettings = androidPgp
|
||||||
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
? '<h3 class="pgp-heading">Public key servers</h3><p class="account-note">Key-server lookup and publication are disabled in Android testing. Import a public key directly and compare its fingerprint with the owner.</p><div hidden><div id="pgp-server-list"></div><input id="pgp-search-email"><button id="pgp-find-key"></button><div id="pgp-found-keys"></div><select id="pgp-publish-server"></select><input id="pgp-server-name"><input id="pgp-server-url"><select id="pgp-server-protocol"></select><button id="pgp-add-server"></button></div>'
|
||||||
<h3 class="pgp-heading">Change a key passphrase</h3>
|
: `<h3 class="pgp-heading">Public key servers</h3>
|
||||||
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
|
||||||
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
|
||||||
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
|
||||||
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
|
||||||
<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>
|
<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>
|
<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>
|
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
@@ -33,7 +33,19 @@ function openEncryptionKeys() {
|
|||||||
<label class="compose-line"><span>Name</span><input id="pgp-server-name" maxlength="60" placeholder="My key server"></label>
|
<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>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>
|
<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>
|
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
|
||||||
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
||||||
|
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
||||||
|
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
||||||
|
<h3 class="pgp-heading">Change a key passphrase</h3>
|
||||||
|
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
||||||
|
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
|
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
||||||
|
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
||||||
|
<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>
|
||||||
|
${serverSettings}
|
||||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||||
@@ -140,7 +152,7 @@ function openEncryptionKeys() {
|
|||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||||
try {
|
try {
|
||||||
const result = await run();
|
const result = await saveAndroidPgpExport(label, await run());
|
||||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||||
} catch (error) { status(error.message || 'That action failed.'); }
|
} catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
@@ -188,7 +200,7 @@ function openEncryptionKeys() {
|
|||||||
if (!passphrase) return;
|
if (!passphrase) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
||||||
status(result.canceled ? '' : 'Key imported.');
|
status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.');
|
||||||
await render();
|
await render();
|
||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
@@ -241,7 +253,7 @@ function openEncryptionKeys() {
|
|||||||
button.className = 'discard';
|
button.className = 'discard';
|
||||||
button.textContent = label;
|
button.textContent = label;
|
||||||
button.onclick = async () => {
|
button.onclick = async () => {
|
||||||
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||||
catch (error) { status(error.message || 'That action failed.'); }
|
catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
@@ -403,7 +415,7 @@ function openEncryptionKeys() {
|
|||||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||||
void renderKeyServers();
|
if (!androidPgp) void renderKeyServers();
|
||||||
void renderContacts();
|
void renderContacts();
|
||||||
void render();
|
void render();
|
||||||
}
|
}
|
||||||
|
|||||||
+10007
-26
File diff suppressed because one or more lines are too long
+12
-4
@@ -27,16 +27,24 @@ 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('#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();
|
selectProductivityUi('#profile-name').focus();
|
||||||
}
|
}
|
||||||
function openPreferences() {
|
async function openPreferences() {
|
||||||
const root=selectProductivityUi('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
||||||
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
||||||
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save appearance</button></div></div></div>`;
|
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
|
||||||
|
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled?window.daybreakMail:null;
|
||||||
|
let notificationPrivacy={showDetails:false};
|
||||||
|
let appLockSettings={enabled:false,deviceSecure:false};
|
||||||
|
if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}}
|
||||||
|
if(appLockBridge){try{appLockSettings=await appLockBridge.getAppLockSettings()}catch(error){toastProductivityUi(error.message||'Could not load app-lock settings');return}}
|
||||||
|
const notificationSetting=notificationBridge?`<label class="compose-line"><span>Show sender and subject in notifications</span><input id="show-notification-details" type="checkbox"${notificationPrivacy.showDetails?' checked':''}></label><p class="account-note">Off by default. Android still hides private details from lock-screen previews.</p>`:'';
|
||||||
|
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><p class="account-note">Requires a secure Android screen lock. Mail sync continues in the background; unlock with your device PIN, pattern, or password when you return.</p>`:'';
|
||||||
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
||||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
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.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')}};
|
||||||
selectProductivityUi('#theme-select').focus();
|
selectProductivityUi('#theme-select').focus();
|
||||||
}
|
}
|
||||||
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
|
function 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 +80,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
|||||||
}
|
}
|
||||||
return baseMessageRenderer();
|
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({
|
window.epMailFeatures.productivity = Object.freeze({
|
||||||
get events() { return savedEvents; },
|
get events() { return savedEvents; },
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
const CACHE='ep-mail-v12';
|
const CACHE='ep-mail-v18';
|
||||||
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
|
||||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
|
||||||
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
||||||
|
|||||||
+93
-2
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user