Compare commits
8
Commits
V0.5.12
...
8a798fec6b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a798fec6b | ||
|
|
5b8aafe22c | ||
|
|
89c45fcf63 | ||
|
|
d7b6e31518 | ||
|
|
b14209a5ae | ||
|
|
d0b26db9ee | ||
|
|
78989f7b56 | ||
|
|
5f456e64d0 |
+16
-15
@@ -7,18 +7,18 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU
|
|||||||
## Implementation progress (2026-11-03)
|
## Implementation progress (2026-11-03)
|
||||||
|
|
||||||
- **Phase 0 — Baseline:** The merged release manifest and core WebView/network settings have now been reviewed and hardened. TLS certificate integration tests, the complete plugin audit, and a production-signed APK review remain open, so the Phase 0 release gate is not closed.
|
- **Phase 0 — Baseline:** The merged release manifest and core WebView/network settings have now been reviewed and hardened. TLS certificate integration tests, the complete plugin audit, and a production-signed APK review remain open, so the Phase 0 release gate is not closed.
|
||||||
- **Phase 1 — Local data/privacy:** Notification privacy, immediate background app locking, `FLAG_SECURE` while locked, account-removal disclosure, and a fail-closed missing-key recovery screen are implemented. Vault lifecycle, complete deletion semantics, and app-lock lifecycle/biometric follow-up remain open.
|
- **Phase 1 — Local data/privacy:** Notification privacy, configurable app locking, `FLAG_SECURE` from backgrounding, account-removal disclosure, explicit full local-data deletion, and fail-closed missing-key recovery are implemented. Vault lifecycle and automated device/lifecycle tests remain open.
|
||||||
- **Phase 2 — Android OpenPGP:** Experimental test implementation is present. It is not security-reviewed or release-complete.
|
- **Phase 2 — Android OpenPGP:** The experimental implementation now includes optional authentication-bound biometric/device-credential release of PGP passphrases, with passphrase fallback and invalidation recovery. It is not security-reviewed or release-complete.
|
||||||
- **Phase 3 — WebView/bridge:** Important protections are implemented; complete bridge review and device/content testing remain open.
|
- **Phase 3 — WebView/bridge:** CSP, navigation, sanitizer, and plugin-surface regression checks are automated; complete bridge review and device/content testing remain open.
|
||||||
- **Phase 4 — Assurance:** Open; independent review, release assurance, and vulnerability/maintenance work remain.
|
- **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.
|
Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed.
|
||||||
|
|
||||||
OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, on-demand PGP/MIME or inline-encrypted-message decryption, and verification of signed-only PGP/MIME and clear-signed messages. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**.
|
OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, on-demand PGP/MIME or inline-encrypted-message decryption, and verification of signed-only PGP/MIME and clear-signed messages. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sends when keys exist or encryption was requested; every renderer-produced raw MIME send also requires a native confirmation because the native layer cannot cryptographically verify its encryption. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**.
|
||||||
|
|
||||||
**Validation evidence:** DAV URL, attachment-name, notification privacy, Android OpenPGP policy decisions, one-shot confirmation callbacks, and the missing-vault-key policy have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock/unlock; with the lock active, emulator screenshots were fully obscured, and unlocking/turning the setting off restored the app. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. The Android OpenPGP module also has automated GnuPG interoperability tests in a Node harness, but those are not device-level mail tests. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Current validation: 157 Node tests and 21 Android unit tests pass; the Android debug build and release-manifest task succeed. Device testing of vault-corruption/key-loss recovery, invalid-certificate integration tests, production-signed APK review, and automated instrumentation of the actual confirmation dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android.
|
**Validation evidence:** DAV URL, attachment-name, notification privacy, app-lock delay policy, app-owned Downloads selection, Android OpenPGP policy decisions, unverified-recipient confirmation, raw-MIME native warning policy, one-shot confirmation callbacks, bounded preview reads, and the missing-vault-key policy have Android unit tests. The latest run passed all 162 Node tests and all 26 Android unit tests; debug APK assembly and the release-manifest processing task also succeeded. The Android PGP module's Node-harness tests cover encrypted-message flows, passphrase-verified biometric unlock, invalidation error propagation, and manual passphrase recovery; they do not exercise Android Keystore prompts or OS-level invalidation. The app lock was previously exercised on an emulator with a device PIN, including background lock/unlock and screenshot obscuring; the new delay choices still need device lifecycle testing. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were previously exercised on an emulator; actual dialog automation remains open. The Android OpenPGP module also has automated GnuPG interoperability tests in a Node harness, but those are not device-level mail tests. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Device testing of vault-corruption/key-loss recovery, biometric enrollment invalidation, invalid-certificate integration, production-signed APK review, and automated instrumentation of native dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android.
|
||||||
|
|
||||||
**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation 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.
|
**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation/biometric dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric invalidation tests; invalid-certificate integration tests; production-signed APK/manifest review; app-lock process-recreation testing; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain.
|
||||||
|
|
||||||
## Goals and limits
|
## Goals and limits
|
||||||
|
|
||||||
@@ -51,9 +51,10 @@ These are implementation observations, not proof that all paths are safe. In par
|
|||||||
### Phase 1 — Local data and privacy controls (P0)
|
### Phase 1 — Local data and privacy controls (P0)
|
||||||
|
|
||||||
- [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. If the key alias is missing while encrypted data remains, the app now refuses to generate a replacement key and shows a recovery screen; it does not reset or expose the data. Add device tests for missing/invalidated keys, corrupted ciphertext, reinstall/migration handling, and the recovery instructions; verify no plaintext fallback for all stored data.
|
- [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. If the key alias is missing while encrypted data remains, the app now refuses to generate a replacement key and shows a recovery screen; it does not reset or expose the data. Add device tests for missing/invalidated keys, corrupted ciphertext, reinstall/migration handling, and the recovery instructions; verify no plaintext fallback for all stored data.
|
||||||
- [~] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation now says downloaded attachment files and global OpenPGP keys are retained. Decide/test whether a separate app-data wipe should remove app-created Downloads and PGP keys; account removal intentionally leaves those user data intact.
|
- [x] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation says downloaded attachment files and global OpenPGP keys are retained.
|
||||||
|
- [~] A separate native-confirmed full-data wipe removes vault contents, account and PGP Keystore keys, app-owned Downloads attachments, WebView data, service-worker registrations/caches, and renderer local settings. It is distinct from account removal; Android storage-failure and end-to-end deletion tests remain open.
|
||||||
- [x] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting.
|
- [x] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting.
|
||||||
- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` while locked to hide task-switcher content and block screenshots; emulator smoke testing confirmed screenshots are obscured. Background sync continues and the setting is off unless enabled. Delayed lock, automated lifecycle/process-recreation tests, biometric UX, and recovery polish remain open.
|
- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` as soon as the app leaves the foreground. Users may choose immediate, 30-second, 1-minute, or 5-minute locking; the default is immediate. Background sync continues and the setting is off unless enabled. Emulator testing of the new delays, automated lifecycle/process-recreation tests, and recovery polish remain open.
|
||||||
- [x] Background sync is separate from the UI lock. Further verification of which credentials/key material are available to background workers remains part of the vault lifecycle review.
|
- [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.
|
||||||
@@ -61,21 +62,21 @@ These are implementation observations, not proof that all paths are safe. In par
|
|||||||
### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity)
|
### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity)
|
||||||
|
|
||||||
- [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Automated Node-harness tests exercise the Android module against GnuPG; independent review and on-device GnuPG/Thunderbird interoperability remain release blockers.
|
- [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Automated Node-harness tests exercise the Android module against GnuPG; independent review and on-device GnuPG/Thunderbird interoperability remain release blockers.
|
||||||
- [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized. Biometric wrapping-key release, lifecycle/recovery handling, and automated checks against unprotected-key persistence remain open.
|
- [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized in that store. Optional PGP passphrase release is separately encrypted by an authentication-bound Android Keystore key; biometric/device-credential invalidation clears the wrapper and falls back to the original passphrase. Device-level invalidation/recovery tests and automated at-rest checks remain open.
|
||||||
- [ ] Add optional biometric/device-credential release of PGP key access and test Keystore invalidation/recovery. Background sync does not use PGP private keys.
|
- [x] Optional biometric/device-credential release of PGP key access is available per key; the default remains passphrase-only, and background sync does not use PGP private keys.
|
||||||
- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, trust, and public keys offered as message attachments (never imported silently). Native prompts guard trust elevation and replacement; automated cancel/confirm regression tests remain open.
|
- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, trust, and public keys offered as message attachments (never imported silently). Trust elevation and replacement are guarded; encryption to keys not fingerprint-verified now requires an explicit per-send confirmation showing the recipient and full fingerprint. Automated native cancel/confirm regression tests remain open.
|
||||||
- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open.
|
- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open.
|
||||||
- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open.
|
- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; every raw MIME send now requires native confirmation because the native layer cannot cryptographically verify renderer-produced encryption. The native send path also checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open.
|
||||||
- [x] Key-server lookup and publication are disabled in the initial Android test implementation.
|
- [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)
|
||||||
|
|
||||||
- [~] 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.
|
- [~] Mail HTML is sanitized, remote images are blocked until per-message approval, and CSP restrictions are in place. Source-level CSP checks are automated; verify generated release assets and behavior on supported devices.
|
||||||
- [x] External URLs are constrained and require user confirmation before opening outside the WebView; unsafe schemes are rejected.
|
- [x] External URLs are constrained and require user confirmation before opening outside the WebView; unsafe schemes are rejected.
|
||||||
- [~] Broad unused filesystem/navigation capabilities have been removed, but a complete review of every Capacitor plugin/method and permission remains open.
|
- [~] Broad unused filesystem/navigation capabilities have been removed. Automated checks cover CSP, manifest permissions, external URL constraints, DAV redirects, and selected bridge methods; a complete method-by-method plugin review remains open.
|
||||||
- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open.
|
- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. Text/image previews use bounded stream reads, while attachment downloads stream to app storage. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open.
|
||||||
|
|
||||||
**Exit criteria:** automated CSP/navigation/bridge tests, sanitizer regressions, and a manual WebView inspection on the minimum and target Android versions.
|
**Exit criteria:** automated CSP/navigation/bridge tests, sanitizer regressions, and a manual WebView inspection on the minimum and target Android versions.
|
||||||
|
|
||||||
|
|||||||
+5
-5
@@ -1,6 +1,6 @@
|
|||||||
# Encryption plan: OpenPGP mail encryption for ep-mail
|
# Encryption plan: OpenPGP mail encryption for ep-mail
|
||||||
|
|
||||||
Status: **Desktop implementation is complete; an experimental Android Phase 2 path is available for local testing only.** Native confirmation prompts are implemented in that test path, but automated bypass testing, Android interoperability, independent security review, and release assurance remain open. The Android test path must not be used for sensitive mail. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for details. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
|
Status: **Desktop implementation is complete; an experimental Android Phase 2 path is available for local testing only.** It now includes per-key authentication-bound biometric/device-credential passphrase release, with passphrase fallback. Native confirmation prompts are implemented, but actual Android biometric/device testing, automated bypass testing, on-device interoperability, independent security review, and release assurance remain open. Do not use the Android test path for sensitive mail. See [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md) for details. Automated review findings and their fixes are documented in [SECURITY_REVIEW.md](./SECURITY_REVIEW.md); see [TODO.md](./TODO.md) for follow-up work.
|
||||||
|
|
||||||
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
|
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
|
||||||
|
|
||||||
@@ -22,8 +22,8 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
**Private keys**
|
**Private keys**
|
||||||
- One or more keys per account; never stored unprotected and never sent anywhere.
|
- One or more keys per account; never stored unprotected and never sent anywhere.
|
||||||
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
|
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
|
||||||
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4).
|
- Android test implementation: private keys remain passphrase-protected inside the Keystore-encrypted vault. An optional per-key Android Keystore authentication-bound wrapper can release a cached PGP passphrase after biometric/device-credential authentication. This wrapper and its invalidation recovery have not been independently reviewed or fully device-tested; passphrase entry remains the fallback.
|
||||||
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk.
|
- Desktop passphrases are cached in memory for a configurable time, then cleared. Android never stores plaintext passphrases; its optional experimental biometric feature persists only the authentication-bound Keystore ciphertext. Both paths need platform-specific expiry/invalidation assurance before security claims.
|
||||||
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
|
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
|
||||||
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
|
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
|||||||
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) |
|
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | Done (desktop) |
|
||||||
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
|
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
|
||||||
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
|
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
|
||||||
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open |
|
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android test path implemented, review/device assurance open |
|
||||||
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
|
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
|
||||||
| 6 | Docs, security review, release | Docs and release done; independent review open |
|
| 6 | Docs, security review, release | Docs and release done; independent review open |
|
||||||
|
|
||||||
@@ -96,6 +96,6 @@ The desktop Settings → Encryption keys view can search and publish through:
|
|||||||
|
|
||||||
All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification.
|
All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification.
|
||||||
|
|
||||||
Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is not included because Android OpenPGP support is not implemented.
|
Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is intentionally disabled in the experimental Android scope.
|
||||||
|
|
||||||
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
|
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
|
||||||
|
|||||||
@@ -27,6 +27,16 @@ npm run android:apk
|
|||||||
|
|
||||||
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
The debug APK is written to `android/app/build/outputs/apk/debug/app-debug.apk` and copied to `release/ep-mail <version>-debug.apk`; install it on a connected test device with `adb install -r android/app/build/outputs/apk/debug/app-debug.apk`. For a signed release, configure `EP_MAIL_ANDROID_STORE_FILE` (an absolute path), `EP_MAIL_ANDROID_STORE_PASSWORD`, `EP_MAIL_ANDROID_KEY_ALIAS`, and `EP_MAIL_ANDROID_KEY_PASSWORD` in the build environment, then run `npm run android:release-apk`. The signed artifact is copied to `release/ep-mail <version>.apk`; keep keystores and passwords out of the repository and logs. The first account enables a visible, ongoing foreground-service notification while IMAP IDLE checks for new mail; Android also runs a network-constrained periodic reconciliation. Notification sender/subject details are hidden by default; enabling them in Settings still keeps lock-screen previews redacted. Android may delay or stop background activity after force-stop, prolonged device restrictions, or vendor battery management.
|
||||||
|
|
||||||
|
Android builds use the Gradle wrapper and Android Gradle Plugin 9.4.0. Capacitor's generated modules are aligned to that plugin version during the build; the legacy Android DSL and external Kotlin plugin remain enabled for compatibility and must be migrated before upgrading to AGP 10.
|
||||||
|
|
||||||
|
On Android, previously cached folder messages appear while the mailbox refreshes; a folder without cached messages still needs to load from the server. Folder discovery and message actions run separately from cached-folder loading. The app stays in the message list until you select a message; returning to the list does not automatically reopen the newest message.
|
||||||
|
|
||||||
|
While reading a message on Android, swipe in from the screen edge using the system Back gesture, or use the Back button in the reader, to return to the same position in the message list.
|
||||||
|
|
||||||
|
In connected IMAP folders, scrolling to the end of the message list loads the next page automatically. The **Load more** button remains available as a manual fallback. On Android, background refreshes wait while you browse down the list so they do not replace older messages; return to the top or press Refresh to apply pending updates.
|
||||||
|
|
||||||
|
After upgrading from an older Android build, close and reopen ep-mail once if it still shows the previous interface. This lets the updated offline app shell take control without clearing account data.
|
||||||
|
|
||||||
## Run on Windows or Linux
|
## Run on Windows or Linux
|
||||||
|
|
||||||
Install Python 3, open a terminal in this folder, and run:
|
Install Python 3, open a terminal in this folder, and run:
|
||||||
|
|||||||
@@ -35,8 +35,9 @@
|
|||||||
- [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation.
|
- [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation.
|
||||||
- [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions.
|
- [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions.
|
||||||
- [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness.
|
- [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness.
|
||||||
|
- [x] Add optional per-key Android biometric/device-credential passphrase release with passphrase fallback.
|
||||||
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review.
|
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review.
|
||||||
- [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, remaining signature parity/device interoperability, and dependency advisory remediation.
|
- [ ] Android follow-up: device-test biometric prompt/key invalidation recovery, full vault lifecycle/recovery, remaining parity/device interoperability, and dependency advisory remediation.
|
||||||
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
||||||
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
|
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
|
||||||
- [x] Phase 6: documentation and release.
|
- [x] Phase 6: documentation and release.
|
||||||
@@ -55,7 +56,7 @@
|
|||||||
- [x] Refuse to generate a replacement Keystore key when encrypted vault data already exists; show a fail-closed recovery screen with clear-data guidance.
|
- [x] Refuse to generate a replacement Keystore key when encrypted vault data already exists; show a fail-closed recovery screen with clear-data guidance.
|
||||||
- [ ] Device-test missing/invalidated Keystore keys, corrupted vault data, migration/reinstall behavior, and recovery instructions.
|
- [ ] Device-test missing/invalidated Keystore keys, corrupted vault data, migration/reinstall behavior, and recovery instructions.
|
||||||
- [ ] Define/test full app-data deletion and downloaded-file/OpenPGP-key retention or removal behavior.
|
- [ ] Define/test full app-data deletion and downloaded-file/OpenPGP-key retention or removal behavior.
|
||||||
- [ ] Add app-lock timeout/delay options and decide whether to add biometric unlock; test process recreation and lifecycle transitions.
|
- [ ] Add app-lock timeout/delay process/lifecycle tests and decide whether to add biometric unlock to the separate app lock (PGP per-key biometric release is implemented experimentally).
|
||||||
|
|
||||||
## Appearance and settings
|
## Appearance and settings
|
||||||
|
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ android {
|
|||||||
buildTypes {
|
buildTypes {
|
||||||
release {
|
release {
|
||||||
minifyEnabled false
|
minifyEnabled false
|
||||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||||
if (hasCompleteReleaseSigning) signingConfig signingConfigs.release
|
if (hasCompleteReleaseSigning) signingConfig signingConfigs.release
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -80,6 +80,7 @@ dependencies {
|
|||||||
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
||||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||||
|
implementation 'androidx.biometric:biometric:1.1.0'
|
||||||
implementation project(':capacitor-android')
|
implementation project(':capacitor-android')
|
||||||
implementation 'com.sun.mail:android-mail:1.6.7'
|
implementation 'com.sun.mail:android-mail:1.6.7'
|
||||||
implementation 'com.sun.mail:android-activation:1.6.7'
|
implementation 'com.sun.mail:android-activation:1.6.7'
|
||||||
|
|||||||
@@ -68,6 +68,8 @@ internal object AndroidAccountVault {
|
|||||||
|
|
||||||
fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false)
|
fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false)
|
||||||
|
|
||||||
|
fun appLockDelaySeconds(): Int = read().optInt("appLockDelaySeconds", 0)
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun setAppLockEnabled(enabled: Boolean): Boolean {
|
fun setAppLockEnabled(enabled: Boolean): Boolean {
|
||||||
val store = read().put("appLockEnabled", enabled)
|
val store = read().put("appLockEnabled", enabled)
|
||||||
@@ -75,14 +77,69 @@ internal object AndroidAccountVault {
|
|||||||
return enabled
|
return enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun setAppLockDelaySeconds(seconds: Int): Int {
|
||||||
|
AndroidAppLockPolicy.requireValidDelay(seconds)
|
||||||
|
val store = read().put("appLockDelaySeconds", seconds)
|
||||||
|
write(store)
|
||||||
|
return seconds
|
||||||
|
}
|
||||||
|
|
||||||
fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) }
|
fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) }
|
||||||
?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject())
|
?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject())
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun savePgpStore(candidate: JSONObject) {
|
fun savePgpStore(candidate: JSONObject) {
|
||||||
validatePgpStore(candidate)
|
validatePgpStore(candidate)
|
||||||
val store = read().put("pgpStore", JSONObject(candidate.toString()))
|
val store = read()
|
||||||
|
val previousKeys = store.optJSONObject("pgpStore")?.optJSONArray("keys") ?: JSONArray()
|
||||||
|
val nextFingerprints = (0 until (candidate.optJSONArray("keys")?.length() ?: 0))
|
||||||
|
.mapNotNull { candidate.optJSONArray("keys")?.optJSONObject(it)?.optString("fingerprint") }
|
||||||
|
.map { it.uppercase(Locale.ROOT) }
|
||||||
|
.toSet()
|
||||||
|
val removedFingerprints = (0 until previousKeys.length())
|
||||||
|
.mapNotNull { previousKeys.optJSONObject(it)?.optString("fingerprint") }
|
||||||
|
.filter { it.uppercase(Locale.ROOT) !in nextFingerprints }
|
||||||
|
val biometricUnlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject()
|
||||||
|
removedFingerprints.forEach { biometricUnlocks.remove(it.uppercase(Locale.ROOT)) }
|
||||||
|
store.put("pgpBiometricUnlocks", biometricUnlocks)
|
||||||
|
store.put("pgpStore", JSONObject(candidate.toString()))
|
||||||
write(store)
|
write(store)
|
||||||
|
removedFingerprints.forEach(AndroidPgpBiometricUnlock::deleteKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun pgpBiometricUnlock(fingerprint: String): String? =
|
||||||
|
read().optJSONObject("pgpBiometricUnlocks")?.optString(fingerprint.uppercase(Locale.ROOT))
|
||||||
|
?.takeIf(String::isNotBlank)
|
||||||
|
|
||||||
|
fun hasPgpBiometricUnlock(fingerprint: String): Boolean =
|
||||||
|
pgpBiometricUnlock(fingerprint) != null
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun setPgpBiometricUnlock(fingerprint: String, ciphertext: String?) {
|
||||||
|
require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) {
|
||||||
|
"The OpenPGP fingerprint is invalid."
|
||||||
|
}
|
||||||
|
val store = read()
|
||||||
|
val unlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject()
|
||||||
|
val key = fingerprint.uppercase(Locale.ROOT)
|
||||||
|
if (ciphertext.isNullOrBlank()) unlocks.remove(key)
|
||||||
|
else {
|
||||||
|
require(ciphertext.length <= 16_384) { "Biometric key unlock data is too large." }
|
||||||
|
unlocks.put(key, ciphertext)
|
||||||
|
}
|
||||||
|
store.put("pgpBiometricUnlocks", unlocks)
|
||||||
|
write(store)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun wipe() {
|
||||||
|
val prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
check(prefs.edit().clear().commit()) { "Could not delete encrypted local data." }
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
if (keyStore.containsAlias(KEY_ALIAS)) keyStore.deleteEntry(KEY_ALIAS)
|
||||||
|
AndroidPgpBiometricUnlock.deleteAllKeys()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validatePgpStore(candidate: JSONObject) {
|
private fun validatePgpStore(candidate: JSONObject) {
|
||||||
@@ -282,7 +339,7 @@ internal object AndroidAccountVault {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun cacheMessages(id: String, folder: String, messages: JSONArray) {
|
fun cacheMessages(id: String, folder: String, messages: JSONArray, replace: Boolean = false) {
|
||||||
val store = read()
|
val store = read()
|
||||||
val accounts = store.optJSONArray("accounts") ?: return
|
val accounts = store.optJSONArray("accounts") ?: return
|
||||||
for (index in 0 until accounts.length()) {
|
for (index in 0 until accounts.length()) {
|
||||||
@@ -291,16 +348,18 @@ internal object AndroidAccountVault {
|
|||||||
val cache = account.optJSONObject("mailCache") ?: JSONObject()
|
val cache = account.optJSONObject("mailCache") ?: JSONObject()
|
||||||
val previous = cache.optJSONArray(folder) ?: JSONArray()
|
val previous = cache.optJSONArray(folder) ?: JSONArray()
|
||||||
val merged = LinkedHashMap<String, JSONObject>()
|
val merged = LinkedHashMap<String, JSONObject>()
|
||||||
|
if (!replace) {
|
||||||
for (itemIndex in 0 until previous.length()) {
|
for (itemIndex in 0 until previous.length()) {
|
||||||
val item = previous.optJSONObject(itemIndex) ?: continue
|
val item = previous.optJSONObject(itemIndex) ?: continue
|
||||||
merged[item.optString("uid", item.optString("id"))] = item
|
merged[item.optString("uid", item.optString("id"))] = item
|
||||||
}
|
}
|
||||||
|
}
|
||||||
for (itemIndex in 0 until messages.length()) {
|
for (itemIndex in 0 until messages.length()) {
|
||||||
val item = messages.optJSONObject(itemIndex) ?: continue
|
val item = messages.optJSONObject(itemIndex) ?: continue
|
||||||
merged[item.optString("uid", item.optString("id"))] = item
|
merged[item.optString("uid", item.optString("id"))] = item
|
||||||
}
|
}
|
||||||
cache.put(folder, JSONArray().apply {
|
cache.put(folder, JSONArray().apply {
|
||||||
merged.values.toList().takeLast(30).forEach { put(it) }
|
merged.values.sortedByDescending { it.optLong("timestamp") }.take(30).forEach { put(it) }
|
||||||
})
|
})
|
||||||
account.put("mailCache", cache)
|
account.put("mailCache", cache)
|
||||||
write(store)
|
write(store)
|
||||||
@@ -311,7 +370,16 @@ internal object AndroidAccountVault {
|
|||||||
fun cachedFolder(id: String, folder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject? {
|
fun cachedFolder(id: String, folder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject? {
|
||||||
val account = account(id) ?: return null
|
val account = account(id) ?: return null
|
||||||
val cached = account.optJSONObject("mailCache")?.optJSONArray(folder) ?: return null
|
val cached = account.optJSONObject("mailCache")?.optJSONArray(folder) ?: return null
|
||||||
|
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
val matched = (0 until cached.length()).mapNotNull { cached.optJSONObject(it) }
|
val matched = (0 until cached.length()).mapNotNull { cached.optJSONObject(it) }
|
||||||
|
.filter { message ->
|
||||||
|
(0 until snoozed.length()).none { index ->
|
||||||
|
val item = snoozed.optJSONObject(index) ?: return@none false
|
||||||
|
item.optString("folder") == folder && item.optLong("uid") == message.optLong("uid") &&
|
||||||
|
item.optLong("dueAt") > now
|
||||||
|
}
|
||||||
|
}
|
||||||
.filter { matchesFilters(it, filters) }
|
.filter { matchesFilters(it, filters) }
|
||||||
.sortedByDescending { it.optLong("timestamp") }
|
.sortedByDescending { it.optLong("timestamp") }
|
||||||
val start = offset.coerceAtLeast(0)
|
val start = offset.coerceAtLeast(0)
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
internal object AndroidAppLockPolicy {
|
||||||
|
val allowedDelaySeconds = setOf(0, 30, 60, 300)
|
||||||
|
|
||||||
|
fun requireValidDelay(seconds: Int) {
|
||||||
|
require(seconds in allowedDelaySeconds) {
|
||||||
|
"Choose a supported app-lock delay."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
internal object AndroidDownloadPolicy {
|
||||||
|
fun isAppOwnedDownload(ownerPackage: String?, relativePath: String?, packageName: String): Boolean =
|
||||||
|
ownerPackage == packageName &&
|
||||||
|
relativePath?.trimEnd('/') == "Download"
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package studio.daybreak.mail
|
|||||||
|
|
||||||
import android.content.ContentValues
|
import android.content.ContentValues
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import android.content.ContentUris
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Environment
|
import android.os.Environment
|
||||||
import android.provider.MediaStore
|
import android.provider.MediaStore
|
||||||
@@ -13,6 +14,7 @@ import org.json.JSONObject
|
|||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.ByteArrayInputStream
|
||||||
import java.io.ByteArrayOutputStream
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.InputStream
|
||||||
import java.text.DateFormat
|
import java.text.DateFormat
|
||||||
import java.text.SimpleDateFormat
|
import java.text.SimpleDateFormat
|
||||||
import java.util.Calendar
|
import java.util.Calendar
|
||||||
@@ -25,6 +27,7 @@ import javax.activation.DataHandler
|
|||||||
import javax.mail.Address
|
import javax.mail.Address
|
||||||
import javax.mail.Authenticator
|
import javax.mail.Authenticator
|
||||||
import javax.mail.Flags
|
import javax.mail.Flags
|
||||||
|
import javax.mail.FetchProfile
|
||||||
import javax.mail.Folder
|
import javax.mail.Folder
|
||||||
import javax.mail.Message
|
import javax.mail.Message
|
||||||
import javax.mail.Multipart
|
import javax.mail.Multipart
|
||||||
@@ -43,6 +46,52 @@ import javax.mail.internet.MimeUtility
|
|||||||
internal object AndroidMailService {
|
internal object AndroidMailService {
|
||||||
data class SyncResult(val payload: JSONObject, val newCount: Int)
|
data class SyncResult(val payload: JSONObject, val newCount: Int)
|
||||||
|
|
||||||
|
fun deleteSavedAttachments(context: Context) {
|
||||||
|
if (Build.VERSION.SDK_INT >= 29) {
|
||||||
|
val columns = arrayOf(
|
||||||
|
MediaStore.MediaColumns._ID,
|
||||||
|
MediaStore.MediaColumns.OWNER_PACKAGE_NAME,
|
||||||
|
MediaStore.MediaColumns.RELATIVE_PATH
|
||||||
|
)
|
||||||
|
val cursor = context.contentResolver.query(
|
||||||
|
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
|
||||||
|
columns,
|
||||||
|
"${MediaStore.MediaColumns.RELATIVE_PATH} = ?",
|
||||||
|
arrayOf("${Environment.DIRECTORY_DOWNLOADS}/"),
|
||||||
|
null
|
||||||
|
) ?: throw IllegalStateException("Could not inspect saved attachments in Downloads.")
|
||||||
|
cursor.use {
|
||||||
|
val idColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
|
||||||
|
val ownerColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.OWNER_PACKAGE_NAME)
|
||||||
|
val pathColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.RELATIVE_PATH)
|
||||||
|
while (it.moveToNext()) {
|
||||||
|
if (!AndroidDownloadPolicy.isAppOwnedDownload(
|
||||||
|
it.getString(ownerColumn),
|
||||||
|
it.getString(pathColumn),
|
||||||
|
context.packageName
|
||||||
|
)) continue
|
||||||
|
val uri = ContentUris.withAppendedId(
|
||||||
|
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
|
||||||
|
it.getLong(idColumn)
|
||||||
|
)
|
||||||
|
context.contentResolver.delete(uri, null, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) ?: return
|
||||||
|
val files = directory.listFiles()
|
||||||
|
?: throw IllegalStateException("Could not inspect saved attachments in Downloads.")
|
||||||
|
for (file in files) {
|
||||||
|
if (file.isFile && !file.delete()) {
|
||||||
|
throw IllegalStateException("Could not delete an app-saved attachment from Downloads.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (directory.exists() && !directory.delete()) {
|
||||||
|
throw IllegalStateException("Could not remove the app's Downloads folder.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fun connect(account: JSONObject): JSONObject = withStore(account) { session, store ->
|
fun connect(account: JSONObject): JSONObject = withStore(account) { session, store ->
|
||||||
val inbox = store.getFolder("INBOX")
|
val inbox = store.getFolder("INBOX")
|
||||||
check(inbox.exists()) { "The inbox could not be found." }
|
check(inbox.exists()) { "The inbox could not be found." }
|
||||||
@@ -112,6 +161,13 @@ internal object AndroidMailService {
|
|||||||
val first = (end - 19).coerceAtLeast(1)
|
val first = (end - 19).coerceAtLeast(1)
|
||||||
val result = JSONArray()
|
val result = JSONArray()
|
||||||
val batch = folder.getMessages(first, end).reversed()
|
val batch = folder.getMessages(first, end).reversed()
|
||||||
|
val profile = FetchProfile().apply {
|
||||||
|
add(FetchProfile.Item.ENVELOPE)
|
||||||
|
add(FetchProfile.Item.FLAGS)
|
||||||
|
add(FetchProfile.Item.CONTENT_INFO)
|
||||||
|
add(UIDFolder.FetchProfileItem.UID)
|
||||||
|
}
|
||||||
|
folder.fetch(batch.toTypedArray(), profile)
|
||||||
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||||
val cached = JSONArray()
|
val cached = JSONArray()
|
||||||
for (message in batch) {
|
for (message in batch) {
|
||||||
@@ -126,7 +182,7 @@ internal object AndroidMailService {
|
|||||||
result.put(value)
|
result.put(value)
|
||||||
cached.put(value)
|
cached.put(value)
|
||||||
}
|
}
|
||||||
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached)
|
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached, replace = offset <= 0)
|
||||||
JSONObject().put("messages", result).put("total", total)
|
JSONObject().put("messages", result).put("total", total)
|
||||||
.put("start", first).put("end", end).put("folder", requestedFolder)
|
.put("start", first).put("end", end).put("folder", requestedFolder)
|
||||||
} finally {
|
} finally {
|
||||||
@@ -408,6 +464,7 @@ internal object AndroidMailService {
|
|||||||
return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT))
|
return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
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)
|
||||||
@@ -440,7 +497,7 @@ internal object AndroidMailService {
|
|||||||
val filename = input.optString("filename")
|
val filename = input.optString("filename")
|
||||||
val part = findAttachment(message, filename)
|
val part = findAttachment(message, filename)
|
||||||
?: throw IllegalStateException("No attachment was found in this message.")
|
?: throw IllegalStateException("No attachment was found in this message.")
|
||||||
saveAttachmentBytes(context, filename.ifBlank { "attachment" }, part.contentType, part.inputStream.readBytes())
|
saveAttachmentStream(context, filename.ifBlank { "attachment" }, part.contentType, part.inputStream)
|
||||||
} finally {
|
} finally {
|
||||||
folder.close(false)
|
folder.close(false)
|
||||||
}
|
}
|
||||||
@@ -461,7 +518,7 @@ internal object AndroidMailService {
|
|||||||
val none = JSONObject().put("kind", "none")
|
val none = JSONObject().put("kind", "none")
|
||||||
.put("reason", "No preview is available for this file type. Download it to open it.")
|
.put("reason", "No preview is available for this file type. Download it to open it.")
|
||||||
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
|
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
|
||||||
val bytes = part.inputStream.use { it.readBytes() }
|
val bytes = part.inputStream.use { BoundedInputReader.read(it, 5 * 1048576 + 1) }
|
||||||
if (bytes.size > 5 * 1048576) {
|
if (bytes.size > 5 * 1048576) {
|
||||||
none.put("reason", "This image is too large to preview. Download it instead.")
|
none.put("reason", "This image is too large to preview. Download it instead.")
|
||||||
} else {
|
} else {
|
||||||
@@ -470,7 +527,7 @@ internal object AndroidMailService {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
|
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
|
||||||
val bytes = part.inputStream.use { it.readBytes() }
|
val bytes = part.inputStream.use { BoundedInputReader.read(it, 100001) }
|
||||||
JSONObject().put("kind", "text")
|
JSONObject().put("kind", "text")
|
||||||
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
|
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
|
||||||
.put("truncated", bytes.size > 100000)
|
.put("truncated", bytes.size > 100000)
|
||||||
@@ -787,6 +844,10 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
|
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
|
||||||
|
return saveAttachmentStream(context, filename, contentType, ByteArrayInputStream(bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun saveAttachmentStream(context: Context, filename: String, contentType: String, input: InputStream): JSONObject {
|
||||||
val safeFilename = AttachmentNamePolicy.sanitize(filename)
|
val safeFilename = AttachmentNamePolicy.sanitize(filename)
|
||||||
val mimeType = contentType.substringBefore(';').ifBlank {
|
val mimeType = contentType.substringBefore(';').ifBlank {
|
||||||
MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
||||||
@@ -799,14 +860,41 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||||
?: throw IllegalStateException("Could not create the attachment in Downloads.")
|
?: throw IllegalStateException("Could not create the attachment in Downloads.")
|
||||||
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
try {
|
||||||
|
val output = context.contentResolver.openOutputStream(uri)
|
||||||
?: throw IllegalStateException("Could not write the attachment.")
|
?: throw IllegalStateException("Could not write the attachment.")
|
||||||
|
input.use { source -> output.use { source.copyTo(it) } }
|
||||||
|
} catch (error: Exception) {
|
||||||
|
try {
|
||||||
|
input.close()
|
||||||
|
} catch (cleanupError: Exception) {
|
||||||
|
error.addSuppressed(cleanupError)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
context.contentResolver.delete(uri, null, null)
|
||||||
|
} catch (cleanupError: Exception) {
|
||||||
|
error.addSuppressed(cleanupError)
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", safeFilename)
|
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", safeFilename)
|
||||||
}
|
}
|
||||||
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
|
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
|
||||||
?: throw IllegalStateException("Downloads storage is not available.")
|
?: throw IllegalStateException("Downloads storage is not available.")
|
||||||
val file = File(directory, safeFilename)
|
val file = File(directory, safeFilename)
|
||||||
file.writeBytes(bytes)
|
try {
|
||||||
|
file.outputStream().use { output -> input.use { it.copyTo(output) } }
|
||||||
|
} catch (error: Exception) {
|
||||||
|
try {
|
||||||
|
input.close()
|
||||||
|
} catch (cleanupError: Exception) {
|
||||||
|
error.addSuppressed(cleanupError)
|
||||||
|
}
|
||||||
|
if (file.exists() && !file.delete()) error.addSuppressed(
|
||||||
|
IllegalStateException("Could not remove the incomplete attachment from Downloads.")
|
||||||
|
)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename)
|
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
|
import android.security.keystore.KeyGenParameterSpec
|
||||||
|
import android.security.keystore.KeyPermanentlyInvalidatedException
|
||||||
|
import android.security.keystore.KeyProperties
|
||||||
|
import android.util.Base64
|
||||||
|
import androidx.biometric.BiometricManager
|
||||||
|
import java.security.KeyStore
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import javax.crypto.KeyGenerator
|
||||||
|
import javax.crypto.SecretKey
|
||||||
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
|
|
||||||
|
internal class PgpBiometricUnlockException(
|
||||||
|
val errorCode: String,
|
||||||
|
message: String,
|
||||||
|
cause: Throwable? = null
|
||||||
|
) : IllegalStateException(message, cause)
|
||||||
|
|
||||||
|
internal object AndroidPgpBiometricUnlock {
|
||||||
|
private const val ALIAS_PREFIX = "ep-mail-pgp-unlock-"
|
||||||
|
private const val GCM_TAG_BITS = 128
|
||||||
|
private const val IV_BYTES = 12
|
||||||
|
|
||||||
|
fun requireAvailable(context: Context) {
|
||||||
|
val authenticators = allowedAuthenticators()
|
||||||
|
val result = BiometricManager.from(context).canAuthenticate(authenticators)
|
||||||
|
require(result == BiometricManager.BIOMETRIC_SUCCESS) {
|
||||||
|
"Set up a strong biometric or device screen lock before enabling biometric key unlock."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encryptCipher(context: Context, fingerprint: String): Cipher {
|
||||||
|
requireAvailable(context)
|
||||||
|
try {
|
||||||
|
return createEncryptCipher(context, fingerprint)
|
||||||
|
} catch (_: KeyPermanentlyInvalidatedException) {
|
||||||
|
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
|
||||||
|
deleteKey(fingerprint)
|
||||||
|
return createEncryptCipher(context, fingerprint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createEncryptCipher(context: Context, fingerprint: String): Cipher {
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, secretKey(context, fingerprint))
|
||||||
|
return cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
fun decryptCipher(context: Context, fingerprint: String, ciphertext: String): Cipher {
|
||||||
|
val payload = try {
|
||||||
|
Base64.decode(ciphertext, Base64.NO_WRAP)
|
||||||
|
} catch (_: IllegalArgumentException) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_CORRUPT", "Biometric key unlock data is damaged. Enter the key passphrase and set it up again.")
|
||||||
|
}
|
||||||
|
require(payload.size > IV_BYTES) {
|
||||||
|
"Biometric key unlock data is damaged. Enter the key passphrase and set it up again."
|
||||||
|
}
|
||||||
|
val key = try {
|
||||||
|
secretKey(context, fingerprint, create = false)
|
||||||
|
} catch (_: KeyPermanentlyInvalidatedException) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
|
||||||
|
} catch (_: Exception) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric key unlock is unavailable. Enter the key passphrase and set it up again.")
|
||||||
|
}
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
try {
|
||||||
|
cipher.init(
|
||||||
|
Cipher.DECRYPT_MODE,
|
||||||
|
key,
|
||||||
|
GCMParameterSpec(GCM_TAG_BITS, payload.copyOfRange(0, IV_BYTES))
|
||||||
|
)
|
||||||
|
} catch (_: KeyPermanentlyInvalidatedException) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
|
||||||
|
}
|
||||||
|
return cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
fun seal(passphrase: String, cipher: Cipher): String {
|
||||||
|
require(passphrase.length in 1..4096) { "The key passphrase is empty or too long for biometric unlock." }
|
||||||
|
val plaintext = passphrase.toByteArray(Charsets.UTF_8)
|
||||||
|
val encrypted = try {
|
||||||
|
cipher.doFinal(plaintext)
|
||||||
|
} finally {
|
||||||
|
plaintext.fill(0)
|
||||||
|
}
|
||||||
|
return Base64.encodeToString(cipher.iv + encrypted, Base64.NO_WRAP)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun open(ciphertext: String, cipher: Cipher): String {
|
||||||
|
val payload = Base64.decode(ciphertext, Base64.NO_WRAP)
|
||||||
|
val plaintext = cipher.doFinal(payload.copyOfRange(IV_BYTES, payload.size))
|
||||||
|
return String(plaintext, Charsets.UTF_8).also { plaintext.fill(0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteKey(fingerprint: String) {
|
||||||
|
val alias = alias(fingerprint)
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
if (keyStore.containsAlias(alias)) keyStore.deleteEntry(alias)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteAllKeys() {
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
val aliases = keyStore.aliases()
|
||||||
|
while (aliases.hasMoreElements()) {
|
||||||
|
val name = aliases.nextElement()
|
||||||
|
if (name.startsWith(ALIAS_PREFIX)) keyStore.deleteEntry(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun secretKey(context: Context, fingerprint: String, create: Boolean = true): SecretKey {
|
||||||
|
val alias = alias(fingerprint)
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
try {
|
||||||
|
(keyStore.getKey(alias, null) as? SecretKey)?.let { return it }
|
||||||
|
} catch (error: KeyPermanentlyInvalidatedException) {
|
||||||
|
throw error
|
||||||
|
} catch (error: Exception) {
|
||||||
|
throw IllegalStateException("Biometric key unlock is unavailable. Enter the key passphrase and set it up again.", error)
|
||||||
|
}
|
||||||
|
if (!create) {
|
||||||
|
throw PgpBiometricUnlockException(
|
||||||
|
"BIOMETRIC_INVALIDATED",
|
||||||
|
"Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
||||||
|
val spec = KeyGenParameterSpec.Builder(
|
||||||
|
alias,
|
||||||
|
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
|
||||||
|
)
|
||||||
|
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||||
|
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||||
|
.setKeySize(256)
|
||||||
|
.setRandomizedEncryptionRequired(true)
|
||||||
|
.setUserAuthenticationRequired(true)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
spec.setUserAuthenticationParameters(
|
||||||
|
0,
|
||||||
|
KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
spec.setUserAuthenticationValidityDurationSeconds(-1)
|
||||||
|
spec.setInvalidatedByBiometricEnrollment(true)
|
||||||
|
}
|
||||||
|
generator.init(spec.build())
|
||||||
|
return generator.generateKey()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun allowedAuthenticators(): Int =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
BiometricManager.Authenticators.BIOMETRIC_STRONG or
|
||||||
|
BiometricManager.Authenticators.DEVICE_CREDENTIAL
|
||||||
|
} else {
|
||||||
|
BiometricManager.Authenticators.BIOMETRIC_STRONG
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun alias(fingerprint: String): String {
|
||||||
|
require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) {
|
||||||
|
"The OpenPGP fingerprint is invalid."
|
||||||
|
}
|
||||||
|
return ALIAS_PREFIX + fingerprint.uppercase()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -76,6 +76,10 @@ internal object AndroidPgpPolicy {
|
|||||||
"The message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?"
|
"The message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun unverifiedRawMimeWarning(): String =
|
||||||
|
"Android cannot verify that this raw MIME message is actually encrypted. It may contain readable message content, including inside a deceptive OpenPGP wrapper. " +
|
||||||
|
"Signing alone does not encrypt a message. Continue only if you independently verified the MIME contents and intend to send them."
|
||||||
|
|
||||||
private fun safeLabel(values: List<String>): String =
|
private fun safeLabel(values: List<String>): String =
|
||||||
values.joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" }
|
values.joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" }
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.io.InputStream
|
||||||
|
|
||||||
|
internal object BoundedInputReader {
|
||||||
|
fun read(input: InputStream, maxBytes: Int): ByteArray {
|
||||||
|
require(maxBytes > 0) { "A positive byte limit is required." }
|
||||||
|
val output = ByteArrayOutputStream(minOf(maxBytes, 8192))
|
||||||
|
val buffer = ByteArray(8192)
|
||||||
|
while (output.size() < maxBytes) {
|
||||||
|
val count = input.read(buffer, 0, minOf(buffer.size, maxBytes - output.size()))
|
||||||
|
if (count < 0) break
|
||||||
|
if (count == 0) continue
|
||||||
|
output.write(buffer, 0, count)
|
||||||
|
}
|
||||||
|
return output.toByteArray()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import android.content.IntentFilter
|
|||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.app.AlertDialog
|
import android.app.AlertDialog
|
||||||
|
import androidx.biometric.BiometricPrompt
|
||||||
import com.getcapacitor.JSObject
|
import com.getcapacitor.JSObject
|
||||||
import com.getcapacitor.Plugin
|
import com.getcapacitor.Plugin
|
||||||
import com.getcapacitor.PluginCall
|
import com.getcapacitor.PluginCall
|
||||||
@@ -14,13 +15,20 @@ import com.getcapacitor.PluginMethod
|
|||||||
import com.getcapacitor.annotation.CapacitorPlugin
|
import com.getcapacitor.annotation.CapacitorPlugin
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
import java.util.concurrent.Executors
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import javax.mail.internet.InternetAddress
|
import javax.mail.internet.InternetAddress
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
|
||||||
@CapacitorPlugin(name = "EpMail")
|
@CapacitorPlugin(name = "EpMail")
|
||||||
class EpMailPlugin : Plugin() {
|
class EpMailPlugin : Plugin() {
|
||||||
private var syncReceiver: BroadcastReceiver? = null
|
private var syncReceiver: BroadcastReceiver? = null
|
||||||
|
private var wipeDialogShowing = false
|
||||||
|
private val mailboxExecutor = Executors.newFixedThreadPool(3)
|
||||||
|
private val folderListExecutor = Executors.newFixedThreadPool(2)
|
||||||
|
private val mailActionExecutor = Executors.newSingleThreadExecutor()
|
||||||
|
private val outboxExecutor = Executors.newSingleThreadExecutor()
|
||||||
|
|
||||||
override fun load() {
|
override fun load() {
|
||||||
AndroidAccountVault.initialize(context)
|
AndroidAccountVault.initialize(context)
|
||||||
@@ -55,6 +63,10 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun handleOnDestroy() {
|
override fun handleOnDestroy() {
|
||||||
|
mailboxExecutor.shutdown()
|
||||||
|
folderListExecutor.shutdown()
|
||||||
|
mailActionExecutor.shutdown()
|
||||||
|
outboxExecutor.shutdown()
|
||||||
syncReceiver?.let {
|
syncReceiver?.let {
|
||||||
try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {}
|
try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {}
|
||||||
}
|
}
|
||||||
@@ -93,6 +105,7 @@ class EpMailPlugin : Plugin() {
|
|||||||
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
||||||
call.resolve(JSObject()
|
call.resolve(JSObject()
|
||||||
.put("enabled", AndroidAccountVault.appLockEnabled())
|
.put("enabled", AndroidAccountVault.appLockEnabled())
|
||||||
|
.put("lockDelaySeconds", AndroidAccountVault.appLockDelaySeconds())
|
||||||
.put("deviceSecure", keyguard.isDeviceSecure))
|
.put("deviceSecure", keyguard.isDeviceSecure))
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
call.reject(error.message ?: "Could not read app-lock settings.")
|
call.reject(error.message ?: "Could not read app-lock settings.")
|
||||||
@@ -116,6 +129,17 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun setAppLockDelay(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val seconds = call.getInt("seconds")
|
||||||
|
?: throw IllegalArgumentException("Choose when ep-mail should lock after leaving it.")
|
||||||
|
call.resolve(JSObject().put("lockDelaySeconds", AndroidAccountVault.setAppLockDelaySeconds(seconds)))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save the app-lock delay.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun pgpLoadStore(call: PluginCall) {
|
fun pgpLoadStore(call: PluginCall) {
|
||||||
try {
|
try {
|
||||||
@@ -155,6 +179,130 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun setPgpBiometricUnlock(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val fingerprint = call.getString("fingerprint")
|
||||||
|
?: throw IllegalArgumentException("Choose an OpenPGP key.")
|
||||||
|
val passphrase = call.getString("passphrase")
|
||||||
|
?: throw IllegalArgumentException("Enter the key passphrase first.")
|
||||||
|
require(passphrase.length in 1..4096) { "The key passphrase is empty or too long for biometric unlock." }
|
||||||
|
require(AndroidAccountVault.pgpStore().optJSONArray("keys")?.let { keys ->
|
||||||
|
(0 until keys.length()).any { keys.optJSONObject(it)?.optString("fingerprint") == fingerprint }
|
||||||
|
} == true) { "That OpenPGP key is no longer available." }
|
||||||
|
val cipher = AndroidPgpBiometricUnlock.encryptCipher(context, fingerprint)
|
||||||
|
authenticatePgpCipher(call, cipher) { authenticated ->
|
||||||
|
try {
|
||||||
|
AndroidAccountVault.setPgpBiometricUnlock(
|
||||||
|
fingerprint,
|
||||||
|
AndroidPgpBiometricUnlock.seal(passphrase, authenticated)
|
||||||
|
)
|
||||||
|
call.resolve(JSObject().put("enabled", true))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not enable biometric key unlock.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not enable biometric key unlock.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun getPgpBiometricPassphrase(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val fingerprint = call.getString("fingerprint")
|
||||||
|
?: throw IllegalArgumentException("Choose an OpenPGP key.")
|
||||||
|
val ciphertext = AndroidAccountVault.pgpBiometricUnlock(fingerprint)
|
||||||
|
if (ciphertext == null) {
|
||||||
|
call.resolve(JSObject().put("enabled", false))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val cipher = AndroidPgpBiometricUnlock.decryptCipher(context, fingerprint, ciphertext)
|
||||||
|
authenticatePgpCipher(call, cipher) { authenticated ->
|
||||||
|
try {
|
||||||
|
call.resolve(JSObject()
|
||||||
|
.put("enabled", true)
|
||||||
|
.put("passphrase", AndroidPgpBiometricUnlock.open(ciphertext, authenticated)))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not unlock the OpenPGP key.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: PgpBiometricUnlockException) {
|
||||||
|
if (error.errorCode == "BIOMETRIC_INVALIDATED") {
|
||||||
|
try {
|
||||||
|
call.getString("fingerprint")?.let { fingerprint ->
|
||||||
|
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
|
||||||
|
AndroidPgpBiometricUnlock.deleteKey(fingerprint)
|
||||||
|
}
|
||||||
|
} catch (cleanupError: Exception) {
|
||||||
|
call.reject(cleanupError.message ?: "Biometric unlock expired and could not be cleared.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
call.reject(error.message ?: "Biometric key unlock is unavailable.", error.errorCode)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not unlock the OpenPGP key.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun removePgpBiometricUnlock(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val fingerprint = call.getString("fingerprint")
|
||||||
|
?: throw IllegalArgumentException("Choose an OpenPGP key.")
|
||||||
|
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
|
||||||
|
AndroidPgpBiometricUnlock.deleteKey(fingerprint)
|
||||||
|
call.resolve(JSObject().put("enabled", false))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not remove biometric key unlock.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun pgpBiometricUnlockEnabled(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val fingerprint = call.getString("fingerprint")
|
||||||
|
?: throw IllegalArgumentException("Choose an OpenPGP key.")
|
||||||
|
call.resolve(JSObject().put("enabled", AndroidAccountVault.hasPgpBiometricUnlock(fingerprint)))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not read biometric key-unlock settings.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun authenticatePgpCipher(call: PluginCall, cipher: Cipher, onAuthenticated: (Cipher) -> Unit) {
|
||||||
|
val host = activity as? MainActivity
|
||||||
|
if (host == null) {
|
||||||
|
call.reject("Biometric key unlock is not available in this activity.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
host.runOnUiThread {
|
||||||
|
try {
|
||||||
|
host.authenticatePgpCipher(cipher, object : BiometricPrompt.AuthenticationCallback() {
|
||||||
|
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
|
||||||
|
val authenticated = result.cryptoObject?.cipher
|
||||||
|
if (authenticated == null) {
|
||||||
|
call.reject("Android could not unlock the OpenPGP key.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
onAuthenticated(authenticated)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
|
||||||
|
val cancelled = errorCode == BiometricPrompt.ERROR_USER_CANCELED ||
|
||||||
|
errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON ||
|
||||||
|
errorCode == BiometricPrompt.ERROR_CANCELED
|
||||||
|
call.reject(
|
||||||
|
errString.toString(),
|
||||||
|
if (cancelled) "BIOMETRIC_CANCELLED" else "BIOMETRIC_FAILED"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not start biometric key unlock.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? {
|
private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? {
|
||||||
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
|
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
|
||||||
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
||||||
@@ -263,6 +411,41 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun deleteAllLocalData(call: PluginCall) {
|
||||||
|
if (wipeDialogShowing) {
|
||||||
|
call.reject("A local-data deletion is already awaiting confirmation.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wipeDialogShowing = true
|
||||||
|
AlertDialog.Builder(activity)
|
||||||
|
.setTitle("Delete all local data?")
|
||||||
|
.setMessage(
|
||||||
|
"This permanently deletes every saved mail and DAV account, downloaded and cached mail, drafts, queued sends, local settings, OpenPGP keys and contacts, and attachments saved by ep-mail to Downloads. Encrypted mail cannot be recovered without a separate key backup."
|
||||||
|
)
|
||||||
|
.setNegativeButton("Cancel") { _, _ ->
|
||||||
|
wipeDialogShowing = false
|
||||||
|
call.resolve(JSObject().put("deleted", false))
|
||||||
|
}
|
||||||
|
.setPositiveButton("Delete all data") { _, _ ->
|
||||||
|
wipeDialogShowing = false
|
||||||
|
try {
|
||||||
|
MailIdleService.stop(context)
|
||||||
|
AndroidMailService.deleteSavedAttachments(context)
|
||||||
|
AndroidAccountVault.wipe()
|
||||||
|
(activity as? MainActivity)?.clearLocalWebData()
|
||||||
|
call.resolve(JSObject().put("deleted", true))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not delete all local data.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.setOnCancelListener {
|
||||||
|
wipeDialogShowing = false
|
||||||
|
call.resolve(JSObject().put("deleted", false))
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun connect(call: PluginCall) {
|
fun connect(call: PluginCall) {
|
||||||
try {
|
try {
|
||||||
@@ -305,9 +488,15 @@ class EpMailPlugin : Plugin() {
|
|||||||
try {
|
try {
|
||||||
val account = AndroidAccountVault.account()
|
val account = AndroidAccountVault.account()
|
||||||
?: throw IllegalStateException("Add a mail account before listing folders.")
|
?: throw IllegalStateException("Add a mail account before listing folders.")
|
||||||
|
folderListExecutor.execute {
|
||||||
|
try {
|
||||||
call.resolve(AndroidMailService.listFolders(account).toJSObject())
|
call.resolve(AndroidMailService.listFolders(account).toJSObject())
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
call.resolve(JSObject().put("folders", org.json.JSONArray()).put("offline", true))
|
call.reject(error.message ?: "Could not list mail folders.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not list mail folders.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,6 +511,21 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun getCachedFolder(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val account = AndroidAccountVault.account()
|
||||||
|
?: throw IllegalStateException("Add a mail account before loading cached messages.")
|
||||||
|
val folder = call.getString("folder") ?: "Inbox"
|
||||||
|
val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0)
|
||||||
|
val filters = call.getObject("filters") ?: JSObject()
|
||||||
|
val cached = AndroidAccountVault.cachedFolder(account.optString("id"), folder, offset, JSONObject(filters.toString()))
|
||||||
|
call.resolve(JSObject().put("cached", cached ?: JSONObject.NULL))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not load cached messages.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun syncFolder(call: PluginCall) {
|
fun syncFolder(call: PluginCall) {
|
||||||
try {
|
try {
|
||||||
@@ -333,10 +537,31 @@ class EpMailPlugin : Plugin() {
|
|||||||
val selected = filterFolder?.takeIf { it in setOf("Inbox", "Sent", "Archive", "Trash", "Starred") } ?: requested
|
val selected = filterFolder?.takeIf { it in setOf("Inbox", "Sent", "Archive", "Trash", "Starred") } ?: requested
|
||||||
val folder = if (selected in setOf("Inbox", "Sent", "Archive", "Trash", "Starred", "Snoozed") || AndroidMailService.isCustomFolder(selected)) selected else "Inbox"
|
val folder = if (selected in setOf("Inbox", "Sent", "Archive", "Trash", "Starred", "Snoozed") || AndroidMailService.isCustomFolder(selected)) selected else "Inbox"
|
||||||
val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0)
|
val offset = (call.getInt("offset") ?: 0).coerceAtLeast(0)
|
||||||
AndroidMailService.flushOutbox(account)
|
mailboxExecutor.execute {
|
||||||
|
try {
|
||||||
call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject())
|
call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject())
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
call.reject(error.message ?: "Could not sync the mailbox.")
|
call.reject(error.message ?: "Could not sync the mailbox.")
|
||||||
|
return@execute
|
||||||
|
}
|
||||||
|
retryOutbox(account)
|
||||||
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not sync the mailbox.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun retryOutbox(account: JSONObject) {
|
||||||
|
try {
|
||||||
|
outboxExecutor.execute {
|
||||||
|
try {
|
||||||
|
AndroidMailService.flushOutbox(account)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
android.util.Log.e("EpMailOutbox", "Could not retry queued mail operations", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: java.util.concurrent.RejectedExecutionException) {
|
||||||
|
android.util.Log.w("EpMailOutbox", "Could not schedule queued mail retry", error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -345,18 +570,28 @@ class EpMailPlugin : Plugin() {
|
|||||||
try {
|
try {
|
||||||
val account = AndroidAccountVault.account()
|
val account = AndroidAccountVault.account()
|
||||||
?: throw IllegalStateException("Add a mail account before changing messages.")
|
?: throw IllegalStateException("Add a mail account before changing messages.")
|
||||||
call.resolve(AndroidMailService.updateMessage(account, call.data).toJSObject())
|
val input = JSONObject(call.data.toString())
|
||||||
|
mailActionExecutor.execute {
|
||||||
|
try {
|
||||||
|
call.resolve(AndroidMailService.updateMessage(account, input).toJSObject())
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
val account = AndroidAccountVault.account()
|
if (isConnectivityFailure(error)) {
|
||||||
if (account != null && isConnectivityFailure(error)) {
|
try {
|
||||||
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
|
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
|
||||||
.put("id", UUID.randomUUID().toString())
|
.put("id", UUID.randomUUID().toString())
|
||||||
.put("type", "action")
|
.put("type", "action")
|
||||||
.put("data", JSONObject(call.data.toString())))
|
.put("data", input))
|
||||||
call.resolve(JSObject().put("ok", true).put("queued", true))
|
call.resolve(JSObject().put("ok", true).put("queued", true))
|
||||||
|
} catch (queueError: Exception) {
|
||||||
|
call.reject(queueError.message ?: "Could not queue the message action.")
|
||||||
|
}
|
||||||
} else call.reject(error.message ?: "Could not update the message.")
|
} else call.reject(error.message ?: "Could not update the message.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not update the message.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun setSnooze(call: PluginCall) {
|
fun setSnooze(call: PluginCall) {
|
||||||
@@ -464,10 +699,11 @@ class EpMailPlugin : Plugin() {
|
|||||||
sendPrepared(call, input)
|
sendPrepared(call, input)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
val rawMime = input.optString("rawBase64").isNotBlank()
|
||||||
showPgpConfirmation(
|
showPgpConfirmation(
|
||||||
title = "Send without OpenPGP encryption?",
|
title = if (rawMime) "Send unverified MIME?" else "Send without OpenPGP encryption?",
|
||||||
message = warning,
|
message = warning,
|
||||||
confirmLabel = "Send plaintext",
|
confirmLabel = if (rawMime) "Send anyway" else "Send plaintext",
|
||||||
onConfirmed = { sendPrepared(call, input) },
|
onConfirmed = { sendPrepared(call, input) },
|
||||||
onCancelled = {
|
onCancelled = {
|
||||||
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
|
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
|
||||||
@@ -493,7 +729,7 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun plaintextSendWarning(input: JSONObject): String? {
|
private fun plaintextSendWarning(input: JSONObject): String? {
|
||||||
if (input.optString("rawBase64").isNotBlank()) return null
|
if (input.optString("rawBase64").isNotBlank()) return AndroidPgpPolicy.unverifiedRawMimeWarning()
|
||||||
val recipients = (listOf(input.optString("to"), input.optString("cc"))
|
val recipients = (listOf(input.optString("to"), input.optString("cc"))
|
||||||
.filter(String::isNotBlank)
|
.filter(String::isNotBlank)
|
||||||
.flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } })
|
.flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } })
|
||||||
|
|||||||
@@ -9,17 +9,26 @@ import android.graphics.Color;
|
|||||||
import android.net.Uri;
|
import android.net.Uri;
|
||||||
import android.os.Build;
|
import android.os.Build;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.os.Looper;
|
||||||
|
import android.os.SystemClock;
|
||||||
import android.view.Gravity;
|
import android.view.Gravity;
|
||||||
import android.view.View;
|
import android.view.View;
|
||||||
import android.view.ViewGroup;
|
import android.view.ViewGroup;
|
||||||
import android.view.WindowManager;
|
import android.view.WindowManager;
|
||||||
import android.webkit.WebView;
|
import android.webkit.WebView;
|
||||||
|
import android.webkit.WebStorage;
|
||||||
import android.widget.Button;
|
import android.widget.Button;
|
||||||
import android.widget.FrameLayout;
|
import android.widget.FrameLayout;
|
||||||
import android.widget.LinearLayout;
|
import android.widget.LinearLayout;
|
||||||
import android.widget.TextView;
|
import android.widget.TextView;
|
||||||
import androidx.core.app.ActivityCompat;
|
import androidx.core.app.ActivityCompat;
|
||||||
|
import androidx.core.content.ContextCompat;
|
||||||
|
import androidx.biometric.BiometricManager;
|
||||||
|
import androidx.biometric.BiometricPrompt;
|
||||||
|
import androidx.activity.OnBackPressedCallback;
|
||||||
import com.getcapacitor.BridgeActivity;
|
import com.getcapacitor.BridgeActivity;
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
|
||||||
public class MainActivity extends BridgeActivity {
|
public class MainActivity extends BridgeActivity {
|
||||||
private static final int UNLOCK_REQUEST_CODE = 705;
|
private static final int UNLOCK_REQUEST_CODE = 705;
|
||||||
@@ -28,14 +37,51 @@ public class MainActivity extends BridgeActivity {
|
|||||||
private Button appLockButton;
|
private Button appLockButton;
|
||||||
private boolean appLocked;
|
private boolean appLocked;
|
||||||
private boolean awaitingUnlockResult;
|
private boolean awaitingUnlockResult;
|
||||||
|
private boolean pgpAuthInProgress;
|
||||||
|
private boolean pgpAuthPaused;
|
||||||
|
private long pgpAuthPauseAt;
|
||||||
private boolean activityResumed;
|
private boolean activityResumed;
|
||||||
private boolean vaultRecoveryRequired;
|
private boolean vaultRecoveryRequired;
|
||||||
|
private final Handler appLockHandler = new Handler(Looper.getMainLooper());
|
||||||
|
private final Runnable delayedAppLock = () -> {
|
||||||
|
if (!activityResumed && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
|
||||||
|
};
|
||||||
|
private final Runnable lockAfterPgpAuth = () -> {
|
||||||
|
if (!activityResumed && pgpAuthPaused && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
|
||||||
|
};
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void onCreate(Bundle savedInstanceState) {
|
public void onCreate(Bundle savedInstanceState) {
|
||||||
registerPlugin(EpMailPlugin.class);
|
registerPlugin(EpMailPlugin.class);
|
||||||
super.onCreate(savedInstanceState);
|
super.onCreate(savedInstanceState);
|
||||||
hardenWebView();
|
hardenWebView();
|
||||||
|
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
|
||||||
|
@Override
|
||||||
|
public void handleOnBackPressed() {
|
||||||
|
if (appLocked || vaultRecoveryRequired || getBridge() == null || getBridge().getWebView() == null) {
|
||||||
|
dispatchDefaultBack();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
getBridge().getWebView().evaluateJavascript(
|
||||||
|
"(function(){if(document.body.classList.contains('reader-open') && " +
|
||||||
|
"!document.querySelector('#modal-root .modal-overlay')){" +
|
||||||
|
"const back=document.querySelector('#reader-back');if(back){back.click();return true;}}" +
|
||||||
|
"return false;})()",
|
||||||
|
result -> {
|
||||||
|
if (!"true".equals(result)) dispatchDefaultBack();
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void dispatchDefaultBack() {
|
||||||
|
setEnabled(false);
|
||||||
|
try {
|
||||||
|
getOnBackPressedDispatcher().onBackPressed();
|
||||||
|
} finally {
|
||||||
|
setEnabled(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
AndroidAccountVault.INSTANCE.initialize(getApplicationContext());
|
AndroidAccountVault.INSTANCE.initialize(getApplicationContext());
|
||||||
try {
|
try {
|
||||||
AndroidAccountVault.INSTANCE.read();
|
AndroidAccountVault.INSTANCE.read();
|
||||||
@@ -56,6 +102,10 @@ public class MainActivity extends BridgeActivity {
|
|||||||
super.onResume();
|
super.onResume();
|
||||||
if (vaultRecoveryRequired) return;
|
if (vaultRecoveryRequired) return;
|
||||||
activityResumed = true;
|
activityResumed = true;
|
||||||
|
appLockHandler.removeCallbacks(delayedAppLock);
|
||||||
|
appLockHandler.removeCallbacks(lockAfterPgpAuth);
|
||||||
|
pgpAuthPaused = false;
|
||||||
|
if (!appLocked) getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
if (isAppLockEnabled() && appLocked) {
|
if (isAppLockEnabled() && appLocked) {
|
||||||
lockWebView();
|
lockWebView();
|
||||||
configureUnlockButton();
|
configureUnlockButton();
|
||||||
@@ -65,7 +115,19 @@ public class MainActivity extends BridgeActivity {
|
|||||||
@Override
|
@Override
|
||||||
public void onPause() {
|
public void onPause() {
|
||||||
activityResumed = false;
|
activityResumed = false;
|
||||||
if (!vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
|
if (!vaultRecoveryRequired && isAppLockEnabled() && !pgpAuthInProgress) {
|
||||||
|
int delaySeconds = appLockDelaySeconds();
|
||||||
|
if (delaySeconds == 0) {
|
||||||
|
lockWebView();
|
||||||
|
} else {
|
||||||
|
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
appLockHandler.postDelayed(delayedAppLock, delaySeconds * 1000L);
|
||||||
|
}
|
||||||
|
} else if (!vaultRecoveryRequired && isAppLockEnabled() && pgpAuthInProgress) {
|
||||||
|
pgpAuthPaused = true;
|
||||||
|
pgpAuthPauseAt = SystemClock.elapsedRealtime();
|
||||||
|
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
}
|
||||||
super.onPause();
|
super.onPause();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,8 +140,18 @@ public class MainActivity extends BridgeActivity {
|
|||||||
else updateAppLockMessage("Unlock with your Android screen lock to view mail.");
|
else updateAppLockMessage("Unlock with your Android screen lock to view mail.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDestroy() {
|
||||||
|
appLockHandler.removeCallbacks(delayedAppLock);
|
||||||
|
appLockHandler.removeCallbacks(lockAfterPgpAuth);
|
||||||
|
super.onDestroy();
|
||||||
|
}
|
||||||
|
|
||||||
public void onAppLockSettingChanged(boolean enabled) {
|
public void onAppLockSettingChanged(boolean enabled) {
|
||||||
runOnUiThread(() -> {
|
runOnUiThread(() -> {
|
||||||
|
appLockHandler.removeCallbacks(delayedAppLock);
|
||||||
|
appLockHandler.removeCallbacks(lockAfterPgpAuth);
|
||||||
|
pgpAuthPaused = false;
|
||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
awaitingUnlockResult = false;
|
awaitingUnlockResult = false;
|
||||||
unlockWebView(false);
|
unlockWebView(false);
|
||||||
@@ -91,6 +163,77 @@ public class MainActivity extends BridgeActivity {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private int appLockDelaySeconds() {
|
||||||
|
try {
|
||||||
|
int delay = AndroidAccountVault.INSTANCE.appLockDelaySeconds();
|
||||||
|
AndroidAppLockPolicy.INSTANCE.requireValidDelay(delay);
|
||||||
|
return delay;
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void authenticatePgpCipher(Cipher cipher, BiometricPrompt.AuthenticationCallback callback) {
|
||||||
|
int authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG;
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
authenticators |= BiometricManager.Authenticators.DEVICE_CREDENTIAL;
|
||||||
|
}
|
||||||
|
BiometricPrompt.PromptInfo.Builder prompt = new BiometricPrompt.PromptInfo.Builder()
|
||||||
|
.setTitle("Unlock OpenPGP key")
|
||||||
|
.setSubtitle("Confirm to release this key's passphrase")
|
||||||
|
.setAllowedAuthenticators(authenticators)
|
||||||
|
.setConfirmationRequired(true);
|
||||||
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
|
||||||
|
prompt.setNegativeButtonText("Cancel");
|
||||||
|
}
|
||||||
|
BiometricPrompt biometricPrompt = new BiometricPrompt(
|
||||||
|
this,
|
||||||
|
ContextCompat.getMainExecutor(this),
|
||||||
|
new BiometricPrompt.AuthenticationCallback() {
|
||||||
|
@Override
|
||||||
|
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
|
||||||
|
finishPgpAuthentication();
|
||||||
|
callback.onAuthenticationSucceeded(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onAuthenticationFailed() {
|
||||||
|
callback.onAuthenticationFailed();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onAuthenticationError(int errorCode, CharSequence errString) {
|
||||||
|
finishPgpAuthentication();
|
||||||
|
callback.onAuthenticationError(errorCode, errString);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
pgpAuthInProgress = true;
|
||||||
|
try {
|
||||||
|
biometricPrompt.authenticate(
|
||||||
|
prompt.build(),
|
||||||
|
new BiometricPrompt.CryptoObject(cipher)
|
||||||
|
);
|
||||||
|
} catch (RuntimeException error) {
|
||||||
|
pgpAuthInProgress = false;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void finishPgpAuthentication() {
|
||||||
|
pgpAuthInProgress = false;
|
||||||
|
if (!pgpAuthPaused) return;
|
||||||
|
long elapsed = SystemClock.elapsedRealtime() - pgpAuthPauseAt;
|
||||||
|
long remaining = Math.max(1000L, appLockDelaySeconds() * 1000L - elapsed);
|
||||||
|
appLockHandler.postDelayed(lockAfterPgpAuth, remaining);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void clearLocalWebData() {
|
||||||
|
if (getBridge() == null || getBridge().getWebView() == null) return;
|
||||||
|
getBridge().getWebView().clearCache(true);
|
||||||
|
WebStorage.getInstance().deleteAllData();
|
||||||
|
}
|
||||||
|
|
||||||
private boolean isAppLockEnabled() {
|
private boolean isAppLockEnabled() {
|
||||||
try {
|
try {
|
||||||
return AndroidAccountVault.INSTANCE.appLockEnabled();
|
return AndroidAccountVault.INSTANCE.appLockEnabled();
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<inset xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:drawable="@drawable/ep_splash_icon"
|
||||||
|
android:inset="22dp" />
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
android:width="108dp"
|
||||||
|
android:height="108dp"
|
||||||
|
android:viewportWidth="64"
|
||||||
|
android:viewportHeight="64">
|
||||||
|
<path
|
||||||
|
android:fillColor="@android:color/transparent"
|
||||||
|
android:strokeColor="#eee9de"
|
||||||
|
android:strokeWidth="3"
|
||||||
|
android:pathData="M32,5a27,27 0,1 0,0 54a27,27 0,1 0,0 -54" />
|
||||||
|
<path
|
||||||
|
android:strokeColor="#eee9de"
|
||||||
|
android:strokeWidth="4"
|
||||||
|
android:pathData="M32,4v56" />
|
||||||
|
<group android:rotation="22" android:pivotX="32" android:pivotY="18">
|
||||||
|
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
|
||||||
|
android:strokeWidth="3" android:pathData="M20,18a12,5 0,1 0,24 0a12,5 0,1 0,-24 0" />
|
||||||
|
</group>
|
||||||
|
<group android:rotation="-22" android:pivotX="32" android:pivotY="46">
|
||||||
|
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
|
||||||
|
android:strokeWidth="3" android:pathData="M20,46a12,5 0,1 0,24 0a12,5 0,1 0,-24 0" />
|
||||||
|
</group>
|
||||||
|
<path android:fillColor="@android:color/transparent" android:strokeColor="#eee9de"
|
||||||
|
android:strokeAlpha="0.75" android:strokeWidth="2"
|
||||||
|
android:pathData="M24,32a8,8 0,1 0,16 0a8,8 0,1 0,-16 0" />
|
||||||
|
</vector>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<background android:drawable="@color/ic_launcher_background"/>
|
<background android:drawable="@color/ic_launcher_background"/>
|
||||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
<foreground android:drawable="@drawable/ep_launcher_foreground"/>
|
||||||
</adaptive-icon>
|
</adaptive-icon>
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
<background android:drawable="@color/ic_launcher_background"/>
|
<background android:drawable="@color/ic_launcher_background"/>
|
||||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
<foreground android:drawable="@drawable/ep_launcher_foreground"/>
|
||||||
</adaptive-icon>
|
</adaptive-icon>
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<item android:drawable="@color/ic_launcher_background" />
|
||||||
|
<item
|
||||||
|
android:drawable="@drawable/ep_splash_icon"
|
||||||
|
android:left="5dp"
|
||||||
|
android:top="5dp"
|
||||||
|
android:right="5dp"
|
||||||
|
android:bottom="5dp" />
|
||||||
|
</layer-list>
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
<item>
|
||||||
|
<shape android:shape="oval">
|
||||||
|
<solid android:color="@color/ic_launcher_background" />
|
||||||
|
</shape>
|
||||||
|
</item>
|
||||||
|
<item
|
||||||
|
android:drawable="@drawable/ep_splash_icon"
|
||||||
|
android:left="5dp"
|
||||||
|
android:top="5dp"
|
||||||
|
android:right="5dp"
|
||||||
|
android:bottom="5dp" />
|
||||||
|
</layer-list>
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8"?>
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
<resources>
|
<resources>
|
||||||
<color name="ic_launcher_background">#FFFFFF</color>
|
<color name="ic_launcher_background">#0a0c0b</color>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -17,6 +17,8 @@
|
|||||||
|
|
||||||
|
|
||||||
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">
|
||||||
<item name="android:background">@drawable/splash</item>
|
<item name="windowSplashScreenBackground">#0a0c0b</item>
|
||||||
|
<item name="windowSplashScreenAnimatedIcon">@drawable/ep_splash_icon</item>
|
||||||
|
<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>
|
||||||
</style>
|
</style>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidAppLockPolicyTest {
|
||||||
|
@Test
|
||||||
|
fun acceptsOnlySupportedAppLockDelays() {
|
||||||
|
AndroidAppLockPolicy.allowedDelaySeconds.forEach(AndroidAppLockPolicy::requireValidDelay)
|
||||||
|
assertThrows(IllegalArgumentException::class.java) {
|
||||||
|
AndroidAppLockPolicy.requireValidDelay(45)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidDownloadPolicyTest {
|
||||||
|
@Test
|
||||||
|
fun onlySelectsDownloadsCreatedByThisApplication() {
|
||||||
|
assertTrue(AndroidDownloadPolicy.isAppOwnedDownload("studio.daybreak.mail", "Download/", "studio.daybreak.mail"))
|
||||||
|
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload("other.app", "Download/", "studio.daybreak.mail"))
|
||||||
|
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload(null, "Download/", "studio.daybreak.mail"))
|
||||||
|
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload("studio.daybreak.mail", "Documents/", "studio.daybreak.mail"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -78,6 +78,15 @@ class AndroidPgpPolicyTest {
|
|||||||
assertFalse(warning.contains("Fingerprint:"))
|
assertFalse(warning.contains("Fingerprint:"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rawMimeRequiresNativeConfirmationBecauseEncryptionCannotBeVerified() {
|
||||||
|
val warning = AndroidPgpPolicy.unverifiedRawMimeWarning()
|
||||||
|
|
||||||
|
assertTrue(warning.contains("cannot verify"))
|
||||||
|
assertTrue(warning.contains("deceptive OpenPGP wrapper"))
|
||||||
|
assertTrue(warning.contains("Signing alone does not encrypt"))
|
||||||
|
}
|
||||||
|
|
||||||
private fun contact(fingerprint: String, email: String, trust: String) =
|
private fun contact(fingerprint: String, email: String, trust: String) =
|
||||||
AndroidPgpPolicy.ContactKey(fingerprint, listOf(email), trust)
|
AndroidPgpPolicy.ContactKey(fingerprint, listOf(email), trust)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class BoundedInputReaderTest {
|
||||||
|
@Test
|
||||||
|
fun readsOnlyUpToTheRequestedLimit() {
|
||||||
|
val input = ByteArrayInputStream(byteArrayOf(1, 2, 3, 4, 5))
|
||||||
|
assertArrayEquals(byteArrayOf(1, 2, 3), BoundedInputReader.read(input, 3))
|
||||||
|
assertEquals(2, input.available())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun readsShortStreamsToEnd() {
|
||||||
|
assertArrayEquals(
|
||||||
|
byteArrayOf(1, 2),
|
||||||
|
BoundedInputReader.read(ByteArrayInputStream(byteArrayOf(1, 2)), 5)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,7 @@ buildscript {
|
|||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
dependencies {
|
dependencies {
|
||||||
classpath 'com.android.tools.build:gradle:8.13.0'
|
classpath 'com.android.tools.build:gradle:9.4.0'
|
||||||
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
|
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
|
||||||
classpath 'com.google.gms:google-services:4.4.4'
|
classpath 'com.google.gms:google-services:4.4.4'
|
||||||
|
|
||||||
@@ -19,6 +19,12 @@ buildscript {
|
|||||||
apply from: "variables.gradle"
|
apply from: "variables.gradle"
|
||||||
|
|
||||||
allprojects {
|
allprojects {
|
||||||
|
// Capacitor-generated modules declare their own AGP version.
|
||||||
|
buildscript {
|
||||||
|
configurations.classpath {
|
||||||
|
resolutionStrategy.force 'com.android.tools.build:gradle:9.4.0'
|
||||||
|
}
|
||||||
|
}
|
||||||
repositories {
|
repositories {
|
||||||
google()
|
google()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
|||||||
@@ -20,3 +20,6 @@ org.gradle.jvmargs=-Xmx1536m
|
|||||||
# Android operating system, and which are packaged with your app's APK
|
# Android operating system, and which are packaged with your app's APK
|
||||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
|
# Capacitor's generated modules and the current Kotlin plugin still use the legacy AGP APIs.
|
||||||
|
android.builtInKotlin=false
|
||||||
|
android.newDsl=false
|
||||||
|
|||||||
+2
-1
@@ -1,6 +1,7 @@
|
|||||||
|
#Mon Nov 09 22:05:03 EET 2026
|
||||||
distributionBase=GRADLE_USER_HOME
|
distributionBase=GRADLE_USER_HOME
|
||||||
distributionPath=wrapper/dists
|
distributionPath=wrapper/dists
|
||||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-all.zip
|
distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip
|
||||||
networkTimeout=10000
|
networkTimeout=10000
|
||||||
validateDistributionUrl=true
|
validateDistributionUrl=true
|
||||||
zipStoreBase=GRADLE_USER_HOME
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
|||||||
@@ -4,11 +4,26 @@ 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;
|
||||||
|
let readerListPosition = null;
|
||||||
|
function rememberReaderListPosition() {
|
||||||
|
if (window.daybreakMail?.platform !== 'android' || document.body.classList.contains('reader-open')) return;
|
||||||
|
const list = $('#message-list');
|
||||||
|
readerListPosition = { folder: state.activeFolder, scrollTop: list.scrollTop };
|
||||||
|
}
|
||||||
|
function returnToMessageList() {
|
||||||
|
state.activeMessage = null;
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
$('#reader-pane').innerHTML = emptyReader();
|
||||||
|
renderList();
|
||||||
|
if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop;
|
||||||
|
readerListPosition = null;
|
||||||
|
}
|
||||||
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}}
|
function 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){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
|
if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
|
||||||
|
rememberReaderListPosition();
|
||||||
document.body.classList.add('reader-open');
|
document.body.classList.add('reader-open');
|
||||||
m.unread=false;
|
m.unread=false;
|
||||||
renderList();
|
renderList();
|
||||||
@@ -18,7 +33,7 @@ function openMessage(id){
|
|||||||
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"><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-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()};
|
$('#reader-back').onclick=returnToMessageList;
|
||||||
$('#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'));
|
||||||
@@ -51,6 +66,9 @@ window.epMailShell = Object.freeze({
|
|||||||
get renderList() { return renderList; },
|
get renderList() { return renderList; },
|
||||||
get openMessage() { return openMessage; },
|
get openMessage() { return openMessage; },
|
||||||
get showCompose() { return showCompose; },
|
get showCompose() { return showCompose; },
|
||||||
|
getReaderListPosition() {
|
||||||
|
return readerListPosition?.folder === state.activeFolder ? readerListPosition.scrollTop : 0;
|
||||||
|
},
|
||||||
emptyReader,
|
emptyReader,
|
||||||
wrapRenderList(decorator) { renderList = decorator(renderList); },
|
wrapRenderList(decorator) { renderList = decorator(renderList); },
|
||||||
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
|
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
|
||||||
|
|||||||
+211
-18
@@ -8,12 +8,20 @@ const toastMailUi = appShell.toast;
|
|||||||
const mailFeatureState = {
|
const mailFeatureState = {
|
||||||
connectedAccount: null,
|
connectedAccount: null,
|
||||||
pageOffset: 0,
|
pageOffset: 0,
|
||||||
|
nextOffset: 0,
|
||||||
total: 0,
|
total: 0,
|
||||||
|
autoLoadBlocked: false,
|
||||||
syncPromise: null,
|
syncPromise: null,
|
||||||
syncQueued: false,
|
syncQueued: false,
|
||||||
|
syncMailboxKey: null,
|
||||||
|
displayedMailboxKey: null,
|
||||||
refreshPending: false,
|
refreshPending: false,
|
||||||
|
browseRefreshPending: false,
|
||||||
|
browseRefreshFromStart: false,
|
||||||
folderBeforeSearch: null,
|
folderBeforeSearch: null,
|
||||||
customFolders: [],
|
customFolders: [],
|
||||||
|
folderLoad: null,
|
||||||
|
foldersAccountId: null,
|
||||||
selectedDraftIds: new Set()
|
selectedDraftIds: new Set()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -142,10 +150,23 @@ function renderCustomFolders() {
|
|||||||
|
|
||||||
async function loadCustomFolders() {
|
async function loadCustomFolders() {
|
||||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
|
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
|
||||||
|
const accountId = mailFeatureState.connectedAccount.id;
|
||||||
|
if (mailFeatureState.folderLoad?.accountId === accountId) return mailFeatureState.folderLoad.promise;
|
||||||
|
const request = { accountId };
|
||||||
|
mailFeatureState.folderLoad = request;
|
||||||
|
request.promise = (async () => {
|
||||||
try {
|
try {
|
||||||
mailFeatureState.customFolders = (await window.daybreakMail.listFolders()).folders || [];
|
const result = await window.daybreakMail.listFolders();
|
||||||
|
if (mailFeatureState.folderLoad !== request || mailFeatureState.connectedAccount?.id !== accountId) return;
|
||||||
|
mailFeatureState.customFolders = result.folders || [];
|
||||||
renderCustomFolders();
|
renderCustomFolders();
|
||||||
} catch {}
|
} catch (error) {
|
||||||
|
if (mailFeatureState.folderLoad === request) console.error('Could not load mail folders:', error);
|
||||||
|
} finally {
|
||||||
|
if (mailFeatureState.folderLoad === request) mailFeatureState.folderLoad = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return request.promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
|
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
|
||||||
@@ -183,6 +204,7 @@ async function createMailFolder() {
|
|||||||
if (!name) return;
|
if (!name) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.createFolder(name);
|
const result = await window.daybreakMail.createFolder(name);
|
||||||
|
mailFeatureState.folderLoad = null;
|
||||||
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
|
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
|
||||||
renderCustomFolders();
|
renderCustomFolders();
|
||||||
toastMailUi(`Folder “${result.folder?.name || name}” created`);
|
toastMailUi(`Folder “${result.folder?.name || name}” created`);
|
||||||
@@ -192,6 +214,13 @@ async function createMailFolder() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function updateAccountCard(account) {
|
function updateAccountCard(account) {
|
||||||
|
const accountId = mailFeatureState.connectedAccount?.id || null;
|
||||||
|
if (mailFeatureState.foldersAccountId !== accountId) {
|
||||||
|
mailFeatureState.foldersAccountId = accountId;
|
||||||
|
mailFeatureState.folderLoad = null;
|
||||||
|
mailFeatureState.customFolders = [];
|
||||||
|
renderCustomFolders();
|
||||||
|
}
|
||||||
const card = selectMailUi('#account-settings');
|
const card = selectMailUi('#account-settings');
|
||||||
if (!card) return;
|
if (!card) return;
|
||||||
const email = account.email || '';
|
const email = account.email || '';
|
||||||
@@ -648,29 +677,103 @@ function setupDraftComposer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function syncMailbox(showToast, options = {}) {
|
async function syncMailbox(showToast, options = {}) {
|
||||||
|
const isAndroid = window.daybreakMail?.platform === 'android';
|
||||||
|
const mailboxKey = JSON.stringify([mailFeatureState.connectedAccount?.id, rendererState.activeFolder]);
|
||||||
if (mailFeatureState.syncPromise) {
|
if (mailFeatureState.syncPromise) {
|
||||||
|
if (!isAndroid || mailFeatureState.syncMailboxKey === mailboxKey) {
|
||||||
mailFeatureState.syncQueued = true;
|
mailFeatureState.syncQueued = true;
|
||||||
return mailFeatureState.syncPromise;
|
return mailFeatureState.syncPromise;
|
||||||
}
|
}
|
||||||
|
mailFeatureState.syncQueued = false;
|
||||||
|
}
|
||||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
||||||
openMailAccount();
|
openMailAccount();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const refresh = selectMailUi('#refresh');
|
const refresh = selectMailUi('#refresh');
|
||||||
if (refresh) refresh.disabled = true;
|
if (refresh) refresh.disabled = true;
|
||||||
|
const loadMoreButton = selectMailUi('#load-more');
|
||||||
|
if (loadMoreButton) loadMoreButton.disabled = true;
|
||||||
|
if (!options.append) {
|
||||||
|
mailFeatureState.browseRefreshPending = false;
|
||||||
|
mailFeatureState.browseRefreshFromStart = false;
|
||||||
|
} else {
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Loading more messages…';
|
||||||
|
}
|
||||||
|
const request = {};
|
||||||
|
mailFeatureState.syncRequest = request;
|
||||||
|
mailFeatureState.syncMailboxKey = mailboxKey;
|
||||||
|
let syncSucceeded = false;
|
||||||
const sync = (async () => {
|
const sync = (async () => {
|
||||||
|
let showingCachedMessages = false;
|
||||||
try {
|
try {
|
||||||
|
if (isAndroid && mailFeatureState.displayedMailboxKey !== mailboxKey) {
|
||||||
|
mailFeatureState.displayedMailboxKey = mailboxKey;
|
||||||
|
mailFeatureState.nextOffset = 0;
|
||||||
|
mailFeatureState.total = 0;
|
||||||
|
mailFeatureState.autoLoadBlocked = false;
|
||||||
|
rendererState.messages.splice(0, rendererState.messages.length);
|
||||||
|
rendererState.activeMessage = null;
|
||||||
|
rendererState.selectedIds.clear();
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
||||||
|
appShell.renderList();
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Loading folder…';
|
||||||
|
}
|
||||||
if (rendererState.activeFolder === 'Drafts') {
|
if (rendererState.activeFolder === 'Drafts') {
|
||||||
const result = await window.daybreakMail.listDrafts();
|
const result = await window.daybreakMail.listDrafts();
|
||||||
|
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||||
renderDrafts(result.drafts || []);
|
renderDrafts(result.drafts || []);
|
||||||
|
mailFeatureState.autoLoadBlocked = true;
|
||||||
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
|
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const folder = rendererState.activeFolder;
|
||||||
|
const accountId = mailFeatureState.connectedAccount.id;
|
||||||
|
const offset = options.offset ?? (options.append ? mailFeatureState.nextOffset : mailFeatureState.pageOffset);
|
||||||
|
const filters = mailSearchFilters();
|
||||||
|
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId &&
|
||||||
|
(!isAndroid || mailFeatureState.syncRequest === request);
|
||||||
|
if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) {
|
||||||
|
try {
|
||||||
|
const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters);
|
||||||
|
if (cached && isCurrentMailbox()) {
|
||||||
|
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
|
||||||
|
rendererState.activeMessage = null;
|
||||||
|
mailFeatureState.pageOffset = offset;
|
||||||
|
mailFeatureState.nextOffset = offset + cached.messages.length;
|
||||||
|
mailFeatureState.total = cached.total;
|
||||||
|
mailFeatureState.autoLoadBlocked = true;
|
||||||
|
const pagination = selectMailUi('#pagination');
|
||||||
|
if (pagination) pagination.textContent = cached.total ? `${cached.start}–${cached.end} of ${cached.total} saved messages` : '0 saved messages';
|
||||||
|
const loadMore = selectMailUi('#load-more');
|
||||||
|
if (loadMore) loadMore.classList.toggle('hidden', cached.messages.length >= cached.total);
|
||||||
|
appShell.renderList();
|
||||||
|
showingCachedMessages = true;
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Showing saved messages — syncing';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||||
|
console.error('Could not load cached messages:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isCurrentMailbox()) return;
|
||||||
|
const result = await window.daybreakMail.syncFolder(folder, offset, filters);
|
||||||
|
if (!isCurrentMailbox()) return;
|
||||||
const previouslyActiveMessage = rendererState.activeMessage;
|
const previouslyActiveMessage = rendererState.activeMessage;
|
||||||
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
|
if (options.append) {
|
||||||
const result = await window.daybreakMail.syncFolder(rendererState.activeFolder, offset, mailSearchFilters());
|
const existing = new Set(rendererState.messages.map(message => JSON.stringify([message.sourceFolder || folder, message.uid || message.id])));
|
||||||
if (options.append) rendererState.messages.push(...result.messages);
|
for (const message of result.messages) {
|
||||||
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
const key = JSON.stringify([message.sourceFolder || folder, message.uid || message.id]);
|
||||||
|
if (!existing.has(key)) {
|
||||||
|
rendererState.messages.push(message);
|
||||||
|
existing.add(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
||||||
rendererState.messages.forEach(message => {
|
rendererState.messages.forEach(message => {
|
||||||
try {
|
try {
|
||||||
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
||||||
@@ -679,33 +782,61 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
});
|
});
|
||||||
if (!options.append) mailFeatureState.pageOffset = offset;
|
if (!options.append) mailFeatureState.pageOffset = offset;
|
||||||
mailFeatureState.total = result.total;
|
mailFeatureState.total = result.total;
|
||||||
|
const hasSearch = Boolean(filters.query || filters.sender || filters.subject || filters.after || filters.before || filters.hasAttachments);
|
||||||
|
const isSequencePage = !result.offline && folder !== 'Snoozed' && !hasSearch;
|
||||||
|
const consumed = isSequencePage && result.start > 0 && result.end >= result.start
|
||||||
|
? result.end - result.start + 1
|
||||||
|
: result.messages.length;
|
||||||
|
mailFeatureState.nextOffset = offset + consumed;
|
||||||
|
mailFeatureState.autoLoadBlocked = consumed === 0 || (options.append && result.messages.length === 0);
|
||||||
|
syncSucceeded = true;
|
||||||
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
|
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
|
||||||
? previouslyActiveMessage
|
? previouslyActiveMessage
|
||||||
: rendererState.messages[0]?.id;
|
: window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
|
||||||
rendererState.selectedIds.clear();
|
rendererState.selectedIds.clear();
|
||||||
const unread = rendererState.messages.filter(message => message.unread).length;
|
const unread = rendererState.messages.filter(message => message.unread).length;
|
||||||
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
|
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
|
||||||
if (inboxCount) inboxCount.textContent = String(unread);
|
if (inboxCount) inboxCount.textContent = String(unread);
|
||||||
const pagination = selectMailUi('#pagination');
|
const pagination = selectMailUi('#pagination');
|
||||||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
if (pagination) pagination.textContent = result.total ? `${options.append ? mailFeatureState.pageOffset + 1 : result.start}–${options.append ? Math.min(mailFeatureState.nextOffset, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||||
const loadMore = selectMailUi('#load-more');
|
const loadMore = selectMailUi('#load-more');
|
||||||
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total);
|
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.nextOffset >= result.total || consumed === 0);
|
||||||
rendererState.query = '';
|
rendererState.query = '';
|
||||||
|
const messageList = selectMailUi('#message-list');
|
||||||
|
const scrollTop = options.append ? messageList.scrollTop : 0;
|
||||||
appShell.renderList();
|
appShell.renderList();
|
||||||
|
if (options.append) messageList.scrollTop = scrollTop;
|
||||||
if (rendererState.activeMessage) {
|
if (rendererState.activeMessage) {
|
||||||
appShell.openMessage(rendererState.activeMessage);
|
appShell.openMessage(rendererState.activeMessage);
|
||||||
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
|
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
|
||||||
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
if (current?.uid && window.daybreakMail.platform !== 'android') window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
||||||
}
|
}
|
||||||
else selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
|
||||||
updateAccountCard(mailFeatureState.connectedAccount);
|
updateAccountCard(mailFeatureState.connectedAccount);
|
||||||
const status = selectMailUi('#mail-status');
|
const status = selectMailUi('#mail-status');
|
||||||
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
|
if (status) status.textContent = mailFeatureState.browseRefreshPending
|
||||||
|
? 'Updates paused while browsing — return to the top or refresh'
|
||||||
|
: result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
|
||||||
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
|
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||||
|
if (options.append) mailFeatureState.autoLoadBlocked = true;
|
||||||
|
if (showingCachedMessages) {
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Could not sync — showing saved messages';
|
||||||
|
} else if (options.append) {
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Could not load more messages — use Load more to retry';
|
||||||
|
}
|
||||||
toastMailUi(error.message || 'Could not sync the inbox');
|
toastMailUi(error.message || 'Could not sync the inbox');
|
||||||
} finally {
|
} finally {
|
||||||
|
if (!isAndroid || mailFeatureState.syncRequest === request) {
|
||||||
if (refresh) refresh.disabled = false;
|
if (refresh) refresh.disabled = false;
|
||||||
|
if (loadMoreButton) loadMoreButton.disabled = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
})();
|
})();
|
||||||
@@ -713,14 +844,68 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
try {
|
try {
|
||||||
await sync;
|
await sync;
|
||||||
} finally {
|
} finally {
|
||||||
|
if (mailFeatureState.syncPromise !== sync) return;
|
||||||
mailFeatureState.syncPromise = null;
|
mailFeatureState.syncPromise = null;
|
||||||
|
mailFeatureState.syncMailboxKey = null;
|
||||||
if (mailFeatureState.syncQueued) {
|
if (mailFeatureState.syncQueued) {
|
||||||
mailFeatureState.syncQueued = false;
|
mailFeatureState.syncQueued = false;
|
||||||
void syncMailbox(false);
|
void syncMailbox(false);
|
||||||
|
} else if (runDeferredMailboxRefresh()) {
|
||||||
|
return;
|
||||||
|
} else if (syncSucceeded) {
|
||||||
|
maybeLoadMoreMessages();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function shouldDeferMailboxRefresh() {
|
||||||
|
if (window.daybreakMail?.platform !== 'android') return false;
|
||||||
|
const list = selectMailUi('#message-list');
|
||||||
|
return Boolean(list && (list.scrollTop > 120 ||
|
||||||
|
(document.body.classList.contains('reader-open') &&
|
||||||
|
(appShell.getReaderListPosition() > 120 ||
|
||||||
|
mailFeatureState.nextOffset > mailFeatureState.pageOffset + 20))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestBackgroundMailboxRefresh(options = {}) {
|
||||||
|
if (shouldDeferMailboxRefresh()) {
|
||||||
|
mailFeatureState.browseRefreshPending = true;
|
||||||
|
if (options.offset === 0) mailFeatureState.browseRefreshFromStart = true;
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status && !mailFeatureState.syncPromise) {
|
||||||
|
status.textContent = 'Updates paused while browsing — return to the top or refresh';
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void syncMailbox(false, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
function runDeferredMailboxRefresh() {
|
||||||
|
if (!mailFeatureState.browseRefreshPending || mailFeatureState.syncPromise ||
|
||||||
|
document.visibilityState !== 'visible' || rendererState.activeView !== 'mail' ||
|
||||||
|
shouldDeferMailboxRefresh()) return false;
|
||||||
|
const options = mailFeatureState.browseRefreshFromStart ? { offset: 0 } : {};
|
||||||
|
mailFeatureState.browseRefreshPending = false;
|
||||||
|
mailFeatureState.browseRefreshFromStart = false;
|
||||||
|
void syncMailbox(false, options);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMessageListScroll() {
|
||||||
|
if (!runDeferredMailboxRefresh()) maybeLoadMoreMessages();
|
||||||
|
}
|
||||||
|
|
||||||
|
function maybeLoadMoreMessages() {
|
||||||
|
const list = selectMailUi('#message-list');
|
||||||
|
if (!list || !mailFeatureState.connectedAccount || mailFeatureState.syncPromise ||
|
||||||
|
mailFeatureState.autoLoadBlocked || rendererState.activeFolder === 'Drafts' ||
|
||||||
|
mailFeatureState.nextOffset >= mailFeatureState.total || !list.clientHeight ||
|
||||||
|
document.body.classList.contains('reader-open') ||
|
||||||
|
rendererState.activeView !== 'mail') return;
|
||||||
|
if (list.scrollHeight - list.scrollTop - list.clientHeight > 120) return;
|
||||||
|
void syncMailbox(false, { append: true });
|
||||||
|
}
|
||||||
|
|
||||||
if (window.daybreakMail) {
|
if (window.daybreakMail) {
|
||||||
setupDraftComposer();
|
setupDraftComposer();
|
||||||
let searchTimer;
|
let searchTimer;
|
||||||
@@ -777,7 +962,7 @@ if (window.daybreakMail) {
|
|||||||
}
|
}
|
||||||
if (update.newCount || (update.foldersChanged || []).length) {
|
if (update.newCount || (update.foldersChanged || []).length) {
|
||||||
if (document.visibilityState === 'visible') {
|
if (document.visibilityState === 'visible') {
|
||||||
syncMailbox(false, update.newCount ? { offset: 0 } : {});
|
requestBackgroundMailboxRefresh(update.newCount ? { offset: 0 } : {});
|
||||||
}
|
}
|
||||||
else mailFeatureState.refreshPending = true;
|
else mailFeatureState.refreshPending = true;
|
||||||
}
|
}
|
||||||
@@ -785,18 +970,20 @@ if (window.daybreakMail) {
|
|||||||
document.addEventListener('visibilitychange', () => {
|
document.addEventListener('visibilitychange', () => {
|
||||||
if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
|
if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
|
||||||
mailFeatureState.refreshPending = false;
|
mailFeatureState.refreshPending = false;
|
||||||
syncMailbox(false, { offset: 0 });
|
requestBackgroundMailboxRefresh({ offset: 0 });
|
||||||
|
} else if (document.visibilityState === 'visible') {
|
||||||
|
runDeferredMailboxRefresh();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
window.addEventListener('focus', () => {
|
window.addEventListener('focus', () => {
|
||||||
if (mailFeatureState.connectedAccount) syncMailbox(false);
|
if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh();
|
||||||
});
|
});
|
||||||
window.addEventListener('online', () => {
|
window.addEventListener('online', () => {
|
||||||
if (mailFeatureState.connectedAccount) syncMailbox(false, { offset: 0 });
|
if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh({ offset: 0 });
|
||||||
});
|
});
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
|
if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
|
||||||
syncMailbox(false);
|
requestBackgroundMailboxRefresh();
|
||||||
}
|
}
|
||||||
}, 60 * 1000);
|
}, 60 * 1000);
|
||||||
selectMailUi('#account-settings').addEventListener('click', openMailAccount);
|
selectMailUi('#account-settings').addEventListener('click', openMailAccount);
|
||||||
@@ -825,7 +1012,13 @@ if (window.daybreakMail) {
|
|||||||
mailFeatureState.pageOffset += 20;
|
mailFeatureState.pageOffset += 20;
|
||||||
syncMailbox(false, { offset: mailFeatureState.pageOffset });
|
syncMailbox(false, { offset: mailFeatureState.pageOffset });
|
||||||
};
|
};
|
||||||
selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true });
|
selectMailUi('#load-more').onclick = () => {
|
||||||
|
if (!mailFeatureState.syncPromise) void syncMailbox(false, { append: true });
|
||||||
|
};
|
||||||
|
selectMailUi('#message-list').addEventListener('scroll', handleMessageListScroll, { passive: true });
|
||||||
|
document.addEventListener('click', event => {
|
||||||
|
if (event.target.closest('#reader-back')) runDeferredMailboxRefresh();
|
||||||
|
});
|
||||||
document.addEventListener('click', async event => {
|
document.addEventListener('click', async event => {
|
||||||
const sendButton = event.target.closest('#send');
|
const sendButton = event.target.closest('#send');
|
||||||
if (!sendButton || !mailFeatureState.connectedAccount) return;
|
if (!sendButton || !mailFeatureState.connectedAccount) return;
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.12",
|
"version": "0.5.20",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.12",
|
"version": "0.5.20",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "^8.5.2",
|
"@capacitor/android": "^8.5.2",
|
||||||
"@capacitor/core": "^8.5.2",
|
"@capacitor/core": "^8.5.2",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.12",
|
"version": "0.5.20",
|
||||||
"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",
|
||||||
|
|||||||
+9
-4
@@ -110,9 +110,14 @@ async function pgpUnlockMessage(message, interactive) {
|
|||||||
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
|
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
|
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') {
|
||||||
if (!interactive) { pgpRenderReaderState(message); return; }
|
if (!interactive) { pgpRenderReaderState(message); return; }
|
||||||
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
const prompt = result.code === 'BAD_PASSPHRASE'
|
||||||
|
? 'That passphrase was incorrect. Try again.'
|
||||||
|
: result.code === 'BIOMETRIC_INVALIDATED'
|
||||||
|
? `${result.message} Enter the passphrase to continue.`
|
||||||
|
: `Enter the passphrase for ${result.email || 'your key'}.`;
|
||||||
|
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
|
||||||
if (passphrase === null) return;
|
if (passphrase === null) return;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -179,7 +184,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
|||||||
if (!selectPgpMailUi('#pgp-hint')) return;
|
if (!selectPgpMailUi('#pgp-hint')) return;
|
||||||
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
||||||
else {
|
else {
|
||||||
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
hint.textContent = status.recipients.some(item => item.trust !== 'verified') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
||||||
if (!touched && !encrypt.checked) encrypt.checked = true;
|
if (!touched && !encrypt.checked) encrypt.checked = true;
|
||||||
}
|
}
|
||||||
} catch { hint.textContent = ''; }
|
} catch { hint.textContent = ''; }
|
||||||
@@ -216,7 +221,7 @@ async function prepareSend(to, cc) {
|
|||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
|
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
|
||||||
if (!status.signer.unlocked) {
|
if (!status.signer.unlocked && !status.signer.biometricUnlockEnabled) {
|
||||||
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
||||||
if (passphrase === null) return false;
|
if (passphrase === null) return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ function openEncryptionKeys() {
|
|||||||
<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">
|
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>
|
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Optional biometric unlock stores the passphrase in a Keystore key requiring user authentication. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
||||||
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
||||||
<h3 class="pgp-heading">Change a key passphrase</h3>
|
<h3 class="pgp-heading">Change a key passphrase</h3>
|
||||||
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
||||||
@@ -138,6 +138,42 @@ function openEncryptionKeys() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
row.append(changePassphrase);
|
row.append(changePassphrase);
|
||||||
|
if (androidPgp) {
|
||||||
|
const biometric = document.createElement('button');
|
||||||
|
biometric.className = 'discard';
|
||||||
|
biometric.textContent = 'Checking biometric unlock…';
|
||||||
|
biometric.disabled = true;
|
||||||
|
row.append(biometric);
|
||||||
|
window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => {
|
||||||
|
if (!biometric.isConnected) return;
|
||||||
|
biometric.dataset.enabled = String(enabled);
|
||||||
|
biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…';
|
||||||
|
biometric.disabled = false;
|
||||||
|
}).catch(error => {
|
||||||
|
if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.');
|
||||||
|
});
|
||||||
|
biometric.onclick = async () => {
|
||||||
|
biometric.disabled = true;
|
||||||
|
try {
|
||||||
|
if (biometric.dataset.enabled === 'true') {
|
||||||
|
if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return;
|
||||||
|
await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint);
|
||||||
|
status('Biometric unlock disabled.');
|
||||||
|
} else {
|
||||||
|
const passphrase = needPassphrase();
|
||||||
|
if (!passphrase) return;
|
||||||
|
await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase });
|
||||||
|
passphraseField().value = '';
|
||||||
|
status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.');
|
||||||
|
}
|
||||||
|
await render();
|
||||||
|
} catch (error) {
|
||||||
|
status(error.message || 'Could not update biometric key unlock.');
|
||||||
|
} finally {
|
||||||
|
biometric.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||||
actions.push(['Delete', async () => {
|
actions.push(['Delete', async () => {
|
||||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||||
|
|||||||
+61
-4
@@ -10113,7 +10113,7 @@ ${parts.join("")}`;
|
|||||||
}
|
}
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
function createAndroidPgp({ EpMail: EpMail2, getAccount }) {
|
function createAndroidPgp({ EpMail: EpMail2, getAccount, confirm = globalThis.confirm }) {
|
||||||
let storePromise;
|
let storePromise;
|
||||||
const passphrases = /* @__PURE__ */ new Map();
|
const passphrases = /* @__PURE__ */ new Map();
|
||||||
let cacheMinutes = 10;
|
let cacheMinutes = 10;
|
||||||
@@ -10240,20 +10240,30 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
|
|||||||
async function unlock(fingerprint, passphrase) {
|
async function unlock(fingerprint, passphrase) {
|
||||||
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
|
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
|
||||||
if (!entry) throw new Error("That key was not found.");
|
if (!entry) throw new Error("That key was not found.");
|
||||||
|
const secret = passphrase || await biometricPassphrase(fingerprint);
|
||||||
|
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email || "your key"}.`), { code: "PASSPHRASE_REQUIRED" });
|
||||||
|
return unlockWithPassphrase(entry, secret);
|
||||||
|
}
|
||||||
|
async function unlockWithPassphrase(entry, passphrase) {
|
||||||
try {
|
try {
|
||||||
return await po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase });
|
return await po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase });
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error("The passphrase is incorrect.");
|
throw new Error("The passphrase is incorrect.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function biometricPassphrase(fingerprint) {
|
||||||
|
if (typeof EpMail2.getPgpBiometricPassphrase !== "function") return null;
|
||||||
|
const result = await EpMail2.getPgpBiometricPassphrase({ fingerprint });
|
||||||
|
return result?.enabled && typeof result.passphrase === "string" ? result.passphrase : null;
|
||||||
|
}
|
||||||
async function signerFor(account, passphrase) {
|
async function signerFor(account, passphrase) {
|
||||||
const data = await store();
|
const data = await store();
|
||||||
const entry = data.keys.find((item) => item.email.toLowerCase() === String(account.email).toLowerCase());
|
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" });
|
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);
|
const secret = passphrase || cached(entry.fingerprint) || await biometricPassphrase(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 });
|
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 {
|
try {
|
||||||
const key = await unlock(entry.fingerprint, secret);
|
const key = await unlockWithPassphrase(entry, secret);
|
||||||
cache(entry.fingerprint, secret);
|
cache(entry.fingerprint, secret);
|
||||||
return { key, entry };
|
return { key, entry };
|
||||||
} catch {
|
} catch {
|
||||||
@@ -10277,6 +10287,21 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
|
|||||||
if (pgp.encrypt && recipientKeys.missing.length) {
|
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 });
|
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(", ")}.`), { code: "NO_RECIPIENT_KEY", missing: recipientKeys.missing });
|
||||||
}
|
}
|
||||||
|
const unverifiedKeys = recipientKeys.keys.filter((item) => item.trust !== "verified");
|
||||||
|
if (pgp.encrypt && unverifiedKeys.length) {
|
||||||
|
const details = unverifiedKeys.map(
|
||||||
|
(item) => `${item.address}
|
||||||
|
${item.fingerprint.match(/.{1,4}/g).join(" ")} (${item.trust})`
|
||||||
|
).join("\n\n");
|
||||||
|
const warning = `These recipient keys have not been verified by fingerprint:
|
||||||
|
|
||||||
|
${details}
|
||||||
|
|
||||||
|
If a key is incorrect, its owner may be able to read this message. Compare each fingerprint with its owner through another channel before sending. Send encrypted mail to these unverified keys anyway?`;
|
||||||
|
if (typeof confirm !== "function" || !confirm(warning)) {
|
||||||
|
throw Object.assign(new Error("Sending to unverified recipient keys was cancelled."), { code: "UNVERIFIED_RECIPIENT_KEY" });
|
||||||
|
}
|
||||||
|
}
|
||||||
let inner = mimeInner(`${String(message.text || "").slice(0, 5e5)}${account.signature ? `
|
let inner = mimeInner(`${String(message.text || "").slice(0, 5e5)}${account.signature ? `
|
||||||
|
|
||||||
${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
|
${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
|
||||||
@@ -10364,6 +10389,7 @@ ${body}`);
|
|||||||
selected = candidates.find((entry) => cached(entry.fingerprint)) || selected;
|
selected = candidates.find((entry) => cached(entry.fingerprint)) || selected;
|
||||||
secret = cached(selected.fingerprint);
|
secret = cached(selected.fingerprint);
|
||||||
}
|
}
|
||||||
|
if (!secret) secret = await biometricPassphrase(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." };
|
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;
|
let privateKey;
|
||||||
try {
|
try {
|
||||||
@@ -10536,6 +10562,23 @@ ${body}`);
|
|||||||
clear(fingerprint);
|
clear(fingerprint);
|
||||||
return { removed: true };
|
return { removed: true };
|
||||||
},
|
},
|
||||||
|
async enableBiometricUnlock({ fingerprint, passphrase }) {
|
||||||
|
if (typeof EpMail2.setPgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
|
||||||
|
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
|
||||||
|
if (!entry) throw new Error("That key was not found.");
|
||||||
|
if (!passphrase) throw new Error("Enter the key passphrase first.");
|
||||||
|
await unlockWithPassphrase(entry, passphrase);
|
||||||
|
return EpMail2.setPgpBiometricUnlock({ fingerprint, passphrase });
|
||||||
|
},
|
||||||
|
async biometricUnlockEnabled(fingerprint) {
|
||||||
|
if (typeof EpMail2.pgpBiometricUnlockEnabled !== "function") return false;
|
||||||
|
return Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled);
|
||||||
|
},
|
||||||
|
async disableBiometricUnlock(fingerprint) {
|
||||||
|
if (typeof EpMail2.removePgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
|
||||||
|
clear(fingerprint);
|
||||||
|
return EpMail2.removePgpBiometricUnlock({ fingerprint });
|
||||||
|
},
|
||||||
async contacts() {
|
async contacts() {
|
||||||
return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt }));
|
return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt }));
|
||||||
},
|
},
|
||||||
@@ -10575,10 +10618,20 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
|
|||||||
const { keys, missing } = await resolveRecipients(addresses);
|
const { keys, missing } = await resolveRecipients(addresses);
|
||||||
const account = await getAccount();
|
const account = await getAccount();
|
||||||
const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null;
|
const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null;
|
||||||
|
let biometricUnlockEnabled = false;
|
||||||
|
if (entry && typeof EpMail2.pgpBiometricUnlockEnabled === "function") {
|
||||||
|
biometricUnlockEnabled = Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled);
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
recipients: keys.map((item) => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
|
recipients: keys.map((item) => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
|
||||||
missing,
|
missing,
|
||||||
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null
|
signer: entry ? {
|
||||||
|
fingerprint: entry.fingerprint,
|
||||||
|
email: entry.email,
|
||||||
|
name: entry.name,
|
||||||
|
unlocked: Boolean(cached(entry.fingerprint)),
|
||||||
|
biometricUnlockEnabled
|
||||||
|
} : null
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
decryptMessage,
|
decryptMessage,
|
||||||
@@ -10632,11 +10685,14 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
|
|||||||
var EpMail = registerPlugin("EpMail");
|
var EpMail = registerPlugin("EpMail");
|
||||||
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
|
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
|
||||||
const daybreakMail = {
|
const daybreakMail = {
|
||||||
|
platform: "android",
|
||||||
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
|
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
|
||||||
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
|
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
|
||||||
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
|
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
|
||||||
getAppLockSettings: () => EpMail.getAppLockSettings(),
|
getAppLockSettings: () => EpMail.getAppLockSettings(),
|
||||||
setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }),
|
setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }),
|
||||||
|
setAppLockDelay: (seconds) => EpMail.setAppLockDelay({ seconds }),
|
||||||
|
deleteAllLocalData: () => EpMail.deleteAllLocalData(),
|
||||||
getAccount: () => EpMail.getAccount(),
|
getAccount: () => EpMail.getAccount(),
|
||||||
listAccounts: () => EpMail.listAccounts(),
|
listAccounts: () => EpMail.listAccounts(),
|
||||||
selectAccount: (id) => EpMail.selectAccount({ id }),
|
selectAccount: (id) => EpMail.selectAccount({ id }),
|
||||||
@@ -10644,6 +10700,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
|
|||||||
connect: (details) => EpMail.connect(details),
|
connect: (details) => EpMail.connect(details),
|
||||||
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
||||||
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
||||||
|
getCachedFolder: (folder, offset, filters) => EpMail.getCachedFolder({ folder, offset, filters }).then((result) => result.cached),
|
||||||
listFolders: () => EpMail.listFolders(),
|
listFolders: () => EpMail.listFolders(),
|
||||||
createFolder: (name) => EpMail.createFolder({ name }),
|
createFolder: (name) => EpMail.createFolder({ name }),
|
||||||
listDrafts: () => EpMail.listDrafts(),
|
listDrafts: () => EpMail.listDrafts(),
|
||||||
|
|||||||
+8
-5
@@ -33,18 +33,21 @@ async function openPreferences() {
|
|||||||
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('');
|
||||||
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
|
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
|
||||||
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled?window.daybreakMail:null;
|
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled&&window.daybreakMail?.setAppLockDelay?window.daybreakMail:null;
|
||||||
|
const localDataBridge=window.daybreakMail?.deleteAllLocalData?window.daybreakMail:null;
|
||||||
let notificationPrivacy={showDetails:false};
|
let notificationPrivacy={showDetails:false};
|
||||||
let appLockSettings={enabled:false,deviceSecure:false};
|
let appLockSettings={enabled:false,deviceSecure:false,lockDelaySeconds:0};
|
||||||
if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}}
|
if(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}}
|
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 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>`:'';
|
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><label class="compose-line"><span>Lock delay</span><select class="settings-select" id="app-lock-delay"><option value="0"${appLockSettings.lockDelaySeconds===0?' selected':''}>Immediately</option><option value="30"${appLockSettings.lockDelaySeconds===30?' selected':''}>30 seconds</option><option value="60"${appLockSettings.lockDelaySeconds===60?' selected':''}>1 minute</option><option value="300"${appLockSettings.lockDelaySeconds===300?' selected':''}>5 minutes</option></select></label><p class="account-note">Requires a secure Android screen lock. Screenshots are hidden as soon as you leave; mail sync continues in the background.</p>`:'';
|
||||||
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 localDataSetting=localDataBridge?`<h3 class="pgp-heading">Local data</h3><p class="account-note">Delete saved accounts, cached mail, drafts, queued sends, OpenPGP keys, app settings, and attachments saved by ep-mail to Downloads.</p><button class="discard" id="delete-all-local-data">Delete all local data…</button>`:'';
|
||||||
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}${localDataSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
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=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('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge){await appLockBridge.setAppLockDelay(Number(selectProductivityUi('#app-lock-delay').value));await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked)}productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}};
|
||||||
|
if(localDataBridge)selectProductivityUi('#delete-all-local-data').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await localDataBridge.deleteAllLocalData();if(!result?.deleted){button.disabled=false;return}if('serviceWorker'in navigator){const registrations=await navigator.serviceWorker.getRegistrations();await Promise.all(registrations.map(registration=>registration.unregister()))}if('caches'in window){const names=await caches.keys();await Promise.all(names.map(name=>caches.delete(name)))}localStorage.clear();window.location.reload()}catch(error){button.disabled=false;toastProductivityUi(error.message||'Native data was deleted, but browser data cleanup did not finish. Restart ep-mail to complete cleanup.')}};
|
||||||
selectProductivityUi('#theme-select').focus();
|
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(); }
|
||||||
|
|||||||
@@ -5,11 +5,14 @@ const EpMail = registerPlugin('EpMail');
|
|||||||
|
|
||||||
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
||||||
const daybreakMail = {
|
const daybreakMail = {
|
||||||
|
platform: 'android',
|
||||||
getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
|
getAppVersion: () => EpMail.getAppVersion().then(result => result.version),
|
||||||
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
|
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
|
||||||
setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }),
|
setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }),
|
||||||
getAppLockSettings: () => EpMail.getAppLockSettings(),
|
getAppLockSettings: () => EpMail.getAppLockSettings(),
|
||||||
setAppLockEnabled: enabled => EpMail.setAppLockEnabled({ enabled }),
|
setAppLockEnabled: enabled => EpMail.setAppLockEnabled({ enabled }),
|
||||||
|
setAppLockDelay: seconds => EpMail.setAppLockDelay({ seconds }),
|
||||||
|
deleteAllLocalData: () => EpMail.deleteAllLocalData(),
|
||||||
getAccount: () => EpMail.getAccount(),
|
getAccount: () => EpMail.getAccount(),
|
||||||
listAccounts: () => EpMail.listAccounts(),
|
listAccounts: () => EpMail.listAccounts(),
|
||||||
selectAccount: id => EpMail.selectAccount({ id }),
|
selectAccount: id => EpMail.selectAccount({ id }),
|
||||||
@@ -17,6 +20,7 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
|||||||
connect: details => EpMail.connect(details),
|
connect: details => EpMail.connect(details),
|
||||||
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
||||||
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
||||||
|
getCachedFolder: (folder, offset, filters) => EpMail.getCachedFolder({ folder, offset, filters }).then(result => result.cached),
|
||||||
listFolders: () => EpMail.listFolders(),
|
listFolders: () => EpMail.listFolders(),
|
||||||
createFolder: name => EpMail.createFolder({ name }),
|
createFolder: name => EpMail.createFolder({ name }),
|
||||||
listDrafts: () => EpMail.listDrafts(),
|
listDrafts: () => EpMail.listDrafts(),
|
||||||
|
|||||||
+47
-4
@@ -255,7 +255,7 @@ async function signatureStatuses(signatures, verification, sender) {
|
|||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createAndroidPgp({ EpMail, getAccount }) {
|
export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.confirm }) {
|
||||||
let storePromise;
|
let storePromise;
|
||||||
const passphrases = new Map();
|
const passphrases = new Map();
|
||||||
let cacheMinutes = 10;
|
let cacheMinutes = 10;
|
||||||
@@ -335,16 +335,26 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
async function unlock(fingerprint, passphrase) {
|
async function unlock(fingerprint, passphrase) {
|
||||||
const entry = (await store()).keys.find(item => item.fingerprint === fingerprint);
|
const entry = (await store()).keys.find(item => item.fingerprint === fingerprint);
|
||||||
if (!entry) throw new Error('That key was not found.');
|
if (!entry) throw new Error('That key was not found.');
|
||||||
|
const secret = passphrase || await biometricPassphrase(fingerprint);
|
||||||
|
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email || 'your key'}.`), { code: 'PASSPHRASE_REQUIRED' });
|
||||||
|
return unlockWithPassphrase(entry, secret);
|
||||||
|
}
|
||||||
|
async function unlockWithPassphrase(entry, passphrase) {
|
||||||
try { return await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: entry.privateKey }), passphrase }); }
|
try { return await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: entry.privateKey }), passphrase }); }
|
||||||
catch { throw new Error('The passphrase is incorrect.'); }
|
catch { throw new Error('The passphrase is incorrect.'); }
|
||||||
}
|
}
|
||||||
|
async function biometricPassphrase(fingerprint) {
|
||||||
|
if (typeof EpMail.getPgpBiometricPassphrase !== 'function') return null;
|
||||||
|
const result = await EpMail.getPgpBiometricPassphrase({ fingerprint });
|
||||||
|
return result?.enabled && typeof result.passphrase === 'string' ? result.passphrase : null;
|
||||||
|
}
|
||||||
async function signerFor(account, passphrase) {
|
async function signerFor(account, passphrase) {
|
||||||
const data = await store();
|
const data = await store();
|
||||||
const entry = data.keys.find(item => item.email.toLowerCase() === String(account.email).toLowerCase());
|
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' });
|
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);
|
const secret = passphrase || cached(entry.fingerprint) || await biometricPassphrase(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 });
|
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 }; }
|
try { const key = await unlockWithPassphrase(entry, 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 }); }
|
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) {
|
async function buildOutgoing(message) {
|
||||||
@@ -363,6 +373,16 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
if (pgp.encrypt && recipientKeys.missing.length) {
|
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 });
|
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(', ')}.`), { code: 'NO_RECIPIENT_KEY', missing: recipientKeys.missing });
|
||||||
}
|
}
|
||||||
|
const unverifiedKeys = recipientKeys.keys.filter(item => item.trust !== 'verified');
|
||||||
|
if (pgp.encrypt && unverifiedKeys.length) {
|
||||||
|
const details = unverifiedKeys.map(item =>
|
||||||
|
`${item.address}\n${item.fingerprint.match(/.{1,4}/g).join(' ')} (${item.trust})`
|
||||||
|
).join('\n\n');
|
||||||
|
const warning = `These recipient keys have not been verified by fingerprint:\n\n${details}\n\nIf a key is incorrect, its owner may be able to read this message. Compare each fingerprint with its owner through another channel before sending. Send encrypted mail to these unverified keys anyway?`;
|
||||||
|
if (typeof confirm !== 'function' || !confirm(warning)) {
|
||||||
|
throw Object.assign(new Error('Sending to unverified recipient keys was cancelled.'), { code: 'UNVERIFIED_RECIPIENT_KEY' });
|
||||||
|
}
|
||||||
|
}
|
||||||
let inner = mimeInner(`${String(message.text || '').slice(0, 500000)}${account.signature ? `\n\n${String(account.signature).slice(0, 5000)}` : ''}`, message.attachments || []);
|
let inner = mimeInner(`${String(message.text || '').slice(0, 500000)}${account.signature ? `\n\n${String(account.signature).slice(0, 5000)}` : ''}`, message.attachments || []);
|
||||||
const headers = [
|
const headers = [
|
||||||
`From: ${formatAddress(from)}`,
|
`From: ${formatAddress(from)}`,
|
||||||
@@ -425,6 +445,7 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
selected = candidates.find(entry => cached(entry.fingerprint)) || selected;
|
selected = candidates.find(entry => cached(entry.fingerprint)) || selected;
|
||||||
secret = cached(selected.fingerprint);
|
secret = cached(selected.fingerprint);
|
||||||
}
|
}
|
||||||
|
if (!secret) secret = await biometricPassphrase(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.' };
|
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;
|
let privateKey;
|
||||||
try { privateKey = await unlock(selected.fingerprint, secret); }
|
try { privateKey = await unlock(selected.fingerprint, secret); }
|
||||||
@@ -529,6 +550,23 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
entry.privateKey = protectedKey.armor(); await persist(data); clear(fingerprint); return { changed: true };
|
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 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 enableBiometricUnlock({ fingerprint, passphrase }) {
|
||||||
|
if (typeof EpMail.setPgpBiometricUnlock !== 'function') throw new Error('Biometric key unlock is not available on this device.');
|
||||||
|
const entry = (await store()).keys.find(item => item.fingerprint === fingerprint);
|
||||||
|
if (!entry) throw new Error('That key was not found.');
|
||||||
|
if (!passphrase) throw new Error('Enter the key passphrase first.');
|
||||||
|
await unlockWithPassphrase(entry, passphrase);
|
||||||
|
return EpMail.setPgpBiometricUnlock({ fingerprint, passphrase });
|
||||||
|
},
|
||||||
|
async biometricUnlockEnabled(fingerprint) {
|
||||||
|
if (typeof EpMail.pgpBiometricUnlockEnabled !== 'function') return false;
|
||||||
|
return Boolean((await EpMail.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled);
|
||||||
|
},
|
||||||
|
async disableBiometricUnlock(fingerprint) {
|
||||||
|
if (typeof EpMail.removePgpBiometricUnlock !== 'function') throw new Error('Biometric key unlock is not available on this device.');
|
||||||
|
clear(fingerprint);
|
||||||
|
return EpMail.removePgpBiometricUnlock({ fingerprint });
|
||||||
|
},
|
||||||
async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); },
|
async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); },
|
||||||
async addContact(input = {}) {
|
async addContact(input = {}) {
|
||||||
const armoredKey = input.armoredKey || prompt('Paste an ASCII-armored OpenPGP public key (up to 200 KB):') || '';
|
const armoredKey = input.armoredKey || prompt('Paste an ASCII-armored OpenPGP public key (up to 200 KB):') || '';
|
||||||
@@ -547,8 +585,13 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
const { keys, missing } = await resolveRecipients(addresses);
|
const { keys, missing } = await resolveRecipients(addresses);
|
||||||
const account = await getAccount();
|
const account = await getAccount();
|
||||||
const entry = sign ? (await store()).keys.find(item => item.email.toLowerCase() === String(account?.email || '').toLowerCase()) : null;
|
const entry = sign ? (await store()).keys.find(item => item.email.toLowerCase() === String(account?.email || '').toLowerCase()) : null;
|
||||||
|
let biometricUnlockEnabled = false;
|
||||||
|
if (entry && typeof EpMail.pgpBiometricUnlockEnabled === 'function') {
|
||||||
|
biometricUnlockEnabled = Boolean((await EpMail.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled);
|
||||||
|
}
|
||||||
return { recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })), missing,
|
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 };
|
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name,
|
||||||
|
unlocked: Boolean(cached(entry.fingerprint)), biometricUnlockEnabled } : null };
|
||||||
},
|
},
|
||||||
decryptMessage,
|
decryptMessage,
|
||||||
verifyMessage,
|
verifyMessage,
|
||||||
|
|||||||
+25
-2
@@ -1,5 +1,28 @@
|
|||||||
const CACHE='ep-mail-v19';
|
const CACHE='ep-mail-v22';
|
||||||
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)).then(()=>self.skipWaiting())));
|
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)))).then(()=>self.clients.claim())));
|
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 => {
|
||||||
|
const request = event.request;
|
||||||
|
if (request.method !== 'GET' || new URL(request.url).origin !== location.origin) return;
|
||||||
|
event.respondWith((async () => {
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetch(request, { cache: 'no-cache' });
|
||||||
|
} catch (error) {
|
||||||
|
const cached = await caches.match(request) ||
|
||||||
|
(request.mode === 'navigate' ? await caches.match('./index.html') : null);
|
||||||
|
if (cached) return cached;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
if (response.ok) {
|
||||||
|
try {
|
||||||
|
const cache = await caches.open(CACHE);
|
||||||
|
await cache.put(request, response.clone());
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Could not update offline app cache:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
})());
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,479 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const source = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
|
||||||
|
const syncSource = source.slice(source.indexOf('async function syncMailbox('), source.indexOf('\nif (window.daybreakMail) {', source.indexOf('async function syncMailbox(')));
|
||||||
|
|
||||||
|
function deferred() {
|
||||||
|
let resolve;
|
||||||
|
const promise = new Promise(done => { resolve = done; });
|
||||||
|
return { promise, resolve };
|
||||||
|
}
|
||||||
|
|
||||||
|
function harness({ platform = 'android', cached, sync }) {
|
||||||
|
const messages = [];
|
||||||
|
const state = { messages, activeMessage: null, activeFolder: 'Inbox', activeView: 'mail', selectedIds: new Set(), query: '' };
|
||||||
|
const feature = { connectedAccount: { id: 'account' }, pageOffset: 0, syncPromise: null, syncQueued: false, displayedMailboxKey: JSON.stringify(['account', 'Inbox']) };
|
||||||
|
const elements = new Map();
|
||||||
|
const opened = [];
|
||||||
|
const renders = [];
|
||||||
|
const toasts = [];
|
||||||
|
const classes = new Set();
|
||||||
|
const bridge = {
|
||||||
|
platform,
|
||||||
|
syncFolder: sync,
|
||||||
|
updateMessage: () => Promise.resolve()
|
||||||
|
};
|
||||||
|
if (cached) bridge.getCachedFolder = cached;
|
||||||
|
const context = {
|
||||||
|
window: { daybreakMail: bridge },
|
||||||
|
document: { visibilityState: 'visible', body: { classList: { remove: value => classes.delete(value), contains: value => classes.has(value) } } },
|
||||||
|
rendererState: state,
|
||||||
|
mailFeatureState: feature,
|
||||||
|
selectMailUi: selector => {
|
||||||
|
if (!elements.has(selector)) elements.set(selector, { classList: { toggle() {} }, innerHTML: '', textContent: '' });
|
||||||
|
return elements.get(selector);
|
||||||
|
},
|
||||||
|
appShell: {
|
||||||
|
renderList: () => renders.push(messages.map(message => message.id)),
|
||||||
|
openMessage: id => opened.push(id),
|
||||||
|
getReaderListPosition: () => 0,
|
||||||
|
emptyReader: () => 'empty'
|
||||||
|
},
|
||||||
|
mailSearchFilters: () => ({}),
|
||||||
|
localStorage: { getItem: () => null },
|
||||||
|
updateAccountCard() {},
|
||||||
|
toastMailUi: message => toasts.push(message),
|
||||||
|
console
|
||||||
|
};
|
||||||
|
vm.runInNewContext(`${syncSource}\nthis.syncMailbox = syncMailbox`, context);
|
||||||
|
return { state, feature, context, elements, opened, renders, classes, toasts };
|
||||||
|
}
|
||||||
|
|
||||||
|
function result(ids) {
|
||||||
|
return { messages: ids.map(id => ({ id, uid: id, tags: [] })), total: ids.length, start: 1, end: ids.length };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Android shows cached inbox before network sync without opening a message', async () => {
|
||||||
|
const network = deferred();
|
||||||
|
const ui = harness({ cached: async () => result([1]), sync: () => network.promise });
|
||||||
|
const pending = ui.context.syncMailbox(false);
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(ui.renders[0], [1]);
|
||||||
|
assert.equal(ui.state.activeMessage, null);
|
||||||
|
assert.equal(ui.elements.get('#mail-status').textContent, 'Showing saved messages — syncing');
|
||||||
|
network.resolve(result([2, 1]));
|
||||||
|
await pending;
|
||||||
|
assert.equal(ui.state.activeMessage, null);
|
||||||
|
assert.deepEqual(ui.opened, []);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [2, 1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android refresh respects back navigation during an in-flight sync', async () => {
|
||||||
|
const network = deferred();
|
||||||
|
const ui = harness({ sync: () => network.promise });
|
||||||
|
ui.state.activeMessage = 1;
|
||||||
|
ui.classes.add('reader-open');
|
||||||
|
const pending = ui.context.syncMailbox(false);
|
||||||
|
ui.state.activeMessage = null;
|
||||||
|
ui.classes.delete('reader-open');
|
||||||
|
network.resolve(result([1, 2]));
|
||||||
|
await pending;
|
||||||
|
assert.equal(ui.state.activeMessage, null);
|
||||||
|
assert.deepEqual(ui.opened, []);
|
||||||
|
assert.equal(ui.elements.get('#reader-pane').innerHTML, 'empty');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refresh keeps an explicitly selected Android message and desktop still selects the first', async () => {
|
||||||
|
const android = harness({ sync: async () => result([1, 2]) });
|
||||||
|
android.state.activeMessage = 2;
|
||||||
|
await android.context.syncMailbox(false);
|
||||||
|
assert.deepEqual(android.opened, [2]);
|
||||||
|
const desktop = harness({ platform: 'desktop', sync: async () => result([1, 2]) });
|
||||||
|
await desktop.context.syncMailbox(false);
|
||||||
|
assert.deepEqual(desktop.opened, [1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a message selected from the cache stays open when sync finishes', async () => {
|
||||||
|
const network = deferred();
|
||||||
|
const ui = harness({ cached: async () => result([1]), sync: () => network.promise });
|
||||||
|
const pending = ui.context.syncMailbox(false);
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
ui.state.activeMessage = 1;
|
||||||
|
network.resolve(result([2, 1]));
|
||||||
|
await pending;
|
||||||
|
assert.deepEqual(ui.opened, [1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sync errors leave cached messages visible and report the failure', async () => {
|
||||||
|
const ui = harness({
|
||||||
|
cached: async () => result([1]),
|
||||||
|
sync: async () => { throw new Error('Network failed'); }
|
||||||
|
});
|
||||||
|
await ui.context.syncMailbox(false);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1]);
|
||||||
|
assert.equal(ui.elements.get('#mail-status').textContent, 'Could not sync — showing saved messages');
|
||||||
|
assert.deepEqual(ui.toasts, ['Network failed']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a sync result for a previous folder does not replace the current mailbox', async () => {
|
||||||
|
const network = deferred();
|
||||||
|
const ui = harness({ sync: () => network.promise });
|
||||||
|
const pending = ui.context.syncMailbox(false);
|
||||||
|
ui.state.activeFolder = 'Sent';
|
||||||
|
network.resolve(result([1]));
|
||||||
|
await pending;
|
||||||
|
assert.equal(ui.state.messages.length, 0);
|
||||||
|
assert.deepEqual(ui.opened, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('switching folders shows that folder’s cached messages before the network response', async () => {
|
||||||
|
const network = deferred();
|
||||||
|
const ui = harness({
|
||||||
|
cached: async folder => folder === 'Sent' ? result([42]) : null,
|
||||||
|
sync: () => network.promise
|
||||||
|
});
|
||||||
|
ui.state.messages.push({ id: 1, uid: 1, tags: [] });
|
||||||
|
ui.state.activeFolder = 'Sent';
|
||||||
|
const pending = ui.context.syncMailbox(false, { offset: 0 });
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [42]);
|
||||||
|
assert.deepEqual(ui.renders.at(-1), [42]);
|
||||||
|
network.resolve(result([43]));
|
||||||
|
await pending;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a different folder can load from cache while the previous folder is still syncing', async () => {
|
||||||
|
const inbox = deferred();
|
||||||
|
const sent = deferred();
|
||||||
|
const ui = harness({
|
||||||
|
cached: async folder => folder === 'Sent' ? result([42]) : null,
|
||||||
|
sync: folder => folder === 'Inbox' ? inbox.promise : sent.promise
|
||||||
|
});
|
||||||
|
const first = ui.context.syncMailbox(false);
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
ui.state.activeFolder = 'Sent';
|
||||||
|
const second = ui.context.syncMailbox(false, { offset: 0 });
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [42]);
|
||||||
|
sent.resolve(result([43]));
|
||||||
|
await second;
|
||||||
|
inbox.resolve(result([1]));
|
||||||
|
await first;
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [43]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returning to a folder ignores an older request for the same folder', async () => {
|
||||||
|
const firstInbox = deferred();
|
||||||
|
const sent = deferred();
|
||||||
|
const secondInbox = deferred();
|
||||||
|
let calls = 0;
|
||||||
|
const ui = harness({
|
||||||
|
sync: () => [firstInbox, sent, secondInbox][calls++].promise
|
||||||
|
});
|
||||||
|
const first = ui.context.syncMailbox(false);
|
||||||
|
ui.state.activeFolder = 'Sent';
|
||||||
|
const middle = ui.context.syncMailbox(false);
|
||||||
|
ui.state.activeFolder = 'Inbox';
|
||||||
|
const last = ui.context.syncMailbox(false);
|
||||||
|
secondInbox.resolve(result([3]));
|
||||||
|
await last;
|
||||||
|
firstInbox.resolve(result([1]));
|
||||||
|
sent.resolve(result([2]));
|
||||||
|
await Promise.all([first, middle]);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [3]);
|
||||||
|
assert.equal(ui.elements.get('#refresh').disabled, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('switching accounts never displays the previous account’s messages', async () => {
|
||||||
|
const network = deferred();
|
||||||
|
const ui = harness({ cached: async () => null, sync: () => network.promise });
|
||||||
|
ui.state.messages.push({ id: 1, uid: 1, tags: [] });
|
||||||
|
ui.feature.connectedAccount = { id: 'other' };
|
||||||
|
const pending = ui.context.syncMailbox(false);
|
||||||
|
assert.equal(ui.state.messages.length, 0);
|
||||||
|
network.resolve(result([2]));
|
||||||
|
await pending;
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('scrolling to the end appends one page and retains the scroll position', async () => {
|
||||||
|
const next = deferred();
|
||||||
|
const offsets = [];
|
||||||
|
const ui = harness({ sync: (_folder, offset) => {
|
||||||
|
offsets.push(offset);
|
||||||
|
return next.promise;
|
||||||
|
} });
|
||||||
|
ui.state.messages.push(...result([1, 2]).messages);
|
||||||
|
ui.feature.total = 5;
|
||||||
|
ui.feature.nextOffset = 2;
|
||||||
|
const list = ui.context.selectMailUi('#message-list');
|
||||||
|
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 700 });
|
||||||
|
ui.context.appShell.renderList = () => { list.scrollTop = 0; };
|
||||||
|
ui.context.maybeLoadMoreMessages();
|
||||||
|
ui.context.maybeLoadMoreMessages();
|
||||||
|
assert.deepEqual(offsets, [2]);
|
||||||
|
list.scrollHeight = 1400;
|
||||||
|
next.resolve({ messages: result([3, 4]).messages, total: 5, start: 2, end: 3 });
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3, 4]);
|
||||||
|
assert.equal(list.scrollTop, 700);
|
||||||
|
assert.deepEqual(offsets, [2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android background refresh waits while browsing and runs at the top', async () => {
|
||||||
|
const offsets = [];
|
||||||
|
const ui = harness({ sync: async (_folder, offset) => {
|
||||||
|
offsets.push(offset);
|
||||||
|
return { messages: result([1, 2]).messages, total: 40, start: 21, end: 22 };
|
||||||
|
} });
|
||||||
|
ui.state.messages.push(...result([1, 2, 3]).messages);
|
||||||
|
ui.feature.total = 40;
|
||||||
|
ui.feature.nextOffset = 40;
|
||||||
|
const list = ui.context.selectMailUi('#message-list');
|
||||||
|
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 700 });
|
||||||
|
ui.context.requestBackgroundMailboxRefresh();
|
||||||
|
ui.context.requestBackgroundMailboxRefresh({ offset: 0 });
|
||||||
|
assert.deepEqual(offsets, []);
|
||||||
|
assert.equal(ui.feature.browseRefreshPending, true);
|
||||||
|
assert.match(ui.elements.get('#mail-status').textContent, /Updates paused/);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
|
||||||
|
list.scrollTop = 0;
|
||||||
|
ui.context.handleMessageListScroll();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(offsets, [0]);
|
||||||
|
assert.equal(ui.feature.browseRefreshPending, false);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('automatic refresh is deferred during an Android page fetch and manual refresh remains available', async () => {
|
||||||
|
const page = deferred();
|
||||||
|
const offsets = [];
|
||||||
|
const ui = harness({ sync: (_folder, offset) => {
|
||||||
|
offsets.push(offset);
|
||||||
|
return offsets.length === 1 ? page.promise : Promise.resolve(result([1]));
|
||||||
|
} });
|
||||||
|
ui.state.messages.push(...result([1, 2]).messages);
|
||||||
|
ui.feature.total = 40;
|
||||||
|
ui.feature.nextOffset = 20;
|
||||||
|
const list = ui.context.selectMailUi('#message-list');
|
||||||
|
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 700 });
|
||||||
|
const pending = ui.context.syncMailbox(false, { append: true });
|
||||||
|
assert.match(ui.elements.get('#mail-status').textContent, /Loading more/);
|
||||||
|
ui.context.requestBackgroundMailboxRefresh({ offset: 0 });
|
||||||
|
list.scrollHeight = 1400;
|
||||||
|
page.resolve({ messages: result([3, 4]).messages, total: 40, start: 1, end: 2 });
|
||||||
|
await pending;
|
||||||
|
assert.deepEqual(offsets, [20]);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3, 4]);
|
||||||
|
assert.match(ui.elements.get('#mail-status').textContent, /Updates paused/);
|
||||||
|
await ui.context.syncMailbox(true, { offset: 0 });
|
||||||
|
assert.deepEqual(offsets, [20, 0]);
|
||||||
|
assert.equal(ui.feature.browseRefreshPending, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('desktop background refresh remains immediate while scrolled down', async () => {
|
||||||
|
const offsets = [];
|
||||||
|
const ui = harness({ platform: 'desktop', sync: async (_folder, offset) => {
|
||||||
|
offsets.push(offset);
|
||||||
|
return result([1]);
|
||||||
|
} });
|
||||||
|
Object.assign(ui.context.selectMailUi('#message-list'), { scrollTop: 700, scrollHeight: 1000, clientHeight: 300 });
|
||||||
|
ui.context.requestBackgroundMailboxRefresh({ offset: 0 });
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.deepEqual(offsets, [0]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android defers background refresh when the hidden reader list was scrolled', () => {
|
||||||
|
let calls = 0;
|
||||||
|
const ui = harness({ sync: async () => { calls++; return result([1]); } });
|
||||||
|
ui.context.appShell.getReaderListPosition = () => 500;
|
||||||
|
ui.classes.add('reader-open');
|
||||||
|
Object.assign(ui.context.selectMailUi('#message-list'), { scrollTop: 0 });
|
||||||
|
ui.feature.nextOffset = 20;
|
||||||
|
ui.context.requestBackgroundMailboxRefresh();
|
||||||
|
assert.equal(calls, 0);
|
||||||
|
assert.equal(ui.feature.browseRefreshPending, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('short lists continue loading until the viewport is filled', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const ui = harness({ sync: async () => {
|
||||||
|
calls++;
|
||||||
|
return calls === 1
|
||||||
|
? { messages: result([1]).messages, total: 3, start: 3, end: 3 }
|
||||||
|
: { messages: result([2, 3]).messages, total: 3, start: 1, end: 2 };
|
||||||
|
} });
|
||||||
|
const list = ui.context.selectMailUi('#message-list');
|
||||||
|
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
|
||||||
|
await ui.context.syncMailbox(false, { offset: 0 });
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an appended page does not duplicate messages returned by a shifting mailbox', async () => {
|
||||||
|
const ui = harness({ sync: async () => ({ messages: result([2, 3, 3]).messages, total: 4, start: 1, end: 3 }) });
|
||||||
|
ui.state.messages.push(...result([1, 2]).messages);
|
||||||
|
ui.feature.total = 4;
|
||||||
|
ui.feature.nextOffset = 2;
|
||||||
|
await ui.context.syncMailbox(false, { append: true });
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('automatic loading waits for the list bottom and stops at the last page', () => {
|
||||||
|
let calls = 0;
|
||||||
|
const ui = harness({ sync: async () => { calls++; return result([]); } });
|
||||||
|
ui.feature.total = 40;
|
||||||
|
ui.feature.nextOffset = 20;
|
||||||
|
const list = ui.context.selectMailUi('#message-list');
|
||||||
|
Object.assign(list, { clientHeight: 300, scrollHeight: 1000, scrollTop: 100 });
|
||||||
|
ui.context.maybeLoadMoreMessages();
|
||||||
|
assert.equal(calls, 0);
|
||||||
|
list.scrollTop = 700;
|
||||||
|
ui.feature.nextOffset = 40;
|
||||||
|
ui.context.maybeLoadMoreMessages();
|
||||||
|
assert.equal(calls, 0);
|
||||||
|
ui.feature.nextOffset = 20;
|
||||||
|
ui.state.activeFolder = 'Drafts';
|
||||||
|
ui.context.maybeLoadMoreMessages();
|
||||||
|
assert.equal(calls, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pagination advances over snoozed messages and stops automatic loading on empty pages', async () => {
|
||||||
|
const offsets = [];
|
||||||
|
const ui = harness({ sync: async (_folder, offset) => {
|
||||||
|
offsets.push(offset);
|
||||||
|
if (offset === 0) return { messages: result([1]).messages, total: 45, start: 26, end: 45 };
|
||||||
|
return { messages: [], total: 45, start: 6, end: 25 };
|
||||||
|
} });
|
||||||
|
await ui.context.syncMailbox(false, { offset: 0 });
|
||||||
|
assert.equal(ui.feature.nextOffset, 20);
|
||||||
|
await ui.context.syncMailbox(false, { append: true });
|
||||||
|
assert.deepEqual(offsets, [0, 20]);
|
||||||
|
assert.equal(ui.feature.nextOffset, 40);
|
||||||
|
assert.equal(ui.feature.autoLoadBlocked, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('automatic pagination stops after a failed or empty fetch', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const ui = harness({ sync: async () => { calls++; throw new Error('Offline'); } });
|
||||||
|
ui.feature.total = 40;
|
||||||
|
ui.feature.nextOffset = 20;
|
||||||
|
const list = ui.context.selectMailUi('#message-list');
|
||||||
|
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
|
||||||
|
ui.context.maybeLoadMoreMessages();
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
ui.context.maybeLoadMoreMessages();
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
assert.equal(ui.feature.autoLoadBlocked, true);
|
||||||
|
assert.deepEqual(ui.toasts, ['Offline']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('offline cached pages can load automatically and stop at the cached total', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const ui = harness({ sync: async (_folder, offset) => {
|
||||||
|
calls++;
|
||||||
|
return offset === 0
|
||||||
|
? { messages: result([1]).messages, total: 2, start: 1, end: 1, offline: true }
|
||||||
|
: { messages: result([2]).messages, total: 2, start: 2, end: 2, offline: true };
|
||||||
|
} });
|
||||||
|
const list = ui.context.selectMailUi('#message-list');
|
||||||
|
Object.assign(list, { clientHeight: 300, scrollHeight: 300, scrollTop: 0 });
|
||||||
|
await ui.context.syncMailbox(false);
|
||||||
|
await new Promise(resolve => setImmediate(resolve));
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
assert.deepEqual(ui.state.messages.map(message => message.id), [1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android cache keeps newest messages when loading older pages', () => {
|
||||||
|
const vault = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidAccountVault.kt'), 'utf8');
|
||||||
|
const service = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
|
||||||
|
assert.match(vault, /sortedByDescending \{ it\.optLong\("timestamp"\) \}\.take\(30\)/);
|
||||||
|
assert.match(service, /cacheMessages\(account\.optString\("id"\), requestedFolder, cached, replace = offset <= 0\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('folder discovery deduplicates concurrent requests and ignores the previous account', async () => {
|
||||||
|
const first = deferred();
|
||||||
|
const second = deferred();
|
||||||
|
let calls = 0;
|
||||||
|
const feature = { connectedAccount: { id: 'one' }, customFolders: [] };
|
||||||
|
const renders = [];
|
||||||
|
const context = {
|
||||||
|
mailFeatureState: feature,
|
||||||
|
window: { daybreakMail: { listFolders: () => [first, second][calls++].promise } },
|
||||||
|
renderCustomFolders: () => renders.push(feature.customFolders.map(folder => folder.id)),
|
||||||
|
console
|
||||||
|
};
|
||||||
|
const start = source.indexOf('async function loadCustomFolders()');
|
||||||
|
const end = source.indexOf('\n// Destination options', start);
|
||||||
|
vm.runInNewContext(`${source.slice(start, end)}\nthis.loadCustomFolders = loadCustomFolders`, context);
|
||||||
|
const pending = context.loadCustomFolders();
|
||||||
|
const duplicate = context.loadCustomFolders();
|
||||||
|
assert.equal(calls, 1);
|
||||||
|
feature.connectedAccount = { id: 'two' };
|
||||||
|
const current = context.loadCustomFolders();
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
second.resolve({ folders: [{ id: 'new' }] });
|
||||||
|
await current;
|
||||||
|
first.resolve({ folders: [{ id: 'old' }] });
|
||||||
|
await Promise.all([pending, duplicate]);
|
||||||
|
assert.deepEqual(feature.customFolders.map(folder => folder.id), ['new']);
|
||||||
|
assert.deepEqual(renders, [['new']]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('folder discovery reports errors and allows retry', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const errors = [];
|
||||||
|
const feature = { connectedAccount: { id: 'one' }, customFolders: [] };
|
||||||
|
const context = {
|
||||||
|
mailFeatureState: feature,
|
||||||
|
window: { daybreakMail: { listFolders: async () => {
|
||||||
|
if (++calls === 1) throw new Error('Unavailable');
|
||||||
|
return { folders: [{ id: 'retried' }] };
|
||||||
|
} } },
|
||||||
|
renderCustomFolders() {},
|
||||||
|
console: { error: (...args) => errors.push(args) }
|
||||||
|
};
|
||||||
|
const start = source.indexOf('async function loadCustomFolders()');
|
||||||
|
const end = source.indexOf('\n// Destination options', start);
|
||||||
|
vm.runInNewContext(`${source.slice(start, end)}\nthis.loadCustomFolders = loadCustomFolders`, context);
|
||||||
|
await context.loadCustomFolders();
|
||||||
|
await context.loadCustomFolders();
|
||||||
|
assert.equal(errors.length, 1);
|
||||||
|
assert.equal(feature.customFolders[0].id, 'retried');
|
||||||
|
assert.equal(calls, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android folder discovery and message actions do not run on the Capacitor plugin thread', () => {
|
||||||
|
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
|
||||||
|
const list = plugin.slice(plugin.indexOf('fun listFolders('), plugin.indexOf('fun createFolder('));
|
||||||
|
const action = plugin.slice(plugin.indexOf('fun updateMessage('), plugin.indexOf('fun setSnooze('));
|
||||||
|
assert.ok(list.indexOf('folderListExecutor.execute') < list.indexOf('AndroidMailService.listFolders(account)'));
|
||||||
|
assert.ok(action.indexOf('mailActionExecutor.execute') < action.indexOf('AndroidMailService.updateMessage(account, input)'));
|
||||||
|
assert.match(action, /enqueueMailOperation/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android startup theme uses the EP vector on supported splash screens', () => {
|
||||||
|
const styles = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'values', 'styles.xml'), 'utf8');
|
||||||
|
const icon = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'res', 'drawable', 'ep_splash_icon.xml'), 'utf8');
|
||||||
|
assert.match(styles, /name="windowSplashScreenAnimatedIcon">@drawable\/ep_splash_icon/);
|
||||||
|
assert.match(styles, /name="postSplashScreenTheme">@style\/AppTheme.NoActionBar/);
|
||||||
|
assert.match(icon, /android:strokeColor="#eee9de"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android launcher icons use the EP logo on adaptive and legacy launchers', () => {
|
||||||
|
const res = path.join(root, 'android', 'app', 'src', 'main', 'res');
|
||||||
|
const read = (...parts) => fs.readFileSync(path.join(res, ...parts), 'utf8');
|
||||||
|
for (const name of ['ic_launcher.xml', 'ic_launcher_round.xml']) {
|
||||||
|
assert.match(read('mipmap-anydpi-v26', name), /@drawable\/ep_launcher_foreground/);
|
||||||
|
assert.match(read('mipmap-anydpi', name), /@drawable\/ep_splash_icon/);
|
||||||
|
}
|
||||||
|
assert.match(read('drawable', 'ep_launcher_foreground.xml'), /@drawable\/ep_splash_icon/);
|
||||||
|
assert.match(read('drawable', 'ep_launcher_foreground.xml'), /android:inset="22dp"/);
|
||||||
|
assert.match(read('values', 'ic_launcher_background.xml'), /#0a0c0b/);
|
||||||
|
});
|
||||||
@@ -38,7 +38,7 @@ function makeEndpoint(account) {
|
|||||||
async pgpGetMessageSource() { return messageSource; }
|
async pgpGetMessageSource() { return messageSource; }
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
api: createAndroidPgp({ EpMail, getAccount: async () => account }),
|
api: createAndroidPgp({ EpMail, getAccount: async () => account, confirm: () => true }),
|
||||||
setMessage(rawBase64) { messageSource = { rawBase64 }; }
|
setMessage(rawBase64) { messageSource = { rawBase64 }; }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const bundled = esbuild.buildSync({
|
|||||||
vm.runInThisContext(bundled);
|
vm.runInThisContext(bundled);
|
||||||
const { createAndroidPgp } = global.AndroidPgpBundle;
|
const { createAndroidPgp } = global.AndroidPgpBundle;
|
||||||
|
|
||||||
function makeEndpoint(account) {
|
function makeEndpoint(account, { confirm = () => true } = {}) {
|
||||||
const vault = { keys: [], contacts: [], settings: {} };
|
const vault = { keys: [], contacts: [], settings: {} };
|
||||||
let messageSource = null;
|
let messageSource = null;
|
||||||
const EpMail = {
|
const EpMail = {
|
||||||
@@ -29,7 +29,8 @@ function makeEndpoint(account) {
|
|||||||
async pgpGetMessageSource() { return messageSource; }
|
async pgpGetMessageSource() { return messageSource; }
|
||||||
};
|
};
|
||||||
return {
|
return {
|
||||||
api: createAndroidPgp({ EpMail, getAccount: async () => account }),
|
api: createAndroidPgp({ EpMail, getAccount: async () => account, confirm }),
|
||||||
|
EpMail,
|
||||||
setMessage(value) { messageSource = value; },
|
setMessage(value) { messageSource = value; },
|
||||||
vault
|
vault
|
||||||
};
|
};
|
||||||
@@ -84,6 +85,25 @@ test('Android OpenPGP refuses encryption when any recipient key is missing', asy
|
|||||||
}), error => error.code === 'NO_RECIPIENT_KEY');
|
}), error => error.code === 'NO_RECIPIENT_KEY');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Android OpenPGP requires explicit fingerprint confirmation for unverified recipient keys', async () => {
|
||||||
|
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' }, {
|
||||||
|
confirm: warning => {
|
||||||
|
assert.match(warning, /bob@example\.test/);
|
||||||
|
assert.match(warning, /[A-F0-9]{4}(?: [A-F0-9]{4}){9}/);
|
||||||
|
assert.match(warning, /not been verified by fingerprint/);
|
||||||
|
assert.match(warning, /Compare each fingerprint with its owner through another channel/);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
|
||||||
|
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
|
||||||
|
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
|
||||||
|
await assert.rejects(sender.api.buildOutgoing({
|
||||||
|
to: 'bob@example.test', text: 'do not send to an unverified key',
|
||||||
|
pgp: { encrypt: true }, attachments: []
|
||||||
|
}), error => error.code === 'UNVERIFIED_RECIPIENT_KEY');
|
||||||
|
});
|
||||||
|
|
||||||
test('Android verifies PGP/MIME signed-only and clear-signed mail', async () => {
|
test('Android verifies PGP/MIME signed-only and clear-signed mail', async () => {
|
||||||
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
|
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
|
||||||
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
|
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
|
||||||
@@ -167,3 +187,54 @@ test('Android rejects tampered, malformed, and oversized encrypted input', async
|
|||||||
recipient.setMessage({ rawBase64: 'A'.repeat(35_000_000) });
|
recipient.setMessage({ rawBase64: 'A'.repeat(35_000_000) });
|
||||||
assert.equal((await recipient.api.decryptMessage({ uid: 22, passphrase: 'bob test passphrase' })).code, 'TOO_LARGE');
|
assert.equal((await recipient.api.decryptMessage({ uid: 22, passphrase: 'bob test passphrase' })).code, 'TOO_LARGE');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Android biometric unlock remains optional and releases only a passphrase-verified PGP 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) });
|
||||||
|
|
||||||
|
let protectedPassphrase = null;
|
||||||
|
recipient.EpMail.setPgpBiometricUnlock = async ({ fingerprint, passphrase }) => {
|
||||||
|
assert.equal(fingerprint, bob.key.fingerprint);
|
||||||
|
protectedPassphrase = passphrase;
|
||||||
|
return { enabled: true };
|
||||||
|
};
|
||||||
|
recipient.EpMail.getPgpBiometricPassphrase = async ({ fingerprint }) => ({
|
||||||
|
enabled: fingerprint === bob.key.fingerprint && protectedPassphrase !== null,
|
||||||
|
passphrase: protectedPassphrase
|
||||||
|
});
|
||||||
|
recipient.EpMail.pgpBiometricUnlockEnabled = async () => ({ enabled: protectedPassphrase !== null });
|
||||||
|
|
||||||
|
await assert.rejects(
|
||||||
|
recipient.api.enableBiometricUnlock({ fingerprint: bob.key.fingerprint, passphrase: 'incorrect passphrase' }),
|
||||||
|
/incorrect/
|
||||||
|
);
|
||||||
|
assert.equal(protectedPassphrase, null);
|
||||||
|
await recipient.api.enableBiometricUnlock({ fingerprint: bob.key.fingerprint, passphrase: 'bob test passphrase' });
|
||||||
|
assert.equal((await recipient.api.checkSend({ to: 'bob@example.test', sign: true })).signer.biometricUnlockEnabled, true);
|
||||||
|
|
||||||
|
const built = await sender.api.buildOutgoing({
|
||||||
|
to: 'bob@example.test', subject: 'Biometric unlock test', text: 'protected body',
|
||||||
|
pgp: { encrypt: true }, attachments: []
|
||||||
|
});
|
||||||
|
recipient.setMessage({ rawBase64: built.rawBase64 });
|
||||||
|
const opened = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 23 });
|
||||||
|
assert.equal(opened.ok, true, opened.message);
|
||||||
|
assert.deepEqual(opened.body, ['protected body']);
|
||||||
|
assert.equal(Object.hasOwn(recipient.vault.keys[0], 'passphrase'), false);
|
||||||
|
assert.equal(Object.hasOwn(recipient.vault, 'passphrase'), false);
|
||||||
|
|
||||||
|
await recipient.api.setSettings({ cacheMinutes: 0 });
|
||||||
|
recipient.EpMail.getPgpBiometricPassphrase = async () => {
|
||||||
|
throw Object.assign(new Error('Biometric enrollment changed.'), { code: 'BIOMETRIC_INVALIDATED' });
|
||||||
|
};
|
||||||
|
const invalidated = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 23 });
|
||||||
|
assert.equal(invalidated.code, 'BIOMETRIC_INVALIDATED');
|
||||||
|
const recovered = await recipient.api.decryptMessage({
|
||||||
|
folder: 'Inbox', uid: 23, passphrase: 'bob test passphrase'
|
||||||
|
});
|
||||||
|
assert.equal(recovered.ok, true, recovered.message);
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
|
||||||
|
const root = path.resolve(__dirname, '..');
|
||||||
|
const source = fs.readFileSync(path.join(root, 'app.js'), 'utf8');
|
||||||
|
const helpers = source.slice(source.indexOf('let readerListPosition = null;'), source.indexOf('function renderList()'));
|
||||||
|
|
||||||
|
function harness(platform = 'android') {
|
||||||
|
const classes = new Set();
|
||||||
|
const list = { scrollTop: 0 };
|
||||||
|
const reader = { innerHTML: '' };
|
||||||
|
const state = { activeFolder: 'Inbox', activeMessage: 1 };
|
||||||
|
const context = {
|
||||||
|
window: { daybreakMail: { platform } },
|
||||||
|
document: { body: { classList: {
|
||||||
|
contains: value => classes.has(value),
|
||||||
|
remove: value => classes.delete(value)
|
||||||
|
} } },
|
||||||
|
state,
|
||||||
|
$: selector => selector === '#message-list' ? list : reader,
|
||||||
|
emptyReader: () => 'empty',
|
||||||
|
renderList: () => { list.scrollTop = 0; }
|
||||||
|
};
|
||||||
|
vm.runInNewContext(helpers, context);
|
||||||
|
return { context, classes, list, reader, state };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('opening and returning to a message restores the Android list position', () => {
|
||||||
|
const ui = harness();
|
||||||
|
ui.list.scrollTop = 675;
|
||||||
|
ui.context.rememberReaderListPosition();
|
||||||
|
ui.classes.add('reader-open');
|
||||||
|
ui.list.scrollTop = 0;
|
||||||
|
ui.context.returnToMessageList();
|
||||||
|
assert.equal(ui.list.scrollTop, 675);
|
||||||
|
assert.equal(ui.state.activeMessage, null);
|
||||||
|
assert.equal(ui.classes.has('reader-open'), false);
|
||||||
|
assert.equal(ui.reader.innerHTML, 'empty');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reader rerenders do not overwrite the saved position', () => {
|
||||||
|
const ui = harness();
|
||||||
|
ui.list.scrollTop = 600;
|
||||||
|
ui.context.rememberReaderListPosition();
|
||||||
|
ui.classes.add('reader-open');
|
||||||
|
ui.list.scrollTop = 0;
|
||||||
|
ui.context.rememberReaderListPosition();
|
||||||
|
ui.context.returnToMessageList();
|
||||||
|
assert.equal(ui.list.scrollTop, 600);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('changing folders or using desktop does not restore an unrelated position', () => {
|
||||||
|
const changed = harness();
|
||||||
|
changed.list.scrollTop = 600;
|
||||||
|
changed.context.rememberReaderListPosition();
|
||||||
|
changed.state.activeFolder = 'Sent';
|
||||||
|
changed.context.returnToMessageList();
|
||||||
|
assert.equal(changed.list.scrollTop, 0);
|
||||||
|
const desktop = harness('desktop');
|
||||||
|
desktop.list.scrollTop = 600;
|
||||||
|
desktop.context.rememberReaderListPosition();
|
||||||
|
desktop.context.returnToMessageList();
|
||||||
|
assert.equal(desktop.list.scrollTop, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android system back uses the same reader button and falls back outside the reader', () => {
|
||||||
|
const activity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8');
|
||||||
|
assert.match(activity, /getOnBackPressedDispatcher\(\)\.addCallback/);
|
||||||
|
assert.match(activity, /appLocked \|\| vaultRecoveryRequired/);
|
||||||
|
assert.match(activity, /reader-open/);
|
||||||
|
assert.match(activity, /#modal-root \.modal-overlay/);
|
||||||
|
assert.match(activity, /back\.click\(\)/);
|
||||||
|
assert.match(activity, /if \(!"true"\.equals\(result\)\) dispatchDefaultBack/);
|
||||||
|
assert.match(source, /\$\('#reader-back'\)\.onclick=returnToMessageList/);
|
||||||
|
});
|
||||||
@@ -20,6 +20,11 @@ const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'),
|
|||||||
const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
|
const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
|
||||||
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||||
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
|
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
|
||||||
|
const index = fs.readFileSync(path.join(root, 'index.html'), 'utf8');
|
||||||
|
const manifest = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'AndroidManifest.xml'), 'utf8');
|
||||||
|
const davService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidDavService.kt'), 'utf8');
|
||||||
|
const biometricUnlock = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpBiometricUnlock.kt'), 'utf8');
|
||||||
|
const boundedInputReader = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'BoundedInputReader.kt'), 'utf8');
|
||||||
|
|
||||||
test('mobile layout removes desktop minimum width and provides a compact reader flow', () => {
|
test('mobile layout removes desktop minimum width and provides a compact reader flow', () => {
|
||||||
assert.match(styles, /min-width:320px/);
|
assert.match(styles, /min-width:320px/);
|
||||||
@@ -79,7 +84,64 @@ test('Android app lock is native-enforced and requires a secure device credentia
|
|||||||
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
|
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
|
||||||
assert.match(androidBridge, /getAppLockSettings/);
|
assert.match(androidBridge, /getAppLockSettings/);
|
||||||
assert.match(androidBridge, /setAppLockEnabled/);
|
assert.match(androidBridge, /setAppLockEnabled/);
|
||||||
|
assert.match(androidBridge, /setAppLockDelay/);
|
||||||
assert.match(productivity, /Lock when leaving ep-mail/);
|
assert.match(productivity, /Lock when leaving ep-mail/);
|
||||||
|
assert.match(productivity, /app-lock-delay/);
|
||||||
|
assert.match(mainActivity, /postDelayed\(delayedAppLock/);
|
||||||
|
assert.match(mainActivity, /FLAG_SECURE/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android biometric PGP unlock keeps secrets behind an authentication-bound Keystore key', () => {
|
||||||
|
assert.match(plugin, /fun setPgpBiometricUnlock/);
|
||||||
|
assert.match(plugin, /fun getPgpBiometricPassphrase/);
|
||||||
|
assert.match(plugin, /fun removePgpBiometricUnlock/);
|
||||||
|
assert.match(plugin, /fun pgpBiometricUnlockEnabled/);
|
||||||
|
assert.match(mainActivity, /authenticatePgpCipher/);
|
||||||
|
assert.match(mainActivity, /pgpAuthInProgress/);
|
||||||
|
assert.match(biometricUnlock, /setUserAuthenticationRequired\(true\)/);
|
||||||
|
assert.match(biometricUnlock, /setUserAuthenticationParameters/);
|
||||||
|
assert.match(vault, /pgpBiometricUnlocks/);
|
||||||
|
assert.match(vault, /removedFingerprints\.forEach/);
|
||||||
|
assert.match(androidPgp, /enableBiometricUnlock/);
|
||||||
|
assert.match(androidPgp, /getPgpBiometricPassphrase/);
|
||||||
|
assert.match(pgpMailUi, /BIOMETRIC_INVALIDATED/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android full local-data deletion is explicit, scoped, and clears stored web data', () => {
|
||||||
|
assert.match(productivity, /Delete all local data/);
|
||||||
|
assert.match(androidBridge, /deleteAllLocalData/);
|
||||||
|
assert.match(plugin, /fun deleteAllLocalData/);
|
||||||
|
assert.match(plugin, /setPositiveButton\("Delete all data"\)/);
|
||||||
|
assert.match(vault, /fun wipe\(\)/);
|
||||||
|
assert.match(androidMailService, /fun deleteSavedAttachments/);
|
||||||
|
assert.match(androidMailService, /isAppOwnedDownload/);
|
||||||
|
assert.match(androidMailService, /BoundedInputReader\.read\(it, 5 \* 1048576 \+ 1\)/);
|
||||||
|
assert.match(androidMailService, /BoundedInputReader\.read\(it, 100001\)/);
|
||||||
|
assert.match(androidMailService, /saveAttachmentStream/);
|
||||||
|
assert.match(boundedInputReader, /while \(output\.size\(\) < maxBytes\)/);
|
||||||
|
assert.match(mainActivity, /clearLocalWebData/);
|
||||||
|
assert.match(productivity, /getRegistrations\(\)/);
|
||||||
|
assert.match(productivity, /caches\.delete\(name\)/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android WebView CSP, manifest, navigation, and DAV transport stay constrained', () => {
|
||||||
|
const csp = /http-equiv="Content-Security-Policy" content="([^"]+)"/i.exec(index)?.[1] || '';
|
||||||
|
assert.match(csp, /default-src 'self'/);
|
||||||
|
assert.match(csp, /script-src 'self'/);
|
||||||
|
assert.match(csp, /connect-src 'none'/);
|
||||||
|
assert.match(csp, /frame-src 'none'/);
|
||||||
|
assert.match(csp, /object-src 'none'/);
|
||||||
|
assert.match(csp, /base-uri 'none'/);
|
||||||
|
assert.match(csp, /form-action 'none'/);
|
||||||
|
assert.doesNotMatch(csp, /script-src[^;]*unsafe-inline/i);
|
||||||
|
assert.match(manifest, /android:allowBackup="false"/);
|
||||||
|
assert.match(manifest, /android:usesCleartextTraffic="false"/);
|
||||||
|
assert.doesNotMatch(manifest, /READ_EXTERNAL_STORAGE|WRITE_EXTERNAL_STORAGE|MANAGE_EXTERNAL_STORAGE|REQUEST_INSTALL_PACKAGES/);
|
||||||
|
assert.match(plugin, /Only standard web links can be opened from mail/);
|
||||||
|
assert.match(plugin, /uri\.scheme\?\.lowercase\(Locale\.ROOT\) !in setOf\("http", "https"\)/);
|
||||||
|
assert.match(davService, /followRedirects\(false\)/);
|
||||||
|
assert.match(davService, /followSslRedirects\(false\)/);
|
||||||
|
assert.match(davService, /DavUrlPolicy\.requireSameOrigin/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Android OpenPGP uses the encrypted vault and queues only built MIME data', () => {
|
test('Android OpenPGP uses the encrypted vault and queues only built MIME data', () => {
|
||||||
@@ -88,6 +150,8 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data',
|
|||||||
assert.match(plugin, /fun pgpGetMessageSource/);
|
assert.match(plugin, /fun pgpGetMessageSource/);
|
||||||
assert.match(plugin, /pgpStoreChangeWarning/);
|
assert.match(plugin, /pgpStoreChangeWarning/);
|
||||||
assert.match(plugin, /plaintextSendWarning/);
|
assert.match(plugin, /plaintextSendWarning/);
|
||||||
|
assert.match(plugin, /AndroidPgpPolicy\.unverifiedRawMimeWarning\(\)/);
|
||||||
|
assert.match(plugin, /title = if \(rawMime\) "Send unverified MIME\?"/);
|
||||||
assert.match(plugin, /Send plaintext/);
|
assert.match(plugin, /Send plaintext/);
|
||||||
assert.match(plugin, /showPgpConfirmation\(/);
|
assert.match(plugin, /showPgpConfirmation\(/);
|
||||||
assert.match(plugin, /onCancelled = \{ call\.reject\("OpenPGP key change cancelled\."\) \}/);
|
assert.match(plugin, /onCancelled = \{ call\.reject\("OpenPGP key change cancelled\."\) \}/);
|
||||||
@@ -96,7 +160,9 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data',
|
|||||||
assert.match(androidPgpConfirmationGate, /compareAndSet\(false, true\)/);
|
assert.match(androidPgpConfirmationGate, /compareAndSet\(false, true\)/);
|
||||||
assert.match(androidPgpPolicy, /fun storeChangeWarning/);
|
assert.match(androidPgpPolicy, /fun storeChangeWarning/);
|
||||||
assert.match(androidPgpPolicy, /fun plaintextSendWarning/);
|
assert.match(androidPgpPolicy, /fun plaintextSendWarning/);
|
||||||
|
assert.match(androidPgpPolicy, /fun unverifiedRawMimeWarning/);
|
||||||
assert.match(androidPgp, /curve25519Legacy/);
|
assert.match(androidPgp, /curve25519Legacy/);
|
||||||
|
assert.match(androidPgp, /These recipient keys have not been verified by fingerprint/);
|
||||||
assert.match(androidPgp, /multipart\/encrypted/);
|
assert.match(androidPgp, /multipart\/encrypted/);
|
||||||
assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/);
|
assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/);
|
||||||
assert.match(androidPgp, /async function verifyMessage/);
|
assert.match(androidPgp, /async function verifyMessage/);
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'u
|
|||||||
const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8');
|
const androidDebugScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-apk.cjs'), 'utf8');
|
||||||
const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8');
|
const androidReleaseScript = fs.readFileSync(path.join(root, 'scripts', 'build-android-release-apk.cjs'), 'utf8');
|
||||||
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
|
const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8');
|
||||||
|
const androidRootBuild = fs.readFileSync(path.join(root, 'android', 'build.gradle'), 'utf8');
|
||||||
|
const androidProperties = fs.readFileSync(path.join(root, 'android', 'gradle.properties'), 'utf8');
|
||||||
|
const androidWrapper = fs.readFileSync(path.join(root, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'), 'utf8');
|
||||||
|
|
||||||
test('package metadata and lockfile share one release version', () => {
|
test('package metadata and lockfile share one release version', () => {
|
||||||
assert.equal(packageLock.version, packageJson.version);
|
assert.equal(packageLock.version, packageJson.version);
|
||||||
@@ -45,3 +48,15 @@ test('Android debug APK is labeled as debug and release APK requires signing cre
|
|||||||
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/);
|
assert.match(androidReleaseScript, /EP_MAIL_ANDROID_KEY_PASSWORD/);
|
||||||
assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/);
|
assert.match(androidReleaseScript, /ep-mail \$\{version\}\.apk/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Android Gradle and generated Capacitor modules use a compatible plugin version', () => {
|
||||||
|
const plugin = androidRootBuild.match(/classpath 'com\.android\.tools\.build:gradle:([^']+)'/);
|
||||||
|
const forced = androidRootBuild.match(/resolutionStrategy\.force 'com\.android\.tools\.build:gradle:([^']+)'/);
|
||||||
|
assert.ok(plugin && forced);
|
||||||
|
assert.equal(plugin[1], forced[1]);
|
||||||
|
assert.equal(plugin[1], '9.4.0');
|
||||||
|
assert.match(androidWrapper, /gradle-9\.7\.1-bin\.zip/);
|
||||||
|
assert.match(androidProperties, /^android\.builtInKotlin=false$/m);
|
||||||
|
assert.match(androidProperties, /^android\.newDsl=false$/m);
|
||||||
|
assert.match(androidBuild, /getDefaultProguardFile\('proguard-android-optimize\.txt'\)/);
|
||||||
|
});
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
|
||||||
|
const source = fs.readFileSync(path.join(__dirname, '..', 'service-worker.js'), 'utf8');
|
||||||
|
|
||||||
|
function harness({ network, cached }) {
|
||||||
|
const handlers = {};
|
||||||
|
const writes = [];
|
||||||
|
const context = {
|
||||||
|
URL,
|
||||||
|
location: { origin: 'https://localhost' },
|
||||||
|
self: { addEventListener: (type, handler) => { handlers[type] = handler; } },
|
||||||
|
caches: {
|
||||||
|
match: async request => cached.get(typeof request === 'string' ? request : request.url),
|
||||||
|
open: async () => ({ put: async (request, response) => writes.push([request.url, response]) })
|
||||||
|
},
|
||||||
|
fetch: network
|
||||||
|
};
|
||||||
|
vm.runInNewContext(source, context);
|
||||||
|
return {
|
||||||
|
writes,
|
||||||
|
async request(request) {
|
||||||
|
let response;
|
||||||
|
const pending = [];
|
||||||
|
handlers.fetch({
|
||||||
|
request,
|
||||||
|
respondWith(value) { response = value; },
|
||||||
|
waitUntil(value) { pending.push(value); }
|
||||||
|
});
|
||||||
|
if (!response) return { intercepted: false };
|
||||||
|
const result = await response;
|
||||||
|
await Promise.all(pending);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('new Android app assets replace old cached scripts', async () => {
|
||||||
|
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
|
||||||
|
const fresh = { ok: true, clone() { return this; } };
|
||||||
|
const old = { old: true };
|
||||||
|
const ui = harness({ network: async () => fresh, cached: new Map([[request.url, old]]) });
|
||||||
|
assert.equal(await ui.request(request), fresh);
|
||||||
|
assert.deepEqual(ui.writes, [[request.url, fresh]]);
|
||||||
|
assert.notEqual(source.match(/const CACHE\s*=\s*['"]([^'"]+)/)[1], 'ep-mail-v19');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('offline requests use cached assets and missing assets fail explicitly', async () => {
|
||||||
|
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
|
||||||
|
const old = { old: true };
|
||||||
|
const offline = async () => { throw new Error('offline'); };
|
||||||
|
const ui = harness({ network: offline, cached: new Map([[request.url, old]]) });
|
||||||
|
assert.equal(await ui.request(request), old);
|
||||||
|
const missing = harness({ network: offline, cached: new Map() });
|
||||||
|
await assert.rejects(missing.request(request), /offline/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('network failures for navigation use the cached app shell', async () => {
|
||||||
|
const request = { method: 'GET', url: 'https://localhost/', mode: 'navigate' };
|
||||||
|
const shell = { shell: true };
|
||||||
|
const ui = harness({
|
||||||
|
network: async () => { throw new Error('offline'); },
|
||||||
|
cached: new Map([['./index.html', shell]])
|
||||||
|
});
|
||||||
|
assert.equal(await ui.request(request), shell);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('HTTP error responses are not stored or replaced with cached content', async () => {
|
||||||
|
const request = { method: 'GET', url: 'https://localhost/mail-ui.js', mode: 'same-origin' };
|
||||||
|
const failed = { ok: false, status: 404 };
|
||||||
|
const ui = harness({ network: async () => failed, cached: new Map([[request.url, { old: true }]]) });
|
||||||
|
assert.equal(await ui.request(request), failed);
|
||||||
|
assert.deepEqual(ui.writes, []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cross-origin and non-GET requests are not intercepted', async () => {
|
||||||
|
const ui = harness({ network: async () => { throw new Error('unexpected fetch'); }, cached: new Map() });
|
||||||
|
assert.deepEqual(await ui.request({ method: 'GET', url: 'https://other.example/image.png' }), { intercepted: false });
|
||||||
|
assert.deepEqual(await ui.request({ method: 'POST', url: 'https://localhost/mail-ui.js' }), { intercepted: false });
|
||||||
|
});
|
||||||
+19
-1
@@ -4,11 +4,26 @@ 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;
|
||||||
|
let readerListPosition = null;
|
||||||
|
function rememberReaderListPosition() {
|
||||||
|
if (window.daybreakMail?.platform !== 'android' || document.body.classList.contains('reader-open')) return;
|
||||||
|
const list = $('#message-list');
|
||||||
|
readerListPosition = { folder: state.activeFolder, scrollTop: list.scrollTop };
|
||||||
|
}
|
||||||
|
function returnToMessageList() {
|
||||||
|
state.activeMessage = null;
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
$('#reader-pane').innerHTML = emptyReader();
|
||||||
|
renderList();
|
||||||
|
if (readerListPosition?.folder === state.activeFolder) $('#message-list').scrollTop = readerListPosition.scrollTop;
|
||||||
|
readerListPosition = null;
|
||||||
|
}
|
||||||
function renderList(){let rows=state.messages.filter(m=>{if(state.activeFolder==='Starred'&&!m.star)return false;if(state.activeFolder==='Inbox'&&m.archived)return false;if(state.activeFolder==='Archive'&&!m.archived)return false;if(state.activeFolder==='Trash'&&!m.deleted)return false;if(state.activeFolder==='Sent'&&!m.sent)return false;if(state.activeFolder==='Drafts')return false;if(state.activeFolder==='Snoozed')return false;if(m.deleted&&state.activeFolder!=='Trash')return false;return !state.query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(state.query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===state.activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${state.selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;state.selectedIds.has(id)?state.selectedIds.delete(id):state.selectedIds.add(id);return}if(e.target.closest('.star')){const m=state.messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length){document.body.classList.remove('reader-open');$('#reader-pane').innerHTML=emptyReader()}}
|
function 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){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
|
if(!m){state.activeMessage=null;document.body.classList.remove('reader-open');return;}
|
||||||
|
rememberReaderListPosition();
|
||||||
document.body.classList.add('reader-open');
|
document.body.classList.add('reader-open');
|
||||||
m.unread=false;
|
m.unread=false;
|
||||||
renderList();
|
renderList();
|
||||||
@@ -18,7 +33,7 @@ function openMessage(id){
|
|||||||
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"><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-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()};
|
$('#reader-back').onclick=returnToMessageList;
|
||||||
$('#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'));
|
||||||
@@ -51,6 +66,9 @@ window.epMailShell = Object.freeze({
|
|||||||
get renderList() { return renderList; },
|
get renderList() { return renderList; },
|
||||||
get openMessage() { return openMessage; },
|
get openMessage() { return openMessage; },
|
||||||
get showCompose() { return showCompose; },
|
get showCompose() { return showCompose; },
|
||||||
|
getReaderListPosition() {
|
||||||
|
return readerListPosition?.folder === state.activeFolder ? readerListPosition.scrollTop : 0;
|
||||||
|
},
|
||||||
emptyReader,
|
emptyReader,
|
||||||
wrapRenderList(decorator) { renderList = decorator(renderList); },
|
wrapRenderList(decorator) { renderList = decorator(renderList); },
|
||||||
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
|
wrapOpenMessage(decorator) { openMessage = decorator(openMessage); },
|
||||||
|
|||||||
+211
-18
@@ -8,12 +8,20 @@ const toastMailUi = appShell.toast;
|
|||||||
const mailFeatureState = {
|
const mailFeatureState = {
|
||||||
connectedAccount: null,
|
connectedAccount: null,
|
||||||
pageOffset: 0,
|
pageOffset: 0,
|
||||||
|
nextOffset: 0,
|
||||||
total: 0,
|
total: 0,
|
||||||
|
autoLoadBlocked: false,
|
||||||
syncPromise: null,
|
syncPromise: null,
|
||||||
syncQueued: false,
|
syncQueued: false,
|
||||||
|
syncMailboxKey: null,
|
||||||
|
displayedMailboxKey: null,
|
||||||
refreshPending: false,
|
refreshPending: false,
|
||||||
|
browseRefreshPending: false,
|
||||||
|
browseRefreshFromStart: false,
|
||||||
folderBeforeSearch: null,
|
folderBeforeSearch: null,
|
||||||
customFolders: [],
|
customFolders: [],
|
||||||
|
folderLoad: null,
|
||||||
|
foldersAccountId: null,
|
||||||
selectedDraftIds: new Set()
|
selectedDraftIds: new Set()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -142,10 +150,23 @@ function renderCustomFolders() {
|
|||||||
|
|
||||||
async function loadCustomFolders() {
|
async function loadCustomFolders() {
|
||||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
|
if (!mailFeatureState.connectedAccount || !window.daybreakMail?.listFolders) return;
|
||||||
|
const accountId = mailFeatureState.connectedAccount.id;
|
||||||
|
if (mailFeatureState.folderLoad?.accountId === accountId) return mailFeatureState.folderLoad.promise;
|
||||||
|
const request = { accountId };
|
||||||
|
mailFeatureState.folderLoad = request;
|
||||||
|
request.promise = (async () => {
|
||||||
try {
|
try {
|
||||||
mailFeatureState.customFolders = (await window.daybreakMail.listFolders()).folders || [];
|
const result = await window.daybreakMail.listFolders();
|
||||||
|
if (mailFeatureState.folderLoad !== request || mailFeatureState.connectedAccount?.id !== accountId) return;
|
||||||
|
mailFeatureState.customFolders = result.folders || [];
|
||||||
renderCustomFolders();
|
renderCustomFolders();
|
||||||
} catch {}
|
} catch (error) {
|
||||||
|
if (mailFeatureState.folderLoad === request) console.error('Could not load mail folders:', error);
|
||||||
|
} finally {
|
||||||
|
if (mailFeatureState.folderLoad === request) mailFeatureState.folderLoad = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return request.promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
|
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
|
||||||
@@ -183,6 +204,7 @@ async function createMailFolder() {
|
|||||||
if (!name) return;
|
if (!name) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.createFolder(name);
|
const result = await window.daybreakMail.createFolder(name);
|
||||||
|
mailFeatureState.folderLoad = null;
|
||||||
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
|
mailFeatureState.customFolders = result.folders || mailFeatureState.customFolders;
|
||||||
renderCustomFolders();
|
renderCustomFolders();
|
||||||
toastMailUi(`Folder “${result.folder?.name || name}” created`);
|
toastMailUi(`Folder “${result.folder?.name || name}” created`);
|
||||||
@@ -192,6 +214,13 @@ async function createMailFolder() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function updateAccountCard(account) {
|
function updateAccountCard(account) {
|
||||||
|
const accountId = mailFeatureState.connectedAccount?.id || null;
|
||||||
|
if (mailFeatureState.foldersAccountId !== accountId) {
|
||||||
|
mailFeatureState.foldersAccountId = accountId;
|
||||||
|
mailFeatureState.folderLoad = null;
|
||||||
|
mailFeatureState.customFolders = [];
|
||||||
|
renderCustomFolders();
|
||||||
|
}
|
||||||
const card = selectMailUi('#account-settings');
|
const card = selectMailUi('#account-settings');
|
||||||
if (!card) return;
|
if (!card) return;
|
||||||
const email = account.email || '';
|
const email = account.email || '';
|
||||||
@@ -648,29 +677,103 @@ function setupDraftComposer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function syncMailbox(showToast, options = {}) {
|
async function syncMailbox(showToast, options = {}) {
|
||||||
|
const isAndroid = window.daybreakMail?.platform === 'android';
|
||||||
|
const mailboxKey = JSON.stringify([mailFeatureState.connectedAccount?.id, rendererState.activeFolder]);
|
||||||
if (mailFeatureState.syncPromise) {
|
if (mailFeatureState.syncPromise) {
|
||||||
|
if (!isAndroid || mailFeatureState.syncMailboxKey === mailboxKey) {
|
||||||
mailFeatureState.syncQueued = true;
|
mailFeatureState.syncQueued = true;
|
||||||
return mailFeatureState.syncPromise;
|
return mailFeatureState.syncPromise;
|
||||||
}
|
}
|
||||||
|
mailFeatureState.syncQueued = false;
|
||||||
|
}
|
||||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
||||||
openMailAccount();
|
openMailAccount();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const refresh = selectMailUi('#refresh');
|
const refresh = selectMailUi('#refresh');
|
||||||
if (refresh) refresh.disabled = true;
|
if (refresh) refresh.disabled = true;
|
||||||
|
const loadMoreButton = selectMailUi('#load-more');
|
||||||
|
if (loadMoreButton) loadMoreButton.disabled = true;
|
||||||
|
if (!options.append) {
|
||||||
|
mailFeatureState.browseRefreshPending = false;
|
||||||
|
mailFeatureState.browseRefreshFromStart = false;
|
||||||
|
} else {
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Loading more messages…';
|
||||||
|
}
|
||||||
|
const request = {};
|
||||||
|
mailFeatureState.syncRequest = request;
|
||||||
|
mailFeatureState.syncMailboxKey = mailboxKey;
|
||||||
|
let syncSucceeded = false;
|
||||||
const sync = (async () => {
|
const sync = (async () => {
|
||||||
|
let showingCachedMessages = false;
|
||||||
try {
|
try {
|
||||||
|
if (isAndroid && mailFeatureState.displayedMailboxKey !== mailboxKey) {
|
||||||
|
mailFeatureState.displayedMailboxKey = mailboxKey;
|
||||||
|
mailFeatureState.nextOffset = 0;
|
||||||
|
mailFeatureState.total = 0;
|
||||||
|
mailFeatureState.autoLoadBlocked = false;
|
||||||
|
rendererState.messages.splice(0, rendererState.messages.length);
|
||||||
|
rendererState.activeMessage = null;
|
||||||
|
rendererState.selectedIds.clear();
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
||||||
|
appShell.renderList();
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Loading folder…';
|
||||||
|
}
|
||||||
if (rendererState.activeFolder === 'Drafts') {
|
if (rendererState.activeFolder === 'Drafts') {
|
||||||
const result = await window.daybreakMail.listDrafts();
|
const result = await window.daybreakMail.listDrafts();
|
||||||
|
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||||
renderDrafts(result.drafts || []);
|
renderDrafts(result.drafts || []);
|
||||||
|
mailFeatureState.autoLoadBlocked = true;
|
||||||
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
|
if (showToast) toastMailUi(`${result.drafts.length} saved drafts`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const folder = rendererState.activeFolder;
|
||||||
|
const accountId = mailFeatureState.connectedAccount.id;
|
||||||
|
const offset = options.offset ?? (options.append ? mailFeatureState.nextOffset : mailFeatureState.pageOffset);
|
||||||
|
const filters = mailSearchFilters();
|
||||||
|
const isCurrentMailbox = () => rendererState.activeFolder === folder && mailFeatureState.connectedAccount?.id === accountId &&
|
||||||
|
(!isAndroid || mailFeatureState.syncRequest === request);
|
||||||
|
if (window.daybreakMail.getCachedFolder && !options.append && offset === 0 && !rendererState.messages.length) {
|
||||||
|
try {
|
||||||
|
const cached = await window.daybreakMail.getCachedFolder(folder, offset, filters);
|
||||||
|
if (cached && isCurrentMailbox()) {
|
||||||
|
rendererState.messages.splice(0, rendererState.messages.length, ...cached.messages);
|
||||||
|
rendererState.activeMessage = null;
|
||||||
|
mailFeatureState.pageOffset = offset;
|
||||||
|
mailFeatureState.nextOffset = offset + cached.messages.length;
|
||||||
|
mailFeatureState.total = cached.total;
|
||||||
|
mailFeatureState.autoLoadBlocked = true;
|
||||||
|
const pagination = selectMailUi('#pagination');
|
||||||
|
if (pagination) pagination.textContent = cached.total ? `${cached.start}–${cached.end} of ${cached.total} saved messages` : '0 saved messages';
|
||||||
|
const loadMore = selectMailUi('#load-more');
|
||||||
|
if (loadMore) loadMore.classList.toggle('hidden', cached.messages.length >= cached.total);
|
||||||
|
appShell.renderList();
|
||||||
|
showingCachedMessages = true;
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Showing saved messages — syncing';
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||||
|
console.error('Could not load cached messages:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isCurrentMailbox()) return;
|
||||||
|
const result = await window.daybreakMail.syncFolder(folder, offset, filters);
|
||||||
|
if (!isCurrentMailbox()) return;
|
||||||
const previouslyActiveMessage = rendererState.activeMessage;
|
const previouslyActiveMessage = rendererState.activeMessage;
|
||||||
const offset = options.offset ?? (options.append ? mailFeatureState.pageOffset + rendererState.messages.length : mailFeatureState.pageOffset);
|
if (options.append) {
|
||||||
const result = await window.daybreakMail.syncFolder(rendererState.activeFolder, offset, mailSearchFilters());
|
const existing = new Set(rendererState.messages.map(message => JSON.stringify([message.sourceFolder || folder, message.uid || message.id])));
|
||||||
if (options.append) rendererState.messages.push(...result.messages);
|
for (const message of result.messages) {
|
||||||
else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
const key = JSON.stringify([message.sourceFolder || folder, message.uid || message.id]);
|
||||||
|
if (!existing.has(key)) {
|
||||||
|
rendererState.messages.push(message);
|
||||||
|
existing.add(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else rendererState.messages.splice(0, rendererState.messages.length, ...result.messages);
|
||||||
rendererState.messages.forEach(message => {
|
rendererState.messages.forEach(message => {
|
||||||
try {
|
try {
|
||||||
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
const localTags = JSON.parse(localStorage.getItem(`daybreak-message-labels-${message.id}`) || '[]');
|
||||||
@@ -679,33 +782,61 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
});
|
});
|
||||||
if (!options.append) mailFeatureState.pageOffset = offset;
|
if (!options.append) mailFeatureState.pageOffset = offset;
|
||||||
mailFeatureState.total = result.total;
|
mailFeatureState.total = result.total;
|
||||||
|
const hasSearch = Boolean(filters.query || filters.sender || filters.subject || filters.after || filters.before || filters.hasAttachments);
|
||||||
|
const isSequencePage = !result.offline && folder !== 'Snoozed' && !hasSearch;
|
||||||
|
const consumed = isSequencePage && result.start > 0 && result.end >= result.start
|
||||||
|
? result.end - result.start + 1
|
||||||
|
: result.messages.length;
|
||||||
|
mailFeatureState.nextOffset = offset + consumed;
|
||||||
|
mailFeatureState.autoLoadBlocked = consumed === 0 || (options.append && result.messages.length === 0);
|
||||||
|
syncSucceeded = true;
|
||||||
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
|
rendererState.activeMessage = rendererState.messages.some(message => message.id === previouslyActiveMessage)
|
||||||
? previouslyActiveMessage
|
? previouslyActiveMessage
|
||||||
: rendererState.messages[0]?.id;
|
: window.daybreakMail.platform === 'android' ? null : rendererState.messages[0]?.id;
|
||||||
rendererState.selectedIds.clear();
|
rendererState.selectedIds.clear();
|
||||||
const unread = rendererState.messages.filter(message => message.unread).length;
|
const unread = rendererState.messages.filter(message => message.unread).length;
|
||||||
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
|
const inboxCount = selectMailUi('.folder[data-folder="Inbox"] .count');
|
||||||
if (inboxCount) inboxCount.textContent = String(unread);
|
if (inboxCount) inboxCount.textContent = String(unread);
|
||||||
const pagination = selectMailUi('#pagination');
|
const pagination = selectMailUi('#pagination');
|
||||||
if (pagination) pagination.textContent = result.total ? `${options.append ? 1 : result.start}–${options.append ? Math.min(offset + result.messages.length, result.total) : result.end} of ${result.total}` : '0 messages';
|
if (pagination) pagination.textContent = result.total ? `${options.append ? mailFeatureState.pageOffset + 1 : result.start}–${options.append ? Math.min(mailFeatureState.nextOffset, result.total) : result.end} of ${result.total}` : '0 messages';
|
||||||
const loadMore = selectMailUi('#load-more');
|
const loadMore = selectMailUi('#load-more');
|
||||||
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.pageOffset + rendererState.messages.length >= result.total);
|
if (loadMore) loadMore.classList.toggle('hidden', mailFeatureState.nextOffset >= result.total || consumed === 0);
|
||||||
rendererState.query = '';
|
rendererState.query = '';
|
||||||
|
const messageList = selectMailUi('#message-list');
|
||||||
|
const scrollTop = options.append ? messageList.scrollTop : 0;
|
||||||
appShell.renderList();
|
appShell.renderList();
|
||||||
|
if (options.append) messageList.scrollTop = scrollTop;
|
||||||
if (rendererState.activeMessage) {
|
if (rendererState.activeMessage) {
|
||||||
appShell.openMessage(rendererState.activeMessage);
|
appShell.openMessage(rendererState.activeMessage);
|
||||||
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
|
const current = rendererState.messages.find(message => message.id === rendererState.activeMessage);
|
||||||
if (current?.uid) window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
if (current?.uid && window.daybreakMail.platform !== 'android') window.daybreakMail.updateMessage({ uid: current.uid, folder: current.sourceFolder || rendererState.activeFolder, action: 'unread', enabled: false }).catch(() => {});
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
||||||
}
|
}
|
||||||
else selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
|
||||||
updateAccountCard(mailFeatureState.connectedAccount);
|
updateAccountCard(mailFeatureState.connectedAccount);
|
||||||
const status = selectMailUi('#mail-status');
|
const status = selectMailUi('#mail-status');
|
||||||
if (status) status.textContent = result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
|
if (status) status.textContent = mailFeatureState.browseRefreshPending
|
||||||
|
? 'Updates paused while browsing — return to the top or refresh'
|
||||||
|
: result.offline ? 'Offline — showing saved messages' : 'All caught up with your mail';
|
||||||
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
|
if (showToast) toastMailUi(`Synced ${rendererState.messages.length} messages`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (isAndroid && mailFeatureState.syncRequest !== request) return;
|
||||||
|
if (options.append) mailFeatureState.autoLoadBlocked = true;
|
||||||
|
if (showingCachedMessages) {
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Could not sync — showing saved messages';
|
||||||
|
} else if (options.append) {
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status) status.textContent = 'Could not load more messages — use Load more to retry';
|
||||||
|
}
|
||||||
toastMailUi(error.message || 'Could not sync the inbox');
|
toastMailUi(error.message || 'Could not sync the inbox');
|
||||||
} finally {
|
} finally {
|
||||||
|
if (!isAndroid || mailFeatureState.syncRequest === request) {
|
||||||
if (refresh) refresh.disabled = false;
|
if (refresh) refresh.disabled = false;
|
||||||
|
if (loadMoreButton) loadMoreButton.disabled = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
})();
|
})();
|
||||||
@@ -713,14 +844,68 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
try {
|
try {
|
||||||
await sync;
|
await sync;
|
||||||
} finally {
|
} finally {
|
||||||
|
if (mailFeatureState.syncPromise !== sync) return;
|
||||||
mailFeatureState.syncPromise = null;
|
mailFeatureState.syncPromise = null;
|
||||||
|
mailFeatureState.syncMailboxKey = null;
|
||||||
if (mailFeatureState.syncQueued) {
|
if (mailFeatureState.syncQueued) {
|
||||||
mailFeatureState.syncQueued = false;
|
mailFeatureState.syncQueued = false;
|
||||||
void syncMailbox(false);
|
void syncMailbox(false);
|
||||||
|
} else if (runDeferredMailboxRefresh()) {
|
||||||
|
return;
|
||||||
|
} else if (syncSucceeded) {
|
||||||
|
maybeLoadMoreMessages();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function shouldDeferMailboxRefresh() {
|
||||||
|
if (window.daybreakMail?.platform !== 'android') return false;
|
||||||
|
const list = selectMailUi('#message-list');
|
||||||
|
return Boolean(list && (list.scrollTop > 120 ||
|
||||||
|
(document.body.classList.contains('reader-open') &&
|
||||||
|
(appShell.getReaderListPosition() > 120 ||
|
||||||
|
mailFeatureState.nextOffset > mailFeatureState.pageOffset + 20))));
|
||||||
|
}
|
||||||
|
|
||||||
|
function requestBackgroundMailboxRefresh(options = {}) {
|
||||||
|
if (shouldDeferMailboxRefresh()) {
|
||||||
|
mailFeatureState.browseRefreshPending = true;
|
||||||
|
if (options.offset === 0) mailFeatureState.browseRefreshFromStart = true;
|
||||||
|
const status = selectMailUi('#mail-status');
|
||||||
|
if (status && !mailFeatureState.syncPromise) {
|
||||||
|
status.textContent = 'Updates paused while browsing — return to the top or refresh';
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void syncMailbox(false, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
function runDeferredMailboxRefresh() {
|
||||||
|
if (!mailFeatureState.browseRefreshPending || mailFeatureState.syncPromise ||
|
||||||
|
document.visibilityState !== 'visible' || rendererState.activeView !== 'mail' ||
|
||||||
|
shouldDeferMailboxRefresh()) return false;
|
||||||
|
const options = mailFeatureState.browseRefreshFromStart ? { offset: 0 } : {};
|
||||||
|
mailFeatureState.browseRefreshPending = false;
|
||||||
|
mailFeatureState.browseRefreshFromStart = false;
|
||||||
|
void syncMailbox(false, options);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMessageListScroll() {
|
||||||
|
if (!runDeferredMailboxRefresh()) maybeLoadMoreMessages();
|
||||||
|
}
|
||||||
|
|
||||||
|
function maybeLoadMoreMessages() {
|
||||||
|
const list = selectMailUi('#message-list');
|
||||||
|
if (!list || !mailFeatureState.connectedAccount || mailFeatureState.syncPromise ||
|
||||||
|
mailFeatureState.autoLoadBlocked || rendererState.activeFolder === 'Drafts' ||
|
||||||
|
mailFeatureState.nextOffset >= mailFeatureState.total || !list.clientHeight ||
|
||||||
|
document.body.classList.contains('reader-open') ||
|
||||||
|
rendererState.activeView !== 'mail') return;
|
||||||
|
if (list.scrollHeight - list.scrollTop - list.clientHeight > 120) return;
|
||||||
|
void syncMailbox(false, { append: true });
|
||||||
|
}
|
||||||
|
|
||||||
if (window.daybreakMail) {
|
if (window.daybreakMail) {
|
||||||
setupDraftComposer();
|
setupDraftComposer();
|
||||||
let searchTimer;
|
let searchTimer;
|
||||||
@@ -777,7 +962,7 @@ if (window.daybreakMail) {
|
|||||||
}
|
}
|
||||||
if (update.newCount || (update.foldersChanged || []).length) {
|
if (update.newCount || (update.foldersChanged || []).length) {
|
||||||
if (document.visibilityState === 'visible') {
|
if (document.visibilityState === 'visible') {
|
||||||
syncMailbox(false, update.newCount ? { offset: 0 } : {});
|
requestBackgroundMailboxRefresh(update.newCount ? { offset: 0 } : {});
|
||||||
}
|
}
|
||||||
else mailFeatureState.refreshPending = true;
|
else mailFeatureState.refreshPending = true;
|
||||||
}
|
}
|
||||||
@@ -785,18 +970,20 @@ if (window.daybreakMail) {
|
|||||||
document.addEventListener('visibilitychange', () => {
|
document.addEventListener('visibilitychange', () => {
|
||||||
if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
|
if (document.visibilityState === 'visible' && mailFeatureState.refreshPending) {
|
||||||
mailFeatureState.refreshPending = false;
|
mailFeatureState.refreshPending = false;
|
||||||
syncMailbox(false, { offset: 0 });
|
requestBackgroundMailboxRefresh({ offset: 0 });
|
||||||
|
} else if (document.visibilityState === 'visible') {
|
||||||
|
runDeferredMailboxRefresh();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
window.addEventListener('focus', () => {
|
window.addEventListener('focus', () => {
|
||||||
if (mailFeatureState.connectedAccount) syncMailbox(false);
|
if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh();
|
||||||
});
|
});
|
||||||
window.addEventListener('online', () => {
|
window.addEventListener('online', () => {
|
||||||
if (mailFeatureState.connectedAccount) syncMailbox(false, { offset: 0 });
|
if (mailFeatureState.connectedAccount) requestBackgroundMailboxRefresh({ offset: 0 });
|
||||||
});
|
});
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
|
if (mailFeatureState.connectedAccount && document.visibilityState === 'visible' && rendererState.activeView === 'mail') {
|
||||||
syncMailbox(false);
|
requestBackgroundMailboxRefresh();
|
||||||
}
|
}
|
||||||
}, 60 * 1000);
|
}, 60 * 1000);
|
||||||
selectMailUi('#account-settings').addEventListener('click', openMailAccount);
|
selectMailUi('#account-settings').addEventListener('click', openMailAccount);
|
||||||
@@ -825,7 +1012,13 @@ if (window.daybreakMail) {
|
|||||||
mailFeatureState.pageOffset += 20;
|
mailFeatureState.pageOffset += 20;
|
||||||
syncMailbox(false, { offset: mailFeatureState.pageOffset });
|
syncMailbox(false, { offset: mailFeatureState.pageOffset });
|
||||||
};
|
};
|
||||||
selectMailUi('#load-more').onclick = () => syncMailbox(false, { append: true });
|
selectMailUi('#load-more').onclick = () => {
|
||||||
|
if (!mailFeatureState.syncPromise) void syncMailbox(false, { append: true });
|
||||||
|
};
|
||||||
|
selectMailUi('#message-list').addEventListener('scroll', handleMessageListScroll, { passive: true });
|
||||||
|
document.addEventListener('click', event => {
|
||||||
|
if (event.target.closest('#reader-back')) runDeferredMailboxRefresh();
|
||||||
|
});
|
||||||
document.addEventListener('click', async event => {
|
document.addEventListener('click', async event => {
|
||||||
const sendButton = event.target.closest('#send');
|
const sendButton = event.target.closest('#send');
|
||||||
if (!sendButton || !mailFeatureState.connectedAccount) return;
|
if (!sendButton || !mailFeatureState.connectedAccount) return;
|
||||||
|
|||||||
+9
-4
@@ -110,9 +110,14 @@ async function pgpUnlockMessage(message, interactive) {
|
|||||||
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
|
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
|
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') {
|
||||||
if (!interactive) { pgpRenderReaderState(message); return; }
|
if (!interactive) { pgpRenderReaderState(message); return; }
|
||||||
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
const prompt = result.code === 'BAD_PASSPHRASE'
|
||||||
|
? 'That passphrase was incorrect. Try again.'
|
||||||
|
: result.code === 'BIOMETRIC_INVALIDATED'
|
||||||
|
? `${result.message} Enter the passphrase to continue.`
|
||||||
|
: `Enter the passphrase for ${result.email || 'your key'}.`;
|
||||||
|
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
|
||||||
if (passphrase === null) return;
|
if (passphrase === null) return;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -179,7 +184,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
|||||||
if (!selectPgpMailUi('#pgp-hint')) return;
|
if (!selectPgpMailUi('#pgp-hint')) return;
|
||||||
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
||||||
else {
|
else {
|
||||||
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
hint.textContent = status.recipients.some(item => item.trust !== 'verified') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
||||||
if (!touched && !encrypt.checked) encrypt.checked = true;
|
if (!touched && !encrypt.checked) encrypt.checked = true;
|
||||||
}
|
}
|
||||||
} catch { hint.textContent = ''; }
|
} catch { hint.textContent = ''; }
|
||||||
@@ -216,7 +221,7 @@ async function prepareSend(to, cc) {
|
|||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
if (sign) {
|
if (sign) {
|
||||||
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
|
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
|
||||||
if (!status.signer.unlocked) {
|
if (!status.signer.unlocked && !status.signer.biometricUnlockEnabled) {
|
||||||
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
||||||
if (passphrase === null) return false;
|
if (passphrase === null) return false;
|
||||||
}
|
}
|
||||||
|
|||||||
+37
-1
@@ -35,7 +35,7 @@ function openEncryptionKeys() {
|
|||||||
<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">
|
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>
|
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Optional biometric unlock stores the passphrase in a Keystore key requiring user authentication. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
||||||
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
||||||
<h3 class="pgp-heading">Change a key passphrase</h3>
|
<h3 class="pgp-heading">Change a key passphrase</h3>
|
||||||
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
|
||||||
@@ -138,6 +138,42 @@ function openEncryptionKeys() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
row.append(changePassphrase);
|
row.append(changePassphrase);
|
||||||
|
if (androidPgp) {
|
||||||
|
const biometric = document.createElement('button');
|
||||||
|
biometric.className = 'discard';
|
||||||
|
biometric.textContent = 'Checking biometric unlock…';
|
||||||
|
biometric.disabled = true;
|
||||||
|
row.append(biometric);
|
||||||
|
window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => {
|
||||||
|
if (!biometric.isConnected) return;
|
||||||
|
biometric.dataset.enabled = String(enabled);
|
||||||
|
biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…';
|
||||||
|
biometric.disabled = false;
|
||||||
|
}).catch(error => {
|
||||||
|
if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.');
|
||||||
|
});
|
||||||
|
biometric.onclick = async () => {
|
||||||
|
biometric.disabled = true;
|
||||||
|
try {
|
||||||
|
if (biometric.dataset.enabled === 'true') {
|
||||||
|
if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return;
|
||||||
|
await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint);
|
||||||
|
status('Biometric unlock disabled.');
|
||||||
|
} else {
|
||||||
|
const passphrase = needPassphrase();
|
||||||
|
if (!passphrase) return;
|
||||||
|
await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase });
|
||||||
|
passphraseField().value = '';
|
||||||
|
status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.');
|
||||||
|
}
|
||||||
|
await render();
|
||||||
|
} catch (error) {
|
||||||
|
status(error.message || 'Could not update biometric key unlock.');
|
||||||
|
} finally {
|
||||||
|
biometric.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||||
actions.push(['Delete', async () => {
|
actions.push(['Delete', async () => {
|
||||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||||
|
|||||||
+61
-4
@@ -10113,7 +10113,7 @@ ${parts.join("")}`;
|
|||||||
}
|
}
|
||||||
return results;
|
return results;
|
||||||
}
|
}
|
||||||
function createAndroidPgp({ EpMail: EpMail2, getAccount }) {
|
function createAndroidPgp({ EpMail: EpMail2, getAccount, confirm = globalThis.confirm }) {
|
||||||
let storePromise;
|
let storePromise;
|
||||||
const passphrases = /* @__PURE__ */ new Map();
|
const passphrases = /* @__PURE__ */ new Map();
|
||||||
let cacheMinutes = 10;
|
let cacheMinutes = 10;
|
||||||
@@ -10240,20 +10240,30 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
|
|||||||
async function unlock(fingerprint, passphrase) {
|
async function unlock(fingerprint, passphrase) {
|
||||||
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
|
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
|
||||||
if (!entry) throw new Error("That key was not found.");
|
if (!entry) throw new Error("That key was not found.");
|
||||||
|
const secret = passphrase || await biometricPassphrase(fingerprint);
|
||||||
|
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email || "your key"}.`), { code: "PASSPHRASE_REQUIRED" });
|
||||||
|
return unlockWithPassphrase(entry, secret);
|
||||||
|
}
|
||||||
|
async function unlockWithPassphrase(entry, passphrase) {
|
||||||
try {
|
try {
|
||||||
return await po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase });
|
return await po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase });
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error("The passphrase is incorrect.");
|
throw new Error("The passphrase is incorrect.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
async function biometricPassphrase(fingerprint) {
|
||||||
|
if (typeof EpMail2.getPgpBiometricPassphrase !== "function") return null;
|
||||||
|
const result = await EpMail2.getPgpBiometricPassphrase({ fingerprint });
|
||||||
|
return result?.enabled && typeof result.passphrase === "string" ? result.passphrase : null;
|
||||||
|
}
|
||||||
async function signerFor(account, passphrase) {
|
async function signerFor(account, passphrase) {
|
||||||
const data = await store();
|
const data = await store();
|
||||||
const entry = data.keys.find((item) => item.email.toLowerCase() === String(account.email).toLowerCase());
|
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" });
|
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);
|
const secret = passphrase || cached(entry.fingerprint) || await biometricPassphrase(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 });
|
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 {
|
try {
|
||||||
const key = await unlock(entry.fingerprint, secret);
|
const key = await unlockWithPassphrase(entry, secret);
|
||||||
cache(entry.fingerprint, secret);
|
cache(entry.fingerprint, secret);
|
||||||
return { key, entry };
|
return { key, entry };
|
||||||
} catch {
|
} catch {
|
||||||
@@ -10277,6 +10287,21 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
|
|||||||
if (pgp.encrypt && recipientKeys.missing.length) {
|
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 });
|
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(", ")}.`), { code: "NO_RECIPIENT_KEY", missing: recipientKeys.missing });
|
||||||
}
|
}
|
||||||
|
const unverifiedKeys = recipientKeys.keys.filter((item) => item.trust !== "verified");
|
||||||
|
if (pgp.encrypt && unverifiedKeys.length) {
|
||||||
|
const details = unverifiedKeys.map(
|
||||||
|
(item) => `${item.address}
|
||||||
|
${item.fingerprint.match(/.{1,4}/g).join(" ")} (${item.trust})`
|
||||||
|
).join("\n\n");
|
||||||
|
const warning = `These recipient keys have not been verified by fingerprint:
|
||||||
|
|
||||||
|
${details}
|
||||||
|
|
||||||
|
If a key is incorrect, its owner may be able to read this message. Compare each fingerprint with its owner through another channel before sending. Send encrypted mail to these unverified keys anyway?`;
|
||||||
|
if (typeof confirm !== "function" || !confirm(warning)) {
|
||||||
|
throw Object.assign(new Error("Sending to unverified recipient keys was cancelled."), { code: "UNVERIFIED_RECIPIENT_KEY" });
|
||||||
|
}
|
||||||
|
}
|
||||||
let inner = mimeInner(`${String(message.text || "").slice(0, 5e5)}${account.signature ? `
|
let inner = mimeInner(`${String(message.text || "").slice(0, 5e5)}${account.signature ? `
|
||||||
|
|
||||||
${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
|
${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
|
||||||
@@ -10364,6 +10389,7 @@ ${body}`);
|
|||||||
selected = candidates.find((entry) => cached(entry.fingerprint)) || selected;
|
selected = candidates.find((entry) => cached(entry.fingerprint)) || selected;
|
||||||
secret = cached(selected.fingerprint);
|
secret = cached(selected.fingerprint);
|
||||||
}
|
}
|
||||||
|
if (!secret) secret = await biometricPassphrase(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." };
|
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;
|
let privateKey;
|
||||||
try {
|
try {
|
||||||
@@ -10536,6 +10562,23 @@ ${body}`);
|
|||||||
clear(fingerprint);
|
clear(fingerprint);
|
||||||
return { removed: true };
|
return { removed: true };
|
||||||
},
|
},
|
||||||
|
async enableBiometricUnlock({ fingerprint, passphrase }) {
|
||||||
|
if (typeof EpMail2.setPgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
|
||||||
|
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
|
||||||
|
if (!entry) throw new Error("That key was not found.");
|
||||||
|
if (!passphrase) throw new Error("Enter the key passphrase first.");
|
||||||
|
await unlockWithPassphrase(entry, passphrase);
|
||||||
|
return EpMail2.setPgpBiometricUnlock({ fingerprint, passphrase });
|
||||||
|
},
|
||||||
|
async biometricUnlockEnabled(fingerprint) {
|
||||||
|
if (typeof EpMail2.pgpBiometricUnlockEnabled !== "function") return false;
|
||||||
|
return Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled);
|
||||||
|
},
|
||||||
|
async disableBiometricUnlock(fingerprint) {
|
||||||
|
if (typeof EpMail2.removePgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
|
||||||
|
clear(fingerprint);
|
||||||
|
return EpMail2.removePgpBiometricUnlock({ fingerprint });
|
||||||
|
},
|
||||||
async contacts() {
|
async contacts() {
|
||||||
return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt }));
|
return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt }));
|
||||||
},
|
},
|
||||||
@@ -10575,10 +10618,20 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
|
|||||||
const { keys, missing } = await resolveRecipients(addresses);
|
const { keys, missing } = await resolveRecipients(addresses);
|
||||||
const account = await getAccount();
|
const account = await getAccount();
|
||||||
const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null;
|
const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null;
|
||||||
|
let biometricUnlockEnabled = false;
|
||||||
|
if (entry && typeof EpMail2.pgpBiometricUnlockEnabled === "function") {
|
||||||
|
biometricUnlockEnabled = Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled);
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
recipients: keys.map((item) => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
|
recipients: keys.map((item) => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
|
||||||
missing,
|
missing,
|
||||||
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null
|
signer: entry ? {
|
||||||
|
fingerprint: entry.fingerprint,
|
||||||
|
email: entry.email,
|
||||||
|
name: entry.name,
|
||||||
|
unlocked: Boolean(cached(entry.fingerprint)),
|
||||||
|
biometricUnlockEnabled
|
||||||
|
} : null
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
decryptMessage,
|
decryptMessage,
|
||||||
@@ -10632,11 +10685,14 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
|
|||||||
var EpMail = registerPlugin("EpMail");
|
var EpMail = registerPlugin("EpMail");
|
||||||
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
|
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === "android") {
|
||||||
const daybreakMail = {
|
const daybreakMail = {
|
||||||
|
platform: "android",
|
||||||
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
|
getAppVersion: () => EpMail.getAppVersion().then((result) => result.version),
|
||||||
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
|
getNotificationPrivacy: () => EpMail.getNotificationPrivacy(),
|
||||||
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
|
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
|
||||||
getAppLockSettings: () => EpMail.getAppLockSettings(),
|
getAppLockSettings: () => EpMail.getAppLockSettings(),
|
||||||
setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }),
|
setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }),
|
||||||
|
setAppLockDelay: (seconds) => EpMail.setAppLockDelay({ seconds }),
|
||||||
|
deleteAllLocalData: () => EpMail.deleteAllLocalData(),
|
||||||
getAccount: () => EpMail.getAccount(),
|
getAccount: () => EpMail.getAccount(),
|
||||||
listAccounts: () => EpMail.listAccounts(),
|
listAccounts: () => EpMail.listAccounts(),
|
||||||
selectAccount: (id) => EpMail.selectAccount({ id }),
|
selectAccount: (id) => EpMail.selectAccount({ id }),
|
||||||
@@ -10644,6 +10700,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
|
|||||||
connect: (details) => EpMail.connect(details),
|
connect: (details) => EpMail.connect(details),
|
||||||
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
updateAccount: (id, details) => EpMail.updateAccount({ id, ...details }),
|
||||||
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
syncFolder: (folder, offset, filters) => EpMail.syncFolder({ folder, offset, filters }),
|
||||||
|
getCachedFolder: (folder, offset, filters) => EpMail.getCachedFolder({ folder, offset, filters }).then((result) => result.cached),
|
||||||
listFolders: () => EpMail.listFolders(),
|
listFolders: () => EpMail.listFolders(),
|
||||||
createFolder: (name) => EpMail.createFolder({ name }),
|
createFolder: (name) => EpMail.createFolder({ name }),
|
||||||
listDrafts: () => EpMail.listDrafts(),
|
listDrafts: () => EpMail.listDrafts(),
|
||||||
|
|||||||
+8
-5
@@ -33,18 +33,21 @@ async function openPreferences() {
|
|||||||
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('');
|
||||||
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
|
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
|
||||||
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled?window.daybreakMail:null;
|
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled&&window.daybreakMail?.setAppLockDelay?window.daybreakMail:null;
|
||||||
|
const localDataBridge=window.daybreakMail?.deleteAllLocalData?window.daybreakMail:null;
|
||||||
let notificationPrivacy={showDetails:false};
|
let notificationPrivacy={showDetails:false};
|
||||||
let appLockSettings={enabled:false,deviceSecure:false};
|
let appLockSettings={enabled:false,deviceSecure:false,lockDelaySeconds:0};
|
||||||
if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}}
|
if(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}}
|
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 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>`:'';
|
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><label class="compose-line"><span>Lock delay</span><select class="settings-select" id="app-lock-delay"><option value="0"${appLockSettings.lockDelaySeconds===0?' selected':''}>Immediately</option><option value="30"${appLockSettings.lockDelaySeconds===30?' selected':''}>30 seconds</option><option value="60"${appLockSettings.lockDelaySeconds===60?' selected':''}>1 minute</option><option value="300"${appLockSettings.lockDelaySeconds===300?' selected':''}>5 minutes</option></select></label><p class="account-note">Requires a secure Android screen lock. Screenshots are hidden as soon as you leave; mail sync continues in the background.</p>`:'';
|
||||||
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 localDataSetting=localDataBridge?`<h3 class="pgp-heading">Local data</h3><p class="account-note">Delete saved accounts, cached mail, drafts, queued sends, OpenPGP keys, app settings, and attachments saved by ep-mail to Downloads.</p><button class="discard" id="delete-all-local-data">Delete all local data…</button>`:'';
|
||||||
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}${localDataSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
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=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('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge){await appLockBridge.setAppLockDelay(Number(selectProductivityUi('#app-lock-delay').value));await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked)}productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}};
|
||||||
|
if(localDataBridge)selectProductivityUi('#delete-all-local-data').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await localDataBridge.deleteAllLocalData();if(!result?.deleted){button.disabled=false;return}if('serviceWorker'in navigator){const registrations=await navigator.serviceWorker.getRegistrations();await Promise.all(registrations.map(registration=>registration.unregister()))}if('caches'in window){const names=await caches.keys();await Promise.all(names.map(name=>caches.delete(name)))}localStorage.clear();window.location.reload()}catch(error){button.disabled=false;toastProductivityUi(error.message||'Native data was deleted, but browser data cleanup did not finish. Restart ep-mail to complete cleanup.')}};
|
||||||
selectProductivityUi('#theme-select').focus();
|
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(); }
|
||||||
|
|||||||
+25
-2
@@ -1,5 +1,28 @@
|
|||||||
const CACHE='ep-mail-v19';
|
const CACHE='ep-mail-v22';
|
||||||
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)).then(()=>self.skipWaiting())));
|
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)))).then(()=>self.clients.claim())));
|
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 => {
|
||||||
|
const request = event.request;
|
||||||
|
if (request.method !== 'GET' || new URL(request.url).origin !== location.origin) return;
|
||||||
|
event.respondWith((async () => {
|
||||||
|
let response;
|
||||||
|
try {
|
||||||
|
response = await fetch(request, { cache: 'no-cache' });
|
||||||
|
} catch (error) {
|
||||||
|
const cached = await caches.match(request) ||
|
||||||
|
(request.mode === 'navigate' ? await caches.match('./index.html') : null);
|
||||||
|
if (cached) return cached;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
if (response.ok) {
|
||||||
|
try {
|
||||||
|
const cache = await caches.open(CACHE);
|
||||||
|
await cache.put(request, response.clone());
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Could not update offline app cache:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
})());
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user