Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93ff651e9d | ||
|
|
96c7b6966b | ||
|
|
d0e2ce26bc | ||
|
|
4ec578b072 | ||
|
|
8a798fec6b | ||
|
|
5b8aafe22c | ||
|
|
89c45fcf63 | ||
|
|
d7b6e31518 | ||
|
|
b14209a5ae | ||
|
|
d0b26db9ee | ||
|
|
78989f7b56 | ||
|
|
5f456e64d0 | ||
|
|
526ca767b1 | ||
|
|
3ada3c2ce8 | ||
|
|
9b0009faef |
@@ -0,0 +1 @@
|
|||||||
|
scripts/build-linux-wsl.sh text eol=lf
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"java.configuration.updateBuildConfiguration": "interactive"
|
||||||
|
}
|
||||||
+24
-22
@@ -6,19 +6,19 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU
|
|||||||
|
|
||||||
## Implementation progress (2026-11-03)
|
## Implementation progress (2026-11-03)
|
||||||
|
|
||||||
- **Phase 0 — Baseline:** Mostly implemented; release verification remains open.
|
- **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 and the basic native app lock are implemented; vault lifecycle, deletion, and lock-recovery assurance 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, and on-demand PGP/MIME or inline-encrypted-message decryption. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**.
|
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, and Android OpenPGP trust/plaintext policy decisions have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock and unlock. 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`. Phone and landscape layouts were checked for horizontal overflow. Current validation: 152 passing Node tests, 18 Android unit tests, and a successful Android debug build. 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; automated native confirmation and bypass tests; 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
|
||||||
|
|
||||||
@@ -39,42 +39,44 @@ These are implementation observations, not proof that all paths are safe. In par
|
|||||||
|
|
||||||
### Phase 0 — Android security baseline and release gate (P0)
|
### Phase 0 — Android security baseline and release gate (P0)
|
||||||
|
|
||||||
- [ ] Complete and record a checklist for the merged manifest and production APK (permissions, exported components, backup rules, cleartext policy, WebView debugging, file access, and plugin exposure). Backup/data-extraction exclusions, cleartext denial, removal of the wildcard origin, and removal of the unused broad `FileProvider` are implemented; the production-artifact review is not.
|
- [x] Generate and review the V0.5.11 worktree release-variant merged manifest. It uses package `studio.daybreak.mail`, versionCode 511/versionName 0.5.11, minSdk 24/targetSdk 36; `allowBackup=false`, `usesCleartextTraffic=false`, and data-extraction exclusions for root/files/databases/shared preferences/external storage. The release manifest has no `debuggable=true` attribute. `MainActivity` is exported only for the launcher; WorkManager's exported job service is protected by `BIND_JOB_SERVICE`; diagnostics/profile receivers require `DUMP`; other merged components are non-exported. The only declared permissions are network, foreground data sync, notifications, wake lock, network-state/boot support, and a signature-protected dynamic-receiver permission. The unused broad `FileProvider` and wildcard origin are absent. The V0.5.10 published APK itself remains debug-signed; no production-signed artifact has been reviewed.
|
||||||
- [~] Require TLS and hostname validation on IMAP/SMTP and DAV. DAV is restricted to HTTPS and the configured origin; transport TLS modes are implemented and covered by unit tests. Invalid, expired, and mismatched certificate integration tests and a full native-client review remain open.
|
- [~] Review release WebView settings. Web contents debugging now follows `BuildConfig.DEBUG`; file/content access, file-URL cross-access, automatic JavaScript windows, and geolocation are disabled; mixed content is explicitly `NEVER_ALLOW`. The packaged app uses the HTTPS localhost origin. The hardened build compiles and loads the app/Capacitor bridge in the emulator; a full supported-device review remains open.
|
||||||
|
- [~] Require TLS and hostname validation on IMAP/SMTP and DAV. DAV is restricted to HTTPS and the configured origin; transport requires STARTTLS or implicit TLS and verifies host identity. Unit tests check those settings and absence of permissive trust/socket-factory overrides. Invalid, expired, and mismatched certificate integration tests and a full native-client review remain open.
|
||||||
- [~] Review `EpMailPlugin` as an untrusted-input boundary. DAV URLs and attachment names have specific native validation; PGP MIME structure and send confirmations have added native checks. A complete method-by-method bridge review and comprehensive size/state tests remain open.
|
- [~] Review `EpMailPlugin` as an untrusted-input boundary. DAV URLs and attachment names have specific native validation; PGP MIME structure and send confirmations have added native checks. A complete method-by-method bridge review and comprehensive size/state tests remain open.
|
||||||
- [~] Keep signing keys outside the repository, label debug APKs, and require environment-provided credentials for signed builds. No production-signed APK or merged release review has been completed.
|
- [~] Keep signing keys outside the repository, label debug APKs, and require environment-provided credentials for signed builds. No Android release-signing variables are configured here; published Android APKs are clearly labeled debug/test-only, and no production-signed APK has been reviewed.
|
||||||
- [x] Remove/sanitize sensitive native logging; the current mail sync log omits mailbox content and credentials.
|
- [x] Remove/sanitize sensitive native logging; the current mail sync log omits mailbox content and credentials.
|
||||||
|
|
||||||
**Exit criteria:** documented release manifest/config review; TLS validation and downgrade regression tests pass; no sensitive data in logs; release APK is signed and distinguishable from debug output.
|
**Exit criteria:** documented release manifest/config review; TLS validation and downgrade regression tests pass; no sensitive data in logs; release APK is signed and distinguishable from debug output.
|
||||||
|
|
||||||
### Phase 1 — Local data and privacy controls (P0)
|
### Phase 1 — Local data and privacy controls (P0)
|
||||||
|
|
||||||
- [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. Document and test the key's security/fallback behavior, corruption and reinstall handling, and lock-screen/key invalidation; verify no plaintext fallback across 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.
|
||||||
- [~] Account removal exists, but prove deletion covers account caches, queued sends, downloaded files, and related encryption-key lifecycle; document exported files and recovery limits.
|
- [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 and uses the device credential; background sync continues. Delayed lock, task-switcher obscuring, process-recreation/timeout 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.
|
||||||
|
|
||||||
### 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. Independent review and GnuPG/Thunderbird interoperability on Android are 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, and trust. Native prompts now 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, and ciphertext-before-queueing are implemented. Signed-only/clear-signed/inline signature parity, full hostile-input/tampering suite, and Android interoperability remain open.
|
- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open.
|
||||||
- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy-level unit tests cover prompt/no-prompt decisions. Automated dialog-interaction, bypass, stale-key, and queue-policy tests 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.
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E
|
|||||||
## Desktop app
|
## Desktop app
|
||||||
|
|
||||||
The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
|
The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
|
||||||
|
|
||||||
|
On Windows, `npm run build` runs `scripts\build.ps1`, building the Android debug APK and Windows portable executable. For all targets, run `npm run build:all`: it also builds the Windows installer and uses the default WSL distribution to build the Linux AppImage and Debian package. To select a distribution, run `powershell -NoProfile -ExecutionPolicy Bypass -File scripts\build-all.ps1 -WslDistribution Ubuntu`. WSL needs Linux Node.js, npm and tar, plus the usual Electron packaging prerequisites and network access to install the locked dependencies. Linux builds use a temporary Linux filesystem workspace, then copy both packages into `release\`. Both build scripts preserve the legacy `ep-mail <version>.apk` copy of the debug APK; it is **not a signed release APK** and will overwrite a same-named signed APK. Use `npm run android:release-apk` afterwards when a signed release is needed.
|
||||||
|
|
||||||
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
||||||
|
|
||||||
@@ -18,7 +20,7 @@ See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
|
|||||||
|
|
||||||
## Android app
|
## Android app
|
||||||
|
|
||||||
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, encrypted account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Android Settings can enable an app lock that covers the WebView and disables its JavaScript bridge when the app leaves the foreground; unlock requires the device PIN, pattern, or password, while background mail sync continues. Configure a secure Android screen lock before enabling it. This is a local privacy control, not protection against a compromised or rooted device. Android OpenPGP is now present as an **experimental test-only feature** for key and message testing. It has not had an independent cryptography/security review and is not approved for sensitive or production mail; do not rely on it to protect important messages. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, encrypted account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Android Settings can enable an app lock that covers the WebView and disables its JavaScript bridge when the app leaves the foreground; it also hides the locked screen from screenshots and recent-app previews. Unlock requires the device PIN, pattern, or password, while background mail sync continues. Configure a secure Android screen lock before enabling it. This is a local privacy control, not protection against a compromised or rooted device. Android OpenPGP is now present as an **experimental test-only feature** for key and message testing. It has not had an independent cryptography/security review and is not approved for sensitive or production mail; do not rely on it to protect important messages. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
npm install
|
npm install
|
||||||
@@ -26,7 +28,19 @@ 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.
|
||||||
|
|
||||||
|
For Android OpenPGP testing, transfer a passphrase-protected, ASCII-armored private key (`.asc`) securely to the device. In **Settings → Encryption keys**, enter its passphrase, select **Import private key from file…**, and choose the file (maximum 200,000 bytes). The file picker is unavailable while app lock is enabled because leaving the app can reset the import; paste the key instead, or temporarily disable app lock and re-enable it after importing. Compare the imported fingerprint with the original, then remove the transferred file and clear the clipboard if used. Keep a separate secure backup of the key and its revocation certificate.
|
||||||
|
|
||||||
|
Android builds use the Gradle wrapper and Android Gradle Plugin 9.4.0. Capacitor's generated modules are aligned to that plugin version during the build; the legacy Android DSL and external Kotlin plugin remain enabled for compatibility and must be migrated before upgrading to AGP 10.
|
||||||
|
|
||||||
|
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:
|
||||||
|
|||||||
@@ -34,8 +34,10 @@
|
|||||||
- [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption.
|
- [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption.
|
||||||
- [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation.
|
- [x] 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.
|
||||||
- [ ] Android release gate: automated native-dialog interaction and bypass tests, full parity/interoperability tests, independent human cryptography/security review, and signed release review.
|
- [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness.
|
||||||
- [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, signed/inline verification parity, and dependency advisory remediation.
|
- [x] Add optional per-key Android biometric/device-credential passphrase release with passphrase fallback.
|
||||||
|
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review.
|
||||||
|
- [ ] Android follow-up: device-test biometric prompt/key invalidation recovery, full vault lifecycle/recovery, remaining parity/device interoperability, and dependency advisory remediation.
|
||||||
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
- [x] Phase 5 (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.
|
||||||
@@ -48,6 +50,13 @@
|
|||||||
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
|
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
|
||||||
- [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews.
|
- [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews.
|
||||||
- [x] Add an optional native Android app lock using the device credential while leaving background mail sync available.
|
- [x] Add an optional native Android app lock using the device credential while leaving background mail sync available.
|
||||||
|
- [x] Set `FLAG_SECURE` while the optional app lock is engaged to hide the screen from screenshots and recents previews.
|
||||||
|
- [x] Exercise background lock, credential unlock, and screenshot obscuring on an Android emulator.
|
||||||
|
- [x] Disclose in account-removal confirmation that downloaded files and global OpenPGP keys are retained.
|
||||||
|
- [x] Refuse to generate a replacement Keystore key when encrypted vault data already exists; show a fail-closed recovery screen with clear-data guidance.
|
||||||
|
- [ ] Device-test missing/invalidated Keystore keys, corrupted vault data, migration/reinstall behavior, and recovery instructions.
|
||||||
|
- [ ] Define/test full app-data deletion and downloaded-file/OpenPGP-key retention or removal behavior.
|
||||||
|
- [ ] Add app-lock timeout/delay process/lifecycle tests and decide whether to add biometric unlock to the separate app lock (PGP per-key biometric release is implemented experimentally).
|
||||||
|
|
||||||
## Appearance and settings
|
## Appearance and settings
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@ async function openAccountManager(){
|
|||||||
const editButton=event.target.closest('[data-edit-account]');
|
const editButton=event.target.closest('[data-edit-account]');
|
||||||
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
||||||
const removeButton=event.target.closest('[data-remove-account]');
|
const removeButton=event.target.closest('[data-remove-account]');
|
||||||
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?\n\nIts cached mail, drafts and pending sends will be removed. Downloaded attachment files and OpenPGP keys are kept; delete those separately if you want to remove them too.`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
||||||
};
|
};
|
||||||
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-34
@@ -1,39 +1,39 @@
|
|||||||
apply plugin: 'com.android.application'
|
apply plugin: 'com.android.application'
|
||||||
apply plugin: 'org.jetbrains.kotlin.android'
|
apply plugin: 'org.jetbrains.kotlin.android'
|
||||||
|
|
||||||
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
|
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
|
||||||
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
|
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
|
||||||
def releaseStoreFile = System.getenv('EP_MAIL_ANDROID_STORE_FILE')
|
def releaseStoreFile = System.getenv('EP_MAIL_ANDROID_STORE_FILE')
|
||||||
def releaseStorePassword = System.getenv('EP_MAIL_ANDROID_STORE_PASSWORD')
|
def releaseStorePassword = System.getenv('EP_MAIL_ANDROID_STORE_PASSWORD')
|
||||||
def releaseKeyAlias = System.getenv('EP_MAIL_ANDROID_KEY_ALIAS')
|
def releaseKeyAlias = System.getenv('EP_MAIL_ANDROID_KEY_ALIAS')
|
||||||
def releaseKeyPassword = System.getenv('EP_MAIL_ANDROID_KEY_PASSWORD')
|
def releaseKeyPassword = System.getenv('EP_MAIL_ANDROID_KEY_PASSWORD')
|
||||||
def releaseSigningValues = [releaseStoreFile, releaseStorePassword, releaseKeyAlias, releaseKeyPassword]
|
def releaseSigningValues = [releaseStoreFile, releaseStorePassword, releaseKeyAlias, releaseKeyPassword]
|
||||||
def hasAnyReleaseSigningValue = releaseSigningValues.any { it != null && !it.isBlank() }
|
def hasAnyReleaseSigningValue = releaseSigningValues.any { it != null && !it.isBlank() }
|
||||||
def hasCompleteReleaseSigning = releaseSigningValues.every { it != null && !it.isBlank() }
|
def hasCompleteReleaseSigning = releaseSigningValues.every { it != null && !it.isBlank() }
|
||||||
|
|
||||||
if (hasAnyReleaseSigningValue && !hasCompleteReleaseSigning) {
|
if (hasAnyReleaseSigningValue && !hasCompleteReleaseSigning) {
|
||||||
throw new GradleException('Android release signing requires EP_MAIL_ANDROID_STORE_FILE, EP_MAIL_ANDROID_STORE_PASSWORD, EP_MAIL_ANDROID_KEY_ALIAS, and EP_MAIL_ANDROID_KEY_PASSWORD.')
|
throw new GradleException('Android release signing requires EP_MAIL_ANDROID_STORE_FILE, EP_MAIL_ANDROID_STORE_PASSWORD, EP_MAIL_ANDROID_KEY_ALIAS, and EP_MAIL_ANDROID_KEY_PASSWORD.')
|
||||||
}
|
}
|
||||||
if (hasCompleteReleaseSigning && !new File(releaseStoreFile).isAbsolute()) {
|
if (hasCompleteReleaseSigning && !new File(releaseStoreFile).isAbsolute()) {
|
||||||
throw new GradleException('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.')
|
throw new GradleException('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.')
|
||||||
}
|
}
|
||||||
|
|
||||||
android {
|
android {
|
||||||
namespace = "studio.daybreak.mail"
|
namespace = "studio.daybreak.mail"
|
||||||
compileSdk = rootProject.ext.compileSdkVersion
|
compileSdk = rootProject.ext.compileSdkVersion
|
||||||
buildFeatures {
|
buildFeatures {
|
||||||
buildConfig true
|
buildConfig true
|
||||||
}
|
}
|
||||||
if (hasCompleteReleaseSigning) {
|
if (hasCompleteReleaseSigning) {
|
||||||
signingConfigs {
|
signingConfigs {
|
||||||
release {
|
release {
|
||||||
storeFile file(releaseStoreFile)
|
storeFile file(releaseStoreFile)
|
||||||
storePassword releaseStorePassword
|
storePassword releaseStorePassword
|
||||||
keyAlias releaseKeyAlias
|
keyAlias releaseKeyAlias
|
||||||
keyPassword releaseKeyPassword
|
keyPassword releaseKeyPassword
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
packaging {
|
packaging {
|
||||||
resources {
|
resources {
|
||||||
pickFirsts += "META-INF/NOTICE.md"
|
pickFirsts += "META-INF/NOTICE.md"
|
||||||
@@ -54,11 +54,11 @@ 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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
compileOptions {
|
compileOptions {
|
||||||
sourceCompatibility JavaVersion.VERSION_21
|
sourceCompatibility JavaVersion.VERSION_21
|
||||||
@@ -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'
|
||||||
|
|||||||
@@ -25,7 +25,6 @@ internal object AndroidAccountVault {
|
|||||||
|
|
||||||
fun initialize(context: Context) {
|
fun initialize(context: Context) {
|
||||||
appContext = context.applicationContext
|
appContext = context.applicationContext
|
||||||
secretKey()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
@@ -56,80 +55,137 @@ internal object AndroidAccountVault {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray()
|
fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray()
|
||||||
|
|
||||||
fun notificationDetailsEnabled(): Boolean =
|
fun notificationDetailsEnabled(): Boolean =
|
||||||
read().optBoolean("showNotificationDetails", NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS)
|
read().optBoolean("showNotificationDetails", NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS)
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun setNotificationDetailsEnabled(enabled: Boolean): Boolean {
|
fun setNotificationDetailsEnabled(enabled: Boolean): Boolean {
|
||||||
val store = read().put("showNotificationDetails", enabled)
|
val store = read().put("showNotificationDetails", enabled)
|
||||||
write(store)
|
write(store)
|
||||||
return enabled
|
return enabled
|
||||||
}
|
}
|
||||||
|
|
||||||
fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false)
|
fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false)
|
||||||
|
|
||||||
@Synchronized
|
fun appLockDelaySeconds(): Int = read().optInt("appLockDelaySeconds", 0)
|
||||||
fun setAppLockEnabled(enabled: Boolean): Boolean {
|
|
||||||
val store = read().put("appLockEnabled", enabled)
|
@Synchronized
|
||||||
write(store)
|
fun setAppLockEnabled(enabled: Boolean): Boolean {
|
||||||
return enabled
|
val store = read().put("appLockEnabled", enabled)
|
||||||
}
|
write(store)
|
||||||
|
return enabled
|
||||||
fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) }
|
}
|
||||||
?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject())
|
|
||||||
|
@Synchronized
|
||||||
@Synchronized
|
fun setAppLockDelaySeconds(seconds: Int): Int {
|
||||||
fun savePgpStore(candidate: JSONObject) {
|
AndroidAppLockPolicy.requireValidDelay(seconds)
|
||||||
validatePgpStore(candidate)
|
val store = read().put("appLockDelaySeconds", seconds)
|
||||||
val store = read().put("pgpStore", JSONObject(candidate.toString()))
|
write(store)
|
||||||
write(store)
|
return seconds
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun validatePgpStore(candidate: JSONObject) {
|
fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) }
|
||||||
require(candidate.toString().length <= 3_000_000) { "The OpenPGP key store is too large." }
|
?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject())
|
||||||
require(!hasPassphraseField(candidate)) { "Passphrases must never be stored." }
|
|
||||||
val keys = candidate.optJSONArray("keys") ?: JSONArray()
|
@Synchronized
|
||||||
val contacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
fun savePgpStore(candidate: JSONObject) {
|
||||||
require(keys.length() <= 20 && contacts.length() <= 500) { "The OpenPGP key store has too many entries." }
|
validatePgpStore(candidate)
|
||||||
val fingerprint = Regex("^[0-9A-Fa-f]{40,64}$")
|
val store = read()
|
||||||
for (index in 0 until keys.length()) {
|
val previousKeys = store.optJSONObject("pgpStore")?.optJSONArray("keys") ?: JSONArray()
|
||||||
val entry = keys.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP key entry is invalid.")
|
val nextFingerprints = (0 until (candidate.optJSONArray("keys")?.length() ?: 0))
|
||||||
val privateKey = entry.optString("privateKey")
|
.mapNotNull { candidate.optJSONArray("keys")?.optJSONObject(it)?.optString("fingerprint") }
|
||||||
val publicKey = entry.optString("publicKey")
|
.map { it.uppercase(Locale.ROOT) }
|
||||||
require(fingerprint.matches(entry.optString("fingerprint")) &&
|
.toSet()
|
||||||
privateKey.length in 1..200_000 && privateKey.contains("BEGIN PGP PRIVATE KEY BLOCK") &&
|
val removedFingerprints = (0 until previousKeys.length())
|
||||||
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK")) {
|
.mapNotNull { previousKeys.optJSONObject(it)?.optString("fingerprint") }
|
||||||
"An OpenPGP key entry is invalid."
|
.filter { it.uppercase(Locale.ROOT) !in nextFingerprints }
|
||||||
}
|
val biometricUnlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject()
|
||||||
}
|
removedFingerprints.forEach { biometricUnlocks.remove(it.uppercase(Locale.ROOT)) }
|
||||||
for (index in 0 until contacts.length()) {
|
store.put("pgpBiometricUnlocks", biometricUnlocks)
|
||||||
val entry = contacts.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP contact entry is invalid.")
|
store.put("pgpStore", JSONObject(candidate.toString()))
|
||||||
val publicKey = entry.optString("publicKey")
|
write(store)
|
||||||
require(fingerprint.matches(entry.optString("fingerprint")) &&
|
removedFingerprints.forEach(AndroidPgpBiometricUnlock::deleteKey)
|
||||||
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK") &&
|
}
|
||||||
!publicKey.contains("BEGIN PGP PRIVATE KEY BLOCK")) {
|
|
||||||
"An OpenPGP contact entry is invalid."
|
@Synchronized
|
||||||
}
|
fun pgpBiometricUnlock(fingerprint: String): String? =
|
||||||
require(entry.optString("trust") in setOf("unknown", "trusted", "verified")) {
|
read().optJSONObject("pgpBiometricUnlocks")?.optString(fingerprint.uppercase(Locale.ROOT))
|
||||||
"An OpenPGP contact trust value is invalid."
|
?.takeIf(String::isNotBlank)
|
||||||
}
|
|
||||||
}
|
fun hasPgpBiometricUnlock(fingerprint: String): Boolean =
|
||||||
}
|
pgpBiometricUnlock(fingerprint) != null
|
||||||
|
|
||||||
private fun hasPassphraseField(value: Any?): Boolean = when (value) {
|
@Synchronized
|
||||||
is JSONObject -> {
|
fun setPgpBiometricUnlock(fingerprint: String, ciphertext: String?) {
|
||||||
val keys = value.keys()
|
require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) {
|
||||||
var found = false
|
"The OpenPGP fingerprint is invalid."
|
||||||
while (keys.hasNext() && !found) {
|
}
|
||||||
val key = keys.next()
|
val store = read()
|
||||||
found = key.contains("passphrase", ignoreCase = true) || hasPassphraseField(value.opt(key))
|
val unlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject()
|
||||||
}
|
val key = fingerprint.uppercase(Locale.ROOT)
|
||||||
found
|
if (ciphertext.isNullOrBlank()) unlocks.remove(key)
|
||||||
}
|
else {
|
||||||
is JSONArray -> (0 until value.length()).any { hasPassphraseField(value.opt(it)) }
|
require(ciphertext.length <= 16_384) { "Biometric key unlock data is too large." }
|
||||||
else -> false
|
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) {
|
||||||
|
require(candidate.toString().length <= 3_000_000) { "The OpenPGP key store is too large." }
|
||||||
|
require(!hasPassphraseField(candidate)) { "Passphrases must never be stored." }
|
||||||
|
val keys = candidate.optJSONArray("keys") ?: JSONArray()
|
||||||
|
val contacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
||||||
|
require(keys.length() <= 20 && contacts.length() <= 500) { "The OpenPGP key store has too many entries." }
|
||||||
|
val fingerprint = Regex("^[0-9A-Fa-f]{40,64}$")
|
||||||
|
for (index in 0 until keys.length()) {
|
||||||
|
val entry = keys.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP key entry is invalid.")
|
||||||
|
val privateKey = entry.optString("privateKey")
|
||||||
|
val publicKey = entry.optString("publicKey")
|
||||||
|
require(fingerprint.matches(entry.optString("fingerprint")) &&
|
||||||
|
privateKey.length in 1..200_000 && privateKey.contains("BEGIN PGP PRIVATE KEY BLOCK") &&
|
||||||
|
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK")) {
|
||||||
|
"An OpenPGP key entry is invalid."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (index in 0 until contacts.length()) {
|
||||||
|
val entry = contacts.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP contact entry is invalid.")
|
||||||
|
val publicKey = entry.optString("publicKey")
|
||||||
|
require(fingerprint.matches(entry.optString("fingerprint")) &&
|
||||||
|
publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK") &&
|
||||||
|
!publicKey.contains("BEGIN PGP PRIVATE KEY BLOCK")) {
|
||||||
|
"An OpenPGP contact entry is invalid."
|
||||||
|
}
|
||||||
|
require(entry.optString("trust") in setOf("unknown", "trusted", "verified")) {
|
||||||
|
"An OpenPGP contact trust value is invalid."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hasPassphraseField(value: Any?): Boolean = when (value) {
|
||||||
|
is JSONObject -> {
|
||||||
|
val keys = value.keys()
|
||||||
|
var found = false
|
||||||
|
while (keys.hasNext() && !found) {
|
||||||
|
val key = keys.next()
|
||||||
|
found = key.contains("passphrase", ignoreCase = true) || hasPassphraseField(value.opt(key))
|
||||||
|
}
|
||||||
|
found
|
||||||
|
}
|
||||||
|
is JSONArray -> (0 until value.length()).any { hasPassphraseField(value.opt(it)) }
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
|
||||||
fun account(id: String? = null): JSONObject? {
|
fun account(id: String? = null): JSONObject? {
|
||||||
val store = read()
|
val store = read()
|
||||||
@@ -283,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()) {
|
||||||
@@ -292,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>()
|
||||||
for (itemIndex in 0 until previous.length()) {
|
if (!replace) {
|
||||||
val item = previous.optJSONObject(itemIndex) ?: continue
|
for (itemIndex in 0 until previous.length()) {
|
||||||
merged[item.optString("uid", item.optString("id"))] = item
|
val item = previous.optJSONObject(itemIndex) ?: continue
|
||||||
|
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)
|
||||||
@@ -312,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)
|
||||||
@@ -504,13 +571,13 @@ internal object AndroidAccountVault {
|
|||||||
.put("id", account.optString("id"))
|
.put("id", account.optString("id"))
|
||||||
.put("email", account.optString("email"))
|
.put("email", account.optString("email"))
|
||||||
.put("displayName", account.optString("displayName"))
|
.put("displayName", account.optString("displayName"))
|
||||||
.put("imapHost", account.optString("imapHost"))
|
.put("imapHost", account.optString("imapHost"))
|
||||||
.put("smtpHost", account.optString("smtpHost"))
|
.put("smtpHost", account.optString("smtpHost"))
|
||||||
.put("imapPort", account.optInt("imapPort", 143))
|
.put("imapPort", account.optInt("imapPort", 143))
|
||||||
.put("smtpPort", account.optInt("smtpPort", 587))
|
.put("smtpPort", account.optInt("smtpPort", 587))
|
||||||
.put("imapSecure", account.optBoolean("imapSecure", false))
|
.put("imapSecure", account.optBoolean("imapSecure", false))
|
||||||
.put("smtpSecure", account.optBoolean("smtpSecure", false))
|
.put("smtpSecure", account.optBoolean("smtpSecure", false))
|
||||||
.put("signature", account.optString("signature"))
|
.put("signature", account.optString("signature"))
|
||||||
.put("notificationsEnabled", account.optBoolean("notificationsEnabled", true))
|
.put("notificationsEnabled", account.optBoolean("notificationsEnabled", true))
|
||||||
.put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2))
|
.put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2))
|
||||||
.put("rules", account.optJSONArray("rules") ?: JSONArray())
|
.put("rules", account.optJSONArray("rules") ?: JSONArray())
|
||||||
@@ -601,6 +668,11 @@ internal object AndroidAccountVault {
|
|||||||
private fun secretKey(): SecretKey {
|
private fun secretKey(): SecretKey {
|
||||||
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
||||||
|
val hasEncryptedData = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
|
||||||
|
.contains(ENCRYPTED_VALUE)
|
||||||
|
check(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData)) {
|
||||||
|
AndroidVaultKeyPolicy.MISSING_KEY_MESSAGE
|
||||||
|
}
|
||||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
||||||
generator.init(
|
generator.init(
|
||||||
KeyGenParameterSpec.Builder(
|
KeyGenParameterSpec.Builder(
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -10,9 +11,10 @@ import android.webkit.MimeTypeMap
|
|||||||
import com.sun.mail.imap.IMAPFolder
|
import com.sun.mail.imap.IMAPFolder
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.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 {
|
||||||
@@ -264,25 +320,25 @@ internal object AndroidMailService {
|
|||||||
JSONObject().put("ok", true)
|
JSONObject().put("ok", true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun send(account: JSONObject, input: JSONObject): JSONObject {
|
fun send(account: JSONObject, input: JSONObject): JSONObject {
|
||||||
val rawBase64 = input.optString("rawBase64")
|
val rawBase64 = input.optString("rawBase64")
|
||||||
val session = Session.getInstance(smtpProperties(account), credentials(account))
|
val session = Session.getInstance(smtpProperties(account), credentials(account))
|
||||||
val message: MimeMessage
|
val message: MimeMessage
|
||||||
if (rawBase64.isNotBlank()) {
|
if (rawBase64.isNotBlank()) {
|
||||||
require(rawBase64.length <= 36_000_000 && rawBase64.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
|
require(rawBase64.length <= 36_000_000 && rawBase64.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
|
||||||
"The encrypted message is too large or invalid."
|
"The encrypted message is too large or invalid."
|
||||||
}
|
}
|
||||||
val bytes = Base64.decode(rawBase64, Base64.DEFAULT)
|
val bytes = Base64.decode(rawBase64, Base64.DEFAULT)
|
||||||
require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." }
|
require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." }
|
||||||
message = MimeMessage(session, ByteArrayInputStream(bytes))
|
message = MimeMessage(session, ByteArrayInputStream(bytes))
|
||||||
validateOpenPgpMime(message)
|
validateOpenPgpMime(message)
|
||||||
require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) {
|
require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) {
|
||||||
"The encrypted message needs a sender and at least one recipient."
|
"The encrypted message needs a sender and at least one recipient."
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val recipient = input.optString("to").trim()
|
val recipient = input.optString("to").trim()
|
||||||
require(recipient.isNotEmpty()) { "Add at least one recipient." }
|
require(recipient.isNotEmpty()) { "Add at least one recipient." }
|
||||||
message = MimeMessage(session)
|
message = MimeMessage(session)
|
||||||
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
|
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
|
||||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
|
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
|
||||||
val cc = input.optString("cc").trim()
|
val cc = input.optString("cc").trim()
|
||||||
@@ -321,10 +377,10 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
message.setContent(multipart)
|
message.setContent(multipart)
|
||||||
}
|
}
|
||||||
message.sentDate = Date()
|
message.sentDate = Date()
|
||||||
message.saveChanges()
|
message.saveChanges()
|
||||||
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
|
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
val transport = session.getTransport("smtp")
|
val transport = session.getTransport("smtp")
|
||||||
try {
|
try {
|
||||||
@@ -350,64 +406,65 @@ internal object AndroidMailService {
|
|||||||
} catch (_: Exception) {
|
} catch (_: Exception) {
|
||||||
savedToSent = false
|
savedToSent = false
|
||||||
}
|
}
|
||||||
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
|
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun pgpMessageSource(account: JSONObject, folderName: String, uid: Long): JSONObject = withStore(account) { _, store ->
|
|
||||||
require(uid > 0) { "That message could not be identified." }
|
|
||||||
val folder = resolveFolder(store, folderName) ?: throw IllegalStateException("That mail folder could not be found.")
|
|
||||||
folder.open(Folder.READ_ONLY)
|
|
||||||
try {
|
|
||||||
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
|
|
||||||
?: throw IllegalStateException("The message is no longer available.")
|
|
||||||
val output = ByteArrayOutputStream()
|
|
||||||
message.writeTo(output)
|
|
||||||
val bytes = output.toByteArray()
|
|
||||||
require(bytes.size <= 25 * 1024 * 1024) { "This encrypted message is too large to open on Android testing builds." }
|
|
||||||
JSONObject().put("rawBase64", Base64.encodeToString(bytes, Base64.NO_WRAP))
|
|
||||||
} finally {
|
|
||||||
folder.close(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun validateOpenPgpMime(message: MimeMessage) {
|
|
||||||
val contentType = message.contentType.lowercase(Locale.ROOT)
|
|
||||||
val multipart = message.content as? Multipart
|
|
||||||
?: throw IllegalArgumentException("The OpenPGP MIME message is malformed.")
|
|
||||||
require(multipart.count == 2) { "The OpenPGP MIME message has an unexpected structure." }
|
|
||||||
if (contentType.startsWith("multipart/encrypted")) {
|
|
||||||
val versionPart = multipart.getBodyPart(0)
|
|
||||||
val encryptedPart = multipart.getBodyPart(1)
|
|
||||||
val version = runCatching { versionPart.content.toString().trim() }.getOrDefault("")
|
|
||||||
val armor = runCatching { String(encryptedPart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
|
|
||||||
require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" &&
|
|
||||||
encryptedPart.isMimeType("application/octet-stream") &&
|
|
||||||
armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) {
|
|
||||||
"The encrypted OpenPGP payload is missing or malformed."
|
|
||||||
}
|
|
||||||
} else if (contentType.startsWith("multipart/signed")) {
|
|
||||||
val signaturePart = multipart.getBodyPart(1)
|
|
||||||
val armor = runCatching { String(signaturePart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("")
|
|
||||||
require(signaturePart.isMimeType("application/pgp-signature") &&
|
|
||||||
armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) {
|
|
||||||
"The OpenPGP signature is missing or malformed."
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
throw IllegalArgumentException("Only an OpenPGP MIME message can use the protected send path.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun savePgpAttachment(context: Context, input: JSONObject): JSONObject {
|
|
||||||
val filename = input.optString("filename").replace(Regex("[\\\\/\\r\\n\\u0000]"), "").take(255).ifBlank { "attachment" }
|
|
||||||
val contentType = input.optString("contentType", "application/octet-stream").lowercase(Locale.ROOT)
|
|
||||||
require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) { "The attachment content type is invalid." }
|
|
||||||
val encoded = input.optString("contentBase64")
|
|
||||||
require(encoded.length <= 36_000_000 && encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
|
|
||||||
"The attachment is too large or invalid."
|
|
||||||
}
|
|
||||||
return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT))
|
|
||||||
}
|
|
||||||
|
|
||||||
|
fun pgpMessageSource(account: JSONObject, folderName: String, uid: Long): JSONObject = withStore(account) { _, store ->
|
||||||
|
require(uid > 0) { "That message could not be identified." }
|
||||||
|
val folder = resolveFolder(store, folderName) ?: throw IllegalStateException("That mail folder could not be found.")
|
||||||
|
folder.open(Folder.READ_ONLY)
|
||||||
|
try {
|
||||||
|
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
|
||||||
|
?: throw IllegalStateException("The message is no longer available.")
|
||||||
|
val output = ByteArrayOutputStream()
|
||||||
|
message.writeTo(output)
|
||||||
|
val bytes = output.toByteArray()
|
||||||
|
require(bytes.size <= 25 * 1024 * 1024) { "This encrypted message is too large to open on Android testing builds." }
|
||||||
|
JSONObject().put("rawBase64", Base64.encodeToString(bytes, Base64.NO_WRAP))
|
||||||
|
} finally {
|
||||||
|
folder.close(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun validateOpenPgpMime(message: MimeMessage) {
|
||||||
|
val contentType = message.contentType.lowercase(Locale.ROOT)
|
||||||
|
val multipart = message.content as? Multipart
|
||||||
|
?: throw IllegalArgumentException("The OpenPGP MIME message is malformed.")
|
||||||
|
require(multipart.count == 2) { "The OpenPGP MIME message has an unexpected structure." }
|
||||||
|
if (contentType.startsWith("multipart/encrypted")) {
|
||||||
|
val versionPart = multipart.getBodyPart(0)
|
||||||
|
val encryptedPart = multipart.getBodyPart(1)
|
||||||
|
val version = versionPart.inputStream.bufferedReader(Charsets.US_ASCII).use { it.readText().trim() }
|
||||||
|
val armor = encryptedPart.inputStream.bufferedReader(Charsets.US_ASCII).use { it.readText() }
|
||||||
|
require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" &&
|
||||||
|
encryptedPart.isMimeType("application/octet-stream") &&
|
||||||
|
armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) {
|
||||||
|
"The encrypted OpenPGP payload is missing or malformed."
|
||||||
|
}
|
||||||
|
} else if (contentType.startsWith("multipart/signed")) {
|
||||||
|
val signaturePart = multipart.getBodyPart(1)
|
||||||
|
val armor = signaturePart.inputStream.bufferedReader(Charsets.US_ASCII).use { it.readText() }
|
||||||
|
require(signaturePart.isMimeType("application/pgp-signature") &&
|
||||||
|
armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) {
|
||||||
|
"The OpenPGP signature is missing or malformed."
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw IllegalArgumentException("Only an OpenPGP MIME message can use the protected send path.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun savePgpAttachment(context: Context, input: JSONObject): JSONObject {
|
||||||
|
val filename = input.optString("filename").replace(Regex("[\\\\/\\r\\n\\u0000]"), "").take(255).ifBlank { "attachment" }
|
||||||
|
val contentType = input.optString("contentType", "application/octet-stream").lowercase(Locale.ROOT)
|
||||||
|
require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) { "The attachment content type is invalid." }
|
||||||
|
val encoded = input.optString("contentBase64")
|
||||||
|
require(encoded.length <= 36_000_000 && encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
|
||||||
|
"The attachment is too large or invalid."
|
||||||
|
}
|
||||||
|
return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT))
|
||||||
|
}
|
||||||
|
|
||||||
|
@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)
|
||||||
@@ -422,7 +479,7 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
|
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
android.util.Log.w("EpMailOutbox", "Mail operation remains queued (${error.javaClass.simpleName})")
|
android.util.Log.w("EpMailOutbox", "Mail operation remains queued (${error.javaClass.simpleName})")
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
@@ -550,7 +607,7 @@ internal object AndroidMailService {
|
|||||||
inbox.close(true)
|
inbox.close(true)
|
||||||
}
|
}
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
android.util.Log.e("EpMailRules", "Could not apply a mail rule (${error.javaClass.simpleName})")
|
android.util.Log.e("EpMailRules", "Could not apply a mail rule (${error.javaClass.simpleName})")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -558,19 +615,19 @@ internal object AndroidMailService {
|
|||||||
|
|
||||||
fun watchInbox(
|
fun watchInbox(
|
||||||
account: JSONObject,
|
account: JSONObject,
|
||||||
onNewMail: (Int) -> Unit,
|
onNewMail: (Int) -> Unit,
|
||||||
shouldStop: () -> Boolean,
|
shouldStop: () -> Boolean,
|
||||||
onConnection: (Store?, Folder?) -> Unit
|
onConnection: (Store?, Folder?) -> Unit
|
||||||
) {
|
) {
|
||||||
val protocol = imapProtocol(account)
|
val protocol = imapProtocol(account)
|
||||||
val props = imapProperties(account).apply {
|
val props = imapProperties(account).apply {
|
||||||
setProperty("mail.$protocol.timeout", "0")
|
setProperty("mail.$protocol.timeout", "0")
|
||||||
setProperty("mail.$protocol.writetimeout", "60000")
|
setProperty("mail.$protocol.writetimeout", "60000")
|
||||||
}
|
}
|
||||||
val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
|
val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
|
||||||
.coerceIn(2, 60) * 60_000L
|
.coerceIn(2, 60) * 60_000L
|
||||||
val session = Session.getInstance(props, credentials(account))
|
val session = Session.getInstance(props, credentials(account))
|
||||||
val store = session.getStore(protocol)
|
val store = session.getStore(protocol)
|
||||||
try {
|
try {
|
||||||
store.connect(
|
store.connect(
|
||||||
account.optString("imapHost"),
|
account.optString("imapHost"),
|
||||||
@@ -665,12 +722,13 @@ internal object AndroidMailService {
|
|||||||
val body = ArrayList<String>()
|
val body = ArrayList<String>()
|
||||||
val htmlBodies = ArrayList<String>()
|
val htmlBodies = ArrayList<String>()
|
||||||
val attachments = JSONArray()
|
val attachments = JSONArray()
|
||||||
val links = linkedSetOf<String>()
|
val links = linkedSetOf<String>()
|
||||||
collectParts(message, body, htmlBodies, attachments, links)
|
collectParts(message, body, htmlBodies, attachments, links)
|
||||||
val bodyText = body.joinToString("\n\n").trim().take(8000)
|
val bodyText = body.joinToString("\n\n").trim().take(8000)
|
||||||
val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----")
|
val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----")
|
||||||
val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText
|
val signed = isSignedMessage(message) || bodyText.contains("-----BEGIN PGP SIGNED MESSAGE-----")
|
||||||
val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText
|
||||||
|
val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
||||||
val date = message.receivedDate ?: message.sentDate ?: Date()
|
val date = message.receivedDate ?: message.sentDate ?: Date()
|
||||||
val tags = JSONArray().put(requestedFolder)
|
val tags = JSONArray().put(requestedFolder)
|
||||||
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
|
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
|
||||||
@@ -691,9 +749,10 @@ internal object AndroidMailService {
|
|||||||
.put("color", "#dce6df")
|
.put("color", "#dce6df")
|
||||||
.put("sender", senderName)
|
.put("sender", senderName)
|
||||||
.put("email", senderEmail)
|
.put("email", senderEmail)
|
||||||
.put("subject", subject)
|
.put("subject", subject)
|
||||||
.put("snippet", snippet)
|
.put("snippet", snippet)
|
||||||
.put("encrypted", encrypted)
|
.put("encrypted", encrypted)
|
||||||
|
.put("signed", signed)
|
||||||
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
|
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
|
||||||
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
|
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
|
||||||
.put("timestamp", date.time)
|
.put("timestamp", date.time)
|
||||||
@@ -706,23 +765,32 @@ internal object AndroidMailService {
|
|||||||
.put("sourceFolder", labelFolder)
|
.put("sourceFolder", labelFolder)
|
||||||
.put("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
|
.put("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
|
||||||
.put("body", JSONArray().apply {
|
.put("body", JSONArray().apply {
|
||||||
val paragraphs = visibleBody.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
val paragraphs = visibleBody.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
||||||
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
||||||
})
|
})
|
||||||
.put("links", JSONArray().apply { links.take(30).forEach(::put) })
|
.put("links", JSONArray().apply { links.take(30).forEach(::put) })
|
||||||
.put("attachments", attachments)
|
.put("attachments", attachments)
|
||||||
.put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL)
|
.put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL)
|
||||||
.put("size", files.firstOrNull()?.optString("size") ?: "")
|
.put("size", files.firstOrNull()?.optString("size") ?: "")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isEncryptedMessage(part: javax.mail.Part): Boolean {
|
private fun isEncryptedMessage(part: javax.mail.Part): Boolean {
|
||||||
if (part.isMimeType("multipart/encrypted")) return true
|
if (part.isMimeType("multipart/encrypted")) return true
|
||||||
val content = try { part.content } catch (_: Exception) { return false }
|
val content = try { part.content } catch (_: Exception) { return false }
|
||||||
if (content is Multipart) {
|
if (content is Multipart) {
|
||||||
for (index in 0 until content.count) if (isEncryptedMessage(content.getBodyPart(index))) return true
|
for (index in 0 until content.count) if (isEncryptedMessage(content.getBodyPart(index))) return true
|
||||||
} else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true
|
} else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun isSignedMessage(part: javax.mail.Part): Boolean {
|
||||||
|
if (part.isMimeType("multipart/signed")) return true
|
||||||
|
val content = try { part.content } catch (_: Exception) { return false }
|
||||||
|
if (content is Multipart) {
|
||||||
|
for (index in 0 until content.count) if (isSignedMessage(content.getBodyPart(index))) return true
|
||||||
|
} else if (content is String && content.contains("-----BEGIN PGP SIGNED MESSAGE-----")) return true
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
||||||
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
||||||
@@ -734,7 +802,9 @@ internal object AndroidMailService {
|
|||||||
attachments: JSONArray,
|
attachments: JSONArray,
|
||||||
links: MutableSet<String>
|
links: MutableSet<String>
|
||||||
) {
|
) {
|
||||||
|
if (part.isMimeType("application/pgp-signature") || part.isMimeType("application/pgp-encrypted")) return
|
||||||
val filename = decode(part.fileName)
|
val filename = decode(part.fileName)
|
||||||
|
if (part.isMimeType("application/octet-stream") && filename.equals("encrypted.asc", true)) return
|
||||||
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
|
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
|
||||||
val name = filename.ifBlank { "attachment" }
|
val name = filename.ifBlank { "attachment" }
|
||||||
val size = part.size.coerceAtLeast(0)
|
val size = part.size.coerceAtLeast(0)
|
||||||
@@ -773,29 +843,60 @@ internal object AndroidMailService {
|
|||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
|
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
|
||||||
val safeFilename = AttachmentNamePolicy.sanitize(filename)
|
return saveAttachmentStream(context, filename, contentType, ByteArrayInputStream(bytes))
|
||||||
val mimeType = contentType.substringBefore(';').ifBlank {
|
}
|
||||||
MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
|
||||||
}
|
private fun saveAttachmentStream(context: Context, filename: String, contentType: String, input: InputStream): JSONObject {
|
||||||
if (Build.VERSION.SDK_INT >= 29) {
|
val safeFilename = AttachmentNamePolicy.sanitize(filename)
|
||||||
val values = ContentValues().apply {
|
val mimeType = contentType.substringBefore(';').ifBlank {
|
||||||
put(MediaStore.Downloads.DISPLAY_NAME, safeFilename)
|
MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= 29) {
|
||||||
|
val values = ContentValues().apply {
|
||||||
|
put(MediaStore.Downloads.DISPLAY_NAME, safeFilename)
|
||||||
put(MediaStore.Downloads.MIME_TYPE, mimeType)
|
put(MediaStore.Downloads.MIME_TYPE, mimeType)
|
||||||
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||||
}
|
}
|
||||||
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 {
|
||||||
?: throw IllegalStateException("Could not write the attachment.")
|
val output = context.contentResolver.openOutputStream(uri)
|
||||||
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", safeFilename)
|
?: 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)
|
||||||
|
}
|
||||||
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 {
|
||||||
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename)
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
private const val CUSTOM_FOLDER_PREFIX = "Folder:"
|
private const val CUSTOM_FOLDER_PREFIX = "Folder:"
|
||||||
private val reservedFolderNames = setOf(
|
private val reservedFolderNames = setOf(
|
||||||
@@ -866,9 +967,9 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
|
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
|
||||||
val session = Session.getInstance(imapProperties(account), credentials(account))
|
val session = Session.getInstance(imapProperties(account), credentials(account))
|
||||||
val store = session.getStore(imapProtocol(account))
|
val store = session.getStore(imapProtocol(account))
|
||||||
try {
|
try {
|
||||||
store.connect(
|
store.connect(
|
||||||
account.optString("imapHost"),
|
account.optString("imapHost"),
|
||||||
@@ -882,28 +983,28 @@ internal object AndroidMailService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun credentials(account: JSONObject) = object : Authenticator() {
|
private fun credentials(account: JSONObject) = object : Authenticator() {
|
||||||
override fun getPasswordAuthentication() = PasswordAuthentication(
|
override fun getPasswordAuthentication() = PasswordAuthentication(
|
||||||
account.optString("email"),
|
account.optString("email"),
|
||||||
account.optString("password")
|
account.optString("password")
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun imapProperties(account: JSONObject) = Properties().apply {
|
private fun imapProperties(account: JSONObject) = Properties().apply {
|
||||||
putAll(AndroidMailTransport.imapProperties(MailServerConnection(
|
putAll(AndroidMailTransport.imapProperties(MailServerConnection(
|
||||||
account.optString("imapHost"),
|
account.optString("imapHost"),
|
||||||
account.optInt("imapPort", 143),
|
account.optInt("imapPort", 143),
|
||||||
account.optBoolean("imapSecure", false)
|
account.optBoolean("imapSecure", false)
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun imapProtocol(account: JSONObject) = if (account.optBoolean("imapSecure", false)) "imaps" else "imap"
|
private fun imapProtocol(account: JSONObject) = if (account.optBoolean("imapSecure", false)) "imaps" else "imap"
|
||||||
|
|
||||||
private fun smtpProperties(account: JSONObject) = AndroidMailTransport.smtpProperties(MailServerConnection(
|
private fun smtpProperties(account: JSONObject) = AndroidMailTransport.smtpProperties(MailServerConnection(
|
||||||
account.optString("smtpHost"),
|
account.optString("smtpHost"),
|
||||||
account.optInt("smtpPort", 587),
|
account.optInt("smtpPort", 587),
|
||||||
account.optBoolean("smtpSecure", false)
|
account.optBoolean("smtpSecure", false)
|
||||||
))
|
))
|
||||||
|
|
||||||
private fun displayName(account: JSONObject) =
|
private fun displayName(account: JSONObject) =
|
||||||
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
|
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
|
import android.security.keystore.KeyGenParameterSpec
|
||||||
|
import android.security.keystore.KeyPermanentlyInvalidatedException
|
||||||
|
import android.security.keystore.KeyProperties
|
||||||
|
import android.util.Base64
|
||||||
|
import androidx.biometric.BiometricManager
|
||||||
|
import java.security.KeyStore
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import javax.crypto.KeyGenerator
|
||||||
|
import javax.crypto.SecretKey
|
||||||
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
|
|
||||||
|
internal class PgpBiometricUnlockException(
|
||||||
|
val errorCode: String,
|
||||||
|
message: String,
|
||||||
|
cause: Throwable? = null
|
||||||
|
) : IllegalStateException(message, cause)
|
||||||
|
|
||||||
|
internal object AndroidPgpBiometricUnlock {
|
||||||
|
private const val ALIAS_PREFIX = "ep-mail-pgp-unlock-"
|
||||||
|
private const val GCM_TAG_BITS = 128
|
||||||
|
private const val IV_BYTES = 12
|
||||||
|
|
||||||
|
fun requireAvailable(context: Context) {
|
||||||
|
val authenticators = allowedAuthenticators()
|
||||||
|
val result = BiometricManager.from(context).canAuthenticate(authenticators)
|
||||||
|
require(result == BiometricManager.BIOMETRIC_SUCCESS) {
|
||||||
|
"Set up a strong biometric or device screen lock before enabling biometric key unlock."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun encryptCipher(context: Context, fingerprint: String): Cipher {
|
||||||
|
requireAvailable(context)
|
||||||
|
try {
|
||||||
|
return createEncryptCipher(context, fingerprint)
|
||||||
|
} catch (_: KeyPermanentlyInvalidatedException) {
|
||||||
|
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
|
||||||
|
deleteKey(fingerprint)
|
||||||
|
return createEncryptCipher(context, fingerprint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createEncryptCipher(context: Context, fingerprint: String): Cipher {
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, secretKey(context, fingerprint))
|
||||||
|
return cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
fun decryptCipher(context: Context, fingerprint: String, ciphertext: String): Cipher {
|
||||||
|
val payload = try {
|
||||||
|
Base64.decode(ciphertext, Base64.NO_WRAP)
|
||||||
|
} catch (_: IllegalArgumentException) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_CORRUPT", "Biometric key unlock data is damaged. Enter the key passphrase and set it up again.")
|
||||||
|
}
|
||||||
|
require(payload.size > IV_BYTES) {
|
||||||
|
"Biometric key unlock data is damaged. Enter the key passphrase and set it up again."
|
||||||
|
}
|
||||||
|
val key = try {
|
||||||
|
secretKey(context, fingerprint, create = false)
|
||||||
|
} catch (_: KeyPermanentlyInvalidatedException) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
|
||||||
|
} catch (_: Exception) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric key unlock is unavailable. Enter the key passphrase and set it up again.")
|
||||||
|
}
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
try {
|
||||||
|
cipher.init(
|
||||||
|
Cipher.DECRYPT_MODE,
|
||||||
|
key,
|
||||||
|
GCMParameterSpec(GCM_TAG_BITS, payload.copyOfRange(0, IV_BYTES))
|
||||||
|
)
|
||||||
|
} catch (_: KeyPermanentlyInvalidatedException) {
|
||||||
|
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
|
||||||
|
}
|
||||||
|
return cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
fun seal(passphrase: String, cipher: Cipher): String {
|
||||||
|
require(passphrase.length in 1..4096) { "The key passphrase is empty or too long for biometric unlock." }
|
||||||
|
val plaintext = passphrase.toByteArray(Charsets.UTF_8)
|
||||||
|
val encrypted = try {
|
||||||
|
cipher.doFinal(plaintext)
|
||||||
|
} finally {
|
||||||
|
plaintext.fill(0)
|
||||||
|
}
|
||||||
|
return Base64.encodeToString(cipher.iv + encrypted, Base64.NO_WRAP)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun open(ciphertext: String, cipher: Cipher): String {
|
||||||
|
val payload = Base64.decode(ciphertext, Base64.NO_WRAP)
|
||||||
|
val plaintext = cipher.doFinal(payload.copyOfRange(IV_BYTES, payload.size))
|
||||||
|
return String(plaintext, Charsets.UTF_8).also { plaintext.fill(0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteKey(fingerprint: String) {
|
||||||
|
val alias = alias(fingerprint)
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
if (keyStore.containsAlias(alias)) keyStore.deleteEntry(alias)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deleteAllKeys() {
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
val aliases = keyStore.aliases()
|
||||||
|
while (aliases.hasMoreElements()) {
|
||||||
|
val name = aliases.nextElement()
|
||||||
|
if (name.startsWith(ALIAS_PREFIX)) keyStore.deleteEntry(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun secretKey(context: Context, fingerprint: String, create: Boolean = true): SecretKey {
|
||||||
|
val alias = alias(fingerprint)
|
||||||
|
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
|
||||||
|
try {
|
||||||
|
(keyStore.getKey(alias, null) as? SecretKey)?.let { return it }
|
||||||
|
} catch (error: KeyPermanentlyInvalidatedException) {
|
||||||
|
throw error
|
||||||
|
} catch (error: Exception) {
|
||||||
|
throw IllegalStateException("Biometric key unlock is unavailable. Enter the key passphrase and set it up again.", error)
|
||||||
|
}
|
||||||
|
if (!create) {
|
||||||
|
throw PgpBiometricUnlockException(
|
||||||
|
"BIOMETRIC_INVALIDATED",
|
||||||
|
"Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
|
||||||
|
val spec = KeyGenParameterSpec.Builder(
|
||||||
|
alias,
|
||||||
|
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
|
||||||
|
)
|
||||||
|
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||||
|
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||||
|
.setKeySize(256)
|
||||||
|
.setRandomizedEncryptionRequired(true)
|
||||||
|
.setUserAuthenticationRequired(true)
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
spec.setUserAuthenticationParameters(
|
||||||
|
0,
|
||||||
|
KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
spec.setUserAuthenticationValidityDurationSeconds(-1)
|
||||||
|
spec.setInvalidatedByBiometricEnrollment(true)
|
||||||
|
}
|
||||||
|
generator.init(spec.build())
|
||||||
|
return generator.generateKey()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun allowedAuthenticators(): Int =
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
BiometricManager.Authenticators.BIOMETRIC_STRONG or
|
||||||
|
BiometricManager.Authenticators.DEVICE_CREDENTIAL
|
||||||
|
} else {
|
||||||
|
BiometricManager.Authenticators.BIOMETRIC_STRONG
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun alias(fingerprint: String): String {
|
||||||
|
require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) {
|
||||||
|
"The OpenPGP fingerprint is invalid."
|
||||||
|
}
|
||||||
|
return ALIAS_PREFIX + fingerprint.uppercase()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
/** Makes native confirmations fail closed and guarantees each plugin call gets one decision. */
|
||||||
|
internal class AndroidPgpConfirmationGate(
|
||||||
|
private val showPrompt: (Prompt) -> Unit,
|
||||||
|
private val dispatch: ((() -> Unit) -> Unit)
|
||||||
|
) {
|
||||||
|
data class Prompt(
|
||||||
|
val title: String,
|
||||||
|
val message: String,
|
||||||
|
val confirmLabel: String,
|
||||||
|
val cancelLabel: String,
|
||||||
|
val confirm: () -> Unit,
|
||||||
|
val cancel: () -> Unit
|
||||||
|
)
|
||||||
|
|
||||||
|
fun request(
|
||||||
|
title: String,
|
||||||
|
message: String,
|
||||||
|
confirmLabel: String,
|
||||||
|
cancelLabel: String = "Cancel",
|
||||||
|
onConfirmed: () -> Unit,
|
||||||
|
onCancelled: () -> Unit
|
||||||
|
) {
|
||||||
|
val decided = AtomicBoolean(false)
|
||||||
|
showPrompt(
|
||||||
|
Prompt(
|
||||||
|
title = title,
|
||||||
|
message = message,
|
||||||
|
confirmLabel = confirmLabel,
|
||||||
|
cancelLabel = cancelLabel,
|
||||||
|
confirm = { if (decided.compareAndSet(false, true)) dispatch(onConfirmed) },
|
||||||
|
cancel = { if (decided.compareAndSet(false, true)) dispatch(onCancelled) }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,8 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
internal object AndroidVaultKeyPolicy {
|
||||||
|
fun shouldCreateKey(hasEncryptedData: Boolean): Boolean = !hasEncryptedData
|
||||||
|
|
||||||
|
const val MISSING_KEY_MESSAGE =
|
||||||
|
"The Android Keystore key for saved app data is missing. Existing encrypted data was not reset or replaced."
|
||||||
|
}
|
||||||
@@ -0,0 +1,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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,21 +6,32 @@ import android.content.Intent
|
|||||||
import android.content.IntentFilter
|
import android.content.IntentFilter
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
|
import android.app.Activity
|
||||||
import android.app.AlertDialog
|
import android.app.AlertDialog
|
||||||
|
import androidx.activity.result.ActivityResult
|
||||||
|
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
|
||||||
import com.getcapacitor.PluginMethod
|
import com.getcapacitor.PluginMethod
|
||||||
|
import com.getcapacitor.annotation.ActivityCallback
|
||||||
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 org.json.JSONArray
|
import java.util.concurrent.Executors
|
||||||
import org.json.JSONObject
|
import org.json.JSONArray
|
||||||
import javax.mail.internet.InternetAddress
|
import org.json.JSONObject
|
||||||
|
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)
|
||||||
@@ -38,14 +49,27 @@ class EpMailPlugin : Plugin() {
|
|||||||
@Suppress("DEPRECATION")
|
@Suppress("DEPRECATION")
|
||||||
context.registerReceiver(receiver, filter)
|
context.registerReceiver(receiver, filter)
|
||||||
}
|
}
|
||||||
MailIdleService.start(context)
|
ensureVaultAvailableAndStartSync()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun handleOnResume() {
|
override fun handleOnResume() {
|
||||||
MailIdleService.start(context)
|
ensureVaultAvailableAndStartSync()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureVaultAvailableAndStartSync() {
|
||||||
|
try {
|
||||||
|
AndroidAccountVault.read()
|
||||||
|
MailIdleService.start(context)
|
||||||
|
} catch (error: Exception) {
|
||||||
|
android.util.Log.e("EpMailStorage", "Secure local storage is unavailable (${error.javaClass.simpleName})")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun handleOnDestroy() {
|
override fun handleOnDestroy() {
|
||||||
|
mailboxExecutor.shutdown()
|
||||||
|
folderListExecutor.shutdown()
|
||||||
|
mailActionExecutor.shutdown()
|
||||||
|
outboxExecutor.shutdown()
|
||||||
syncReceiver?.let {
|
syncReceiver?.let {
|
||||||
try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {}
|
try { context.unregisterReceiver(it) } catch (_: IllegalArgumentException) {}
|
||||||
}
|
}
|
||||||
@@ -55,144 +79,349 @@ class EpMailPlugin : Plugin() {
|
|||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun getAppVersion(call: PluginCall) {
|
fun getAppVersion(call: PluginCall) {
|
||||||
call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME))
|
call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME))
|
||||||
}
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun getNotificationPrivacy(call: PluginCall) {
|
fun pickPgpPrivateKey(call: PluginCall) {
|
||||||
try {
|
try {
|
||||||
call.resolve(JSObject().put("showDetails", AndroidAccountVault.notificationDetailsEnabled()))
|
if (AndroidAccountVault.appLockEnabled()) {
|
||||||
} catch (error: Exception) {
|
call.reject("File import is unavailable while app lock is enabled. Paste the key instead, or temporarily disable app lock and re-enable it after importing.")
|
||||||
call.reject(error.message ?: "Could not read notification privacy settings.")
|
return
|
||||||
}
|
}
|
||||||
}
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not check the app lock setting.")
|
||||||
@PluginMethod
|
return
|
||||||
fun setNotificationDetails(call: PluginCall) {
|
}
|
||||||
try {
|
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
|
||||||
val enabled = call.getBoolean("enabled")
|
addCategory(Intent.CATEGORY_OPENABLE)
|
||||||
?: throw IllegalArgumentException("Choose whether notifications may show details.")
|
type = "*/*"
|
||||||
AndroidAccountVault.setNotificationDetailsEnabled(enabled)
|
}
|
||||||
call.resolve(JSObject().put("showDetails", enabled))
|
try {
|
||||||
} catch (error: Exception) {
|
startActivityForResult(call, intent, "pgpPrivateKeyPicked")
|
||||||
call.reject(error.message ?: "Could not save notification privacy settings.")
|
} catch (_: android.content.ActivityNotFoundException) {
|
||||||
}
|
call.reject("No file picker is available on this device.")
|
||||||
}
|
}
|
||||||
|
}
|
||||||
@PluginMethod
|
|
||||||
fun getAppLockSettings(call: PluginCall) {
|
@ActivityCallback
|
||||||
try {
|
private fun pgpPrivateKeyPicked(call: PluginCall?, result: ActivityResult) {
|
||||||
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
if (call == null) return
|
||||||
call.resolve(JSObject()
|
if (result.resultCode != Activity.RESULT_OK) {
|
||||||
.put("enabled", AndroidAccountVault.appLockEnabled())
|
call.resolve(JSObject().put("canceled", true))
|
||||||
.put("deviceSecure", keyguard.isDeviceSecure))
|
return
|
||||||
} catch (error: Exception) {
|
}
|
||||||
call.reject(error.message ?: "Could not read app-lock settings.")
|
val uri = result.data?.data
|
||||||
}
|
if (uri == null || uri.scheme != "content") {
|
||||||
}
|
call.reject("Could not access the selected key file.")
|
||||||
|
return
|
||||||
@PluginMethod
|
}
|
||||||
fun setAppLockEnabled(call: PluginCall) {
|
mailboxExecutor.execute {
|
||||||
try {
|
try {
|
||||||
val enabled = call.getBoolean("enabled")
|
val bytes = context.contentResolver.openInputStream(uri)?.use {
|
||||||
?: throw IllegalArgumentException("Choose whether to lock ep-mail when you leave it.")
|
BoundedInputReader.read(it, 200001)
|
||||||
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
} ?: throw IllegalArgumentException("Could not open the selected key file.")
|
||||||
require(!enabled || keyguard.isDeviceSecure) {
|
if (bytes.isEmpty() || bytes.size > 200000) {
|
||||||
"Set a screen lock in Android Settings before enabling the app lock."
|
throw IllegalArgumentException("That key file is empty or too large (maximum 200 KB).")
|
||||||
}
|
}
|
||||||
AndroidAccountVault.setAppLockEnabled(enabled)
|
call.resolve(JSObject().put("armoredKey", String(bytes, Charsets.UTF_8)))
|
||||||
(activity as? MainActivity)?.onAppLockSettingChanged(enabled)
|
} catch (error: Exception) {
|
||||||
call.resolve(JSObject().put("enabled", enabled).put("deviceSecure", keyguard.isDeviceSecure))
|
call.reject(error.message ?: "Could not read the selected key file.")
|
||||||
} catch (error: Exception) {
|
}
|
||||||
call.reject(error.message ?: "Could not save app-lock settings.")
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
@PluginMethod
|
||||||
@PluginMethod
|
fun getNotificationPrivacy(call: PluginCall) {
|
||||||
fun pgpLoadStore(call: PluginCall) {
|
try {
|
||||||
try {
|
call.resolve(JSObject().put("showDetails", AndroidAccountVault.notificationDetailsEnabled()))
|
||||||
call.resolve(AndroidAccountVault.pgpStore().toJSObject())
|
} catch (error: Exception) {
|
||||||
} catch (error: Exception) {
|
call.reject(error.message ?: "Could not read notification privacy settings.")
|
||||||
call.reject(error.message ?: "Could not load the Android OpenPGP key store.")
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
@PluginMethod
|
||||||
@PluginMethod
|
fun setNotificationDetails(call: PluginCall) {
|
||||||
fun pgpSaveStore(call: PluginCall) {
|
try {
|
||||||
try {
|
val enabled = call.getBoolean("enabled")
|
||||||
val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.")
|
?: throw IllegalArgumentException("Choose whether notifications may show details.")
|
||||||
val next = JSONObject(candidate.toString())
|
AndroidAccountVault.setNotificationDetailsEnabled(enabled)
|
||||||
val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next)
|
call.resolve(JSObject().put("showDetails", enabled))
|
||||||
if (warning == null) {
|
} catch (error: Exception) {
|
||||||
AndroidAccountVault.savePgpStore(next)
|
call.reject(error.message ?: "Could not save notification privacy settings.")
|
||||||
call.resolve(JSObject().put("ok", true))
|
}
|
||||||
} else {
|
}
|
||||||
val host = activity
|
|
||||||
host.runOnUiThread {
|
@PluginMethod
|
||||||
AlertDialog.Builder(host)
|
fun getAppLockSettings(call: PluginCall) {
|
||||||
.setTitle("Confirm OpenPGP key changes")
|
try {
|
||||||
.setMessage(warning)
|
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
||||||
.setNegativeButton("Cancel") { _, _ -> call.reject("OpenPGP key change cancelled.") }
|
call.resolve(JSObject()
|
||||||
.setPositiveButton("Confirm changes") { _, _ ->
|
.put("enabled", AndroidAccountVault.appLockEnabled())
|
||||||
bridge.execute {
|
.put("lockDelaySeconds", AndroidAccountVault.appLockDelaySeconds())
|
||||||
try {
|
.put("deviceSecure", keyguard.isDeviceSecure))
|
||||||
AndroidAccountVault.savePgpStore(next)
|
} catch (error: Exception) {
|
||||||
call.resolve(JSObject().put("ok", true))
|
call.reject(error.message ?: "Could not read app-lock settings.")
|
||||||
} catch (error: Exception) {
|
}
|
||||||
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
|
}
|
||||||
}
|
|
||||||
}
|
@PluginMethod
|
||||||
}
|
fun setAppLockEnabled(call: PluginCall) {
|
||||||
.setOnCancelListener { call.reject("OpenPGP key change cancelled.") }
|
try {
|
||||||
.show()
|
val enabled = call.getBoolean("enabled")
|
||||||
}
|
?: throw IllegalArgumentException("Choose whether to lock ep-mail when you leave it.")
|
||||||
}
|
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
|
||||||
} catch (error: Exception) {
|
require(!enabled || keyguard.isDeviceSecure) {
|
||||||
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
|
"Set a screen lock in Android Settings before enabling the app lock."
|
||||||
}
|
}
|
||||||
}
|
AndroidAccountVault.setAppLockEnabled(enabled)
|
||||||
|
(activity as? MainActivity)?.onAppLockSettingChanged(enabled)
|
||||||
private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? {
|
call.resolve(JSObject().put("enabled", enabled).put("deviceSecure", keyguard.isDeviceSecure))
|
||||||
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
|
} catch (error: Exception) {
|
||||||
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
call.reject(error.message ?: "Could not save app-lock settings.")
|
||||||
return AndroidPgpPolicy.storeChangeWarning(pgpContacts(oldContacts), pgpContacts(newContacts))
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun pgpContacts(values: JSONArray): List<AndroidPgpPolicy.ContactKey> =
|
@PluginMethod
|
||||||
(0 until values.length()).mapNotNull { values.optJSONObject(it) }.map { contact ->
|
fun setAppLockDelay(call: PluginCall) {
|
||||||
AndroidPgpPolicy.ContactKey(
|
try {
|
||||||
fingerprint = contact.optString("fingerprint"),
|
val seconds = call.getInt("seconds")
|
||||||
emails = jsonStrings(contact.optJSONArray("emails")),
|
?: throw IllegalArgumentException("Choose when ep-mail should lock after leaving it.")
|
||||||
trust = contact.optString("trust")
|
call.resolve(JSObject().put("lockDelaySeconds", AndroidAccountVault.setAppLockDelaySeconds(seconds)))
|
||||||
)
|
} catch (error: Exception) {
|
||||||
}
|
call.reject(error.message ?: "Could not save the app-lock delay.")
|
||||||
|
}
|
||||||
private fun jsonStrings(values: JSONArray?): List<String> =
|
}
|
||||||
values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
|
||||||
|
@PluginMethod
|
||||||
@PluginMethod
|
fun pgpLoadStore(call: PluginCall) {
|
||||||
fun pgpGetMessageSource(call: PluginCall) {
|
try {
|
||||||
try {
|
call.resolve(AndroidAccountVault.pgpStore().toJSObject())
|
||||||
val account = AndroidAccountVault.account()
|
} catch (error: Exception) {
|
||||||
?: throw IllegalStateException("Add a mail account before opening messages.")
|
call.reject(error.message ?: "Could not load the Android OpenPGP key store.")
|
||||||
val folder = call.getString("folder") ?: "Inbox"
|
}
|
||||||
val uid = call.getLong("uid") ?: 0L
|
}
|
||||||
call.resolve(AndroidMailService.pgpMessageSource(account, folder, uid).toJSObject())
|
|
||||||
} catch (error: Exception) {
|
@PluginMethod
|
||||||
call.reject(error.message ?: "Could not load the encrypted message.")
|
fun pgpSaveStore(call: PluginCall) {
|
||||||
}
|
try {
|
||||||
}
|
val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.")
|
||||||
|
val next = JSONObject(candidate.toString())
|
||||||
@PluginMethod
|
val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next)
|
||||||
fun savePgpAttachment(call: PluginCall) {
|
if (warning == null) {
|
||||||
try {
|
AndroidAccountVault.savePgpStore(next)
|
||||||
call.resolve(AndroidMailService.savePgpAttachment(context, JSONObject(call.data.toString())).toJSObject())
|
call.resolve(JSObject().put("ok", true))
|
||||||
} catch (error: Exception) {
|
} else {
|
||||||
call.reject(error.message ?: "Could not save the decrypted attachment.")
|
showPgpConfirmation(
|
||||||
}
|
title = "Confirm OpenPGP key changes",
|
||||||
}
|
message = warning,
|
||||||
|
confirmLabel = "Confirm changes",
|
||||||
@PluginMethod
|
onConfirmed = {
|
||||||
fun getAccount(call: PluginCall) {
|
try {
|
||||||
|
AndroidAccountVault.savePgpStore(next)
|
||||||
|
call.resolve(JSObject().put("ok", true))
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onCancelled = { call.reject("OpenPGP key change cancelled.") }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save the Android OpenPGP key store.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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? {
|
||||||
|
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
|
||||||
|
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
|
||||||
|
return AndroidPgpPolicy.storeChangeWarning(pgpContacts(oldContacts), pgpContacts(newContacts))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pgpContacts(values: JSONArray): List<AndroidPgpPolicy.ContactKey> =
|
||||||
|
(0 until values.length()).mapNotNull { values.optJSONObject(it) }.map { contact ->
|
||||||
|
AndroidPgpPolicy.ContactKey(
|
||||||
|
fingerprint = contact.optString("fingerprint"),
|
||||||
|
emails = jsonStrings(contact.optJSONArray("emails")),
|
||||||
|
trust = contact.optString("trust")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun jsonStrings(values: JSONArray?): List<String> =
|
||||||
|
values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
||||||
|
|
||||||
|
private fun showPgpConfirmation(
|
||||||
|
title: String,
|
||||||
|
message: String,
|
||||||
|
confirmLabel: String,
|
||||||
|
onConfirmed: () -> Unit,
|
||||||
|
onCancelled: () -> Unit
|
||||||
|
) {
|
||||||
|
val gate = AndroidPgpConfirmationGate(
|
||||||
|
showPrompt = { prompt ->
|
||||||
|
val host = activity
|
||||||
|
host.runOnUiThread {
|
||||||
|
AlertDialog.Builder(host)
|
||||||
|
.setTitle(prompt.title)
|
||||||
|
.setMessage(prompt.message)
|
||||||
|
.setNegativeButton(prompt.cancelLabel) { _, _ -> prompt.cancel() }
|
||||||
|
.setPositiveButton(prompt.confirmLabel) { _, _ -> prompt.confirm() }
|
||||||
|
.setOnCancelListener { prompt.cancel() }
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
dispatch = { action -> bridge.execute(action) }
|
||||||
|
)
|
||||||
|
gate.request(title, message, confirmLabel, onConfirmed = onConfirmed, onCancelled = onCancelled)
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun pgpGetMessageSource(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
val account = AndroidAccountVault.account()
|
||||||
|
?: throw IllegalStateException("Add a mail account before opening messages.")
|
||||||
|
val folder = call.getString("folder") ?: "Inbox"
|
||||||
|
val uid = PgpMessageUid.requireValid(call.data.opt("uid"))
|
||||||
|
call.resolve(AndroidMailService.pgpMessageSource(account, folder, uid).toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not load the encrypted message.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun savePgpAttachment(call: PluginCall) {
|
||||||
|
try {
|
||||||
|
call.resolve(AndroidMailService.savePgpAttachment(context, JSONObject(call.data.toString())).toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not save the decrypted attachment.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PluginMethod
|
||||||
|
fun getAccount(call: PluginCall) {
|
||||||
val account = AndroidAccountVault.account()
|
val account = AndroidAccountVault.account()
|
||||||
if (account == null) call.resolve()
|
if (account == null) call.resolve()
|
||||||
else call.resolve(AndroidAccountVault.publicAccount(account).toJSObject())
|
else call.resolve(AndroidAccountVault.publicAccount(account).toJSObject())
|
||||||
@@ -234,6 +463,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 {
|
||||||
@@ -276,9 +540,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.")
|
||||||
call.resolve(AndroidMailService.listFolders(account).toJSObject())
|
folderListExecutor.execute {
|
||||||
|
try {
|
||||||
|
call.resolve(AndroidMailService.listFolders(account).toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not list mail folders.")
|
||||||
|
}
|
||||||
|
}
|
||||||
} 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.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,6 +564,21 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@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
|
||||||
fun syncFolder(call: PluginCall) {
|
fun syncFolder(call: PluginCall) {
|
||||||
try {
|
try {
|
||||||
val account = AndroidAccountVault.account()
|
val account = AndroidAccountVault.account()
|
||||||
@@ -304,10 +589,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 {
|
||||||
call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject())
|
try {
|
||||||
|
call.resolve(AndroidMailService.sync(account, folder, offset, JSONObject(filters.toString())).toJSObject())
|
||||||
|
} catch (error: Exception) {
|
||||||
|
call.reject(error.message ?: "Could not sync the mailbox.")
|
||||||
|
return@execute
|
||||||
|
}
|
||||||
|
retryOutbox(account)
|
||||||
|
}
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
call.reject(error.message ?: "Could not sync the mailbox.")
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -316,16 +622,26 @@ 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) {
|
||||||
|
if (isConnectivityFailure(error)) {
|
||||||
|
try {
|
||||||
|
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
|
||||||
|
.put("id", UUID.randomUUID().toString())
|
||||||
|
.put("type", "action")
|
||||||
|
.put("data", input))
|
||||||
|
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.")
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
val account = AndroidAccountVault.account()
|
call.reject(error.message ?: "Could not update the message.")
|
||||||
if (account != null && isConnectivityFailure(error)) {
|
|
||||||
AndroidAccountVault.enqueueMailOperation(account.optString("id"), JSONObject()
|
|
||||||
.put("id", UUID.randomUUID().toString())
|
|
||||||
.put("type", "action")
|
|
||||||
.put("data", JSONObject(call.data.toString())))
|
|
||||||
call.resolve(JSObject().put("ok", true).put("queued", true))
|
|
||||||
} else call.reject(error.message ?: "Could not update the message.")
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -423,38 +739,34 @@ class EpMailPlugin : Plugin() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun send(call: PluginCall) {
|
fun send(call: PluginCall) {
|
||||||
val input = JSONObject(call.data.toString()).apply {
|
val input = JSONObject(call.data.toString()).apply {
|
||||||
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
|
if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>")
|
||||||
}
|
}
|
||||||
val warning = try { plaintextSendWarning(input) } catch (error: Exception) {
|
val warning = try { plaintextSendWarning(input) } catch (error: Exception) {
|
||||||
call.reject(error.message ?: "Could not check the OpenPGP send policy.")
|
call.reject(error.message ?: "Could not check the OpenPGP send policy.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (warning == null) {
|
if (warning == null) {
|
||||||
sendPrepared(call, input)
|
sendPrepared(call, input)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val host = activity
|
val rawMime = input.optString("rawBase64").isNotBlank()
|
||||||
host.runOnUiThread {
|
showPgpConfirmation(
|
||||||
AlertDialog.Builder(host)
|
title = if (rawMime) "Send unverified MIME?" else "Send without OpenPGP encryption?",
|
||||||
.setTitle("Send without OpenPGP encryption?")
|
message = warning,
|
||||||
.setMessage(warning)
|
confirmLabel = if (rawMime) "Send anyway" else "Send plaintext",
|
||||||
.setNegativeButton("Cancel") { _, _ ->
|
onConfirmed = { sendPrepared(call, input) },
|
||||||
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
|
onCancelled = {
|
||||||
}
|
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
|
||||||
.setPositiveButton("Send plaintext") { _, _ -> bridge.execute { sendPrepared(call, input) } }
|
}
|
||||||
.setOnCancelListener {
|
)
|
||||||
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
|
}
|
||||||
}
|
|
||||||
.show()
|
private fun sendPrepared(call: PluginCall, input: JSONObject) {
|
||||||
}
|
try {
|
||||||
}
|
val account = AndroidAccountVault.account()
|
||||||
|
?: throw IllegalStateException("Add a mail account before sending.")
|
||||||
private fun sendPrepared(call: PluginCall, input: JSONObject) {
|
|
||||||
try {
|
|
||||||
val account = AndroidAccountVault.account()
|
|
||||||
?: throw IllegalStateException("Add a mail account before sending.")
|
|
||||||
call.resolve(AndroidMailService.send(account, input).toJSObject())
|
call.resolve(AndroidMailService.send(account, input).toJSObject())
|
||||||
} catch (error: Exception) {
|
} catch (error: Exception) {
|
||||||
val account = AndroidAccountVault.account()
|
val account = AndroidAccountVault.account()
|
||||||
@@ -464,36 +776,36 @@ class EpMailPlugin : Plugin() {
|
|||||||
.put("type", "send")
|
.put("type", "send")
|
||||||
.put("data", input))
|
.put("data", input))
|
||||||
call.resolve(JSObject().put("ok", true).put("queued", true))
|
call.resolve(JSObject().put("ok", true).put("queued", true))
|
||||||
} else call.reject(error.message ?: "Could not send the message.")
|
} else call.reject(error.message ?: "Could not send the message.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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) } })
|
||||||
.distinct()
|
.distinct()
|
||||||
val data = AndroidAccountVault.pgpStore()
|
val data = AndroidAccountVault.pgpStore()
|
||||||
val contacts = data.optJSONArray("contacts") ?: JSONArray()
|
val contacts = data.optJSONArray("contacts") ?: JSONArray()
|
||||||
val keys = data.optJSONArray("keys") ?: JSONArray()
|
val keys = data.optJSONArray("keys") ?: JSONArray()
|
||||||
val available = ArrayList<AndroidPgpPolicy.RecipientKey>()
|
val available = ArrayList<AndroidPgpPolicy.RecipientKey>()
|
||||||
for (address in recipients) {
|
for (address in recipients) {
|
||||||
for (index in 0 until contacts.length()) {
|
for (index in 0 until contacts.length()) {
|
||||||
val contact = contacts.optJSONObject(index) ?: continue
|
val contact = contacts.optJSONObject(index) ?: continue
|
||||||
if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) {
|
if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) {
|
||||||
available.add(AndroidPgpPolicy.RecipientKey(address, contact.optString("fingerprint")))
|
available.add(AndroidPgpPolicy.RecipientKey(address, contact.optString("fingerprint")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (index in 0 until keys.length()) {
|
for (index in 0 until keys.length()) {
|
||||||
val key = keys.optJSONObject(index) ?: continue
|
val key = keys.optJSONObject(index) ?: continue
|
||||||
if (key.optString("email").equals(address, true)) {
|
if (key.optString("email").equals(address, true)) {
|
||||||
available.add(AndroidPgpPolicy.RecipientKey(address, key.optString("fingerprint")))
|
available.add(AndroidPgpPolicy.RecipientKey(address, key.optString("fingerprint")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return AndroidPgpPolicy.plaintextSendWarning(recipients, available, input.optBoolean("pgpRequested"))
|
return AndroidPgpPolicy.plaintextSendWarning(recipients, available, input.optBoolean("pgpRequested"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@PluginMethod
|
@PluginMethod
|
||||||
fun listDrafts(call: PluginCall) {
|
fun listDrafts(call: PluginCall) {
|
||||||
@@ -642,17 +954,17 @@ class EpMailPlugin : Plugin() {
|
|||||||
private fun normalizeAccount(input: JSONObject): JSONObject {
|
private fun normalizeAccount(input: JSONObject): JSONObject {
|
||||||
val email = input.optString("email").trim()
|
val email = input.optString("email").trim()
|
||||||
val password = input.optString("password")
|
val password = input.optString("password")
|
||||||
val displayName = input.optString("displayName").trim().take(80)
|
val displayName = input.optString("displayName").trim().take(80)
|
||||||
val imapHost = input.optString("imapHost").trim()
|
val imapHost = input.optString("imapHost").trim()
|
||||||
val smtpHost = input.optString("smtpHost").trim()
|
val smtpHost = input.optString("smtpHost").trim()
|
||||||
val imapPort = input.optInt("imapPort", 143)
|
val imapPort = input.optInt("imapPort", 143)
|
||||||
val smtpPort = input.optInt("smtpPort", 587)
|
val smtpPort = input.optInt("smtpPort", 587)
|
||||||
require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) {
|
require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) {
|
||||||
"Enter a valid email, account display name, password, and both mail server names."
|
"Enter a valid email, account display name, password, and both mail server names."
|
||||||
}
|
}
|
||||||
require(imapPort in 1..65535 && smtpPort in 1..65535) {
|
require(imapPort in 1..65535 && smtpPort in 1..65535) {
|
||||||
"Enter valid IMAP and SMTP ports (1–65535)."
|
"Enter valid IMAP and SMTP ports (1–65535)."
|
||||||
}
|
}
|
||||||
return JSONObject()
|
return JSONObject()
|
||||||
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
|
.put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() })
|
||||||
.put("email", email)
|
.put("email", email)
|
||||||
@@ -666,10 +978,10 @@ class EpMailPlugin : Plugin() {
|
|||||||
require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." }
|
require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." }
|
||||||
})
|
})
|
||||||
.put("rules", normalizeRules(input.optJSONArray("rules")))
|
.put("rules", normalizeRules(input.optJSONArray("rules")))
|
||||||
.put("imapPort", imapPort)
|
.put("imapPort", imapPort)
|
||||||
.put("smtpPort", smtpPort)
|
.put("smtpPort", smtpPort)
|
||||||
.put("imapSecure", input.optBoolean("imapSecure", false))
|
.put("imapSecure", input.optBoolean("imapSecure", false))
|
||||||
.put("smtpSecure", input.optBoolean("smtpSecure", false))
|
.put("smtpSecure", input.optBoolean("smtpSecure", false))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun normalizeRules(input: JSONArray?): JSONArray {
|
private fun normalizeRules(input: JSONArray?): JSONArray {
|
||||||
|
|||||||
@@ -1,23 +1,34 @@
|
|||||||
package studio.daybreak.mail;
|
package studio.daybreak.mail;
|
||||||
|
|
||||||
import android.Manifest;
|
import android.Manifest;
|
||||||
import android.app.KeyguardManager;
|
import android.app.KeyguardManager;
|
||||||
import android.content.Context;
|
import android.content.Context;
|
||||||
import android.content.Intent;
|
import android.content.Intent;
|
||||||
import android.content.pm.PackageManager;
|
import android.content.pm.PackageManager;
|
||||||
import android.graphics.Color;
|
import android.graphics.Color;
|
||||||
|
import android.net.Uri;
|
||||||
import android.os.Build;
|
import android.os.Build;
|
||||||
import android.os.Bundle;
|
import android.os.Bundle;
|
||||||
|
import android.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.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;
|
||||||
@@ -26,13 +37,59 @@ 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 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();
|
||||||
|
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 {
|
||||||
|
AndroidAccountVault.INSTANCE.read();
|
||||||
|
} catch (Exception storageError) {
|
||||||
|
vaultRecoveryRequired = true;
|
||||||
|
createVaultRecoveryOverlay();
|
||||||
|
return;
|
||||||
|
}
|
||||||
createAppLockOverlay();
|
createAppLockOverlay();
|
||||||
if (isAppLockEnabled()) lockWebView();
|
if (isAppLockEnabled()) lockWebView();
|
||||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||||
@@ -43,7 +100,12 @@ public class MainActivity extends BridgeActivity {
|
|||||||
@Override
|
@Override
|
||||||
public void onResume() {
|
public void onResume() {
|
||||||
super.onResume();
|
super.onResume();
|
||||||
|
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();
|
||||||
@@ -53,7 +115,19 @@ public class MainActivity extends BridgeActivity {
|
|||||||
@Override
|
@Override
|
||||||
public void onPause() {
|
public void onPause() {
|
||||||
activityResumed = false;
|
activityResumed = false;
|
||||||
if (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();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,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);
|
||||||
@@ -79,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();
|
||||||
@@ -88,6 +243,77 @@ public class MainActivity extends BridgeActivity {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void hardenWebView() {
|
||||||
|
if (getBridge() == null || getBridge().getWebView() == null) return;
|
||||||
|
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
|
||||||
|
WebView webView = getBridge().getWebView();
|
||||||
|
android.webkit.WebSettings settings = webView.getSettings();
|
||||||
|
settings.setAllowFileAccess(false);
|
||||||
|
settings.setAllowContentAccess(false);
|
||||||
|
settings.setAllowFileAccessFromFileURLs(false);
|
||||||
|
settings.setAllowUniversalAccessFromFileURLs(false);
|
||||||
|
settings.setGeolocationEnabled(false);
|
||||||
|
settings.setJavaScriptCanOpenWindowsAutomatically(false);
|
||||||
|
settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createVaultRecoveryOverlay() {
|
||||||
|
View content = findViewById(android.R.id.content);
|
||||||
|
if (!(content instanceof FrameLayout)) return;
|
||||||
|
FrameLayout overlay = new FrameLayout(this);
|
||||||
|
overlay.setBackgroundColor(Color.rgb(25, 21, 18));
|
||||||
|
overlay.setClickable(true);
|
||||||
|
overlay.setFocusable(true);
|
||||||
|
|
||||||
|
LinearLayout panel = new LinearLayout(this);
|
||||||
|
panel.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
panel.setGravity(Gravity.CENTER);
|
||||||
|
panel.setPadding(dp(28), dp(28), dp(28), dp(28));
|
||||||
|
|
||||||
|
TextView title = new TextView(this);
|
||||||
|
title.setText("Saved data could not be opened");
|
||||||
|
title.setTextColor(Color.rgb(238, 230, 215));
|
||||||
|
title.setTextSize(21);
|
||||||
|
title.setGravity(Gravity.CENTER);
|
||||||
|
panel.addView(title, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
|
||||||
|
|
||||||
|
TextView details = new TextView(this);
|
||||||
|
details.setText("ep-mail could not decrypt its saved local data. It has not been reset or replaced. Try restoring the same device/app state if available. If you cannot recover it, open Android App info and clear ep-mail data to start fresh; this permanently removes saved accounts, cached mail, drafts, queued sends, DAV settings, and OpenPGP keys. Attachments already saved to Downloads remain there.");
|
||||||
|
details.setTextColor(Color.rgb(210, 199, 181));
|
||||||
|
details.setTextSize(14);
|
||||||
|
details.setGravity(Gravity.CENTER);
|
||||||
|
LinearLayout.LayoutParams detailsParams = new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
detailsParams.topMargin = dp(16);
|
||||||
|
panel.addView(details, detailsParams);
|
||||||
|
|
||||||
|
Button settingsButton = new Button(this);
|
||||||
|
settingsButton.setText("Open Android App info");
|
||||||
|
settingsButton.setOnClickListener(view -> {
|
||||||
|
try {
|
||||||
|
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
|
||||||
|
Uri.parse("package:" + getPackageName())));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
// Keep the recovery instructions visible if Settings cannot be launched.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
|
||||||
|
buttonParams.gravity = Gravity.CENTER_HORIZONTAL;
|
||||||
|
buttonParams.topMargin = dp(24);
|
||||||
|
panel.addView(settingsButton, buttonParams);
|
||||||
|
|
||||||
|
overlay.addView(panel, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
|
||||||
|
((FrameLayout) content).addView(overlay, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
|
||||||
|
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
|
if (getBridge() != null && getBridge().getWebView() != null) {
|
||||||
|
getBridge().getWebView().getSettings().setJavaScriptEnabled(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void createAppLockOverlay() {
|
private void createAppLockOverlay() {
|
||||||
View content = findViewById(android.R.id.content);
|
View content = findViewById(android.R.id.content);
|
||||||
if (!(content instanceof FrameLayout)) return;
|
if (!(content instanceof FrameLayout)) return;
|
||||||
@@ -178,6 +404,7 @@ public class MainActivity extends BridgeActivity {
|
|||||||
|
|
||||||
private void lockWebView() {
|
private void lockWebView() {
|
||||||
appLocked = true;
|
appLocked = true;
|
||||||
|
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE);
|
if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE);
|
||||||
if (getBridge() != null) {
|
if (getBridge() != null) {
|
||||||
WebView webView = getBridge().getWebView();
|
WebView webView = getBridge().getWebView();
|
||||||
@@ -188,6 +415,7 @@ public class MainActivity extends BridgeActivity {
|
|||||||
|
|
||||||
private void unlockWebView(boolean reload) {
|
private void unlockWebView(boolean reload) {
|
||||||
appLocked = false;
|
appLocked = false;
|
||||||
|
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
|
||||||
if (getBridge() != null) {
|
if (getBridge() != null) {
|
||||||
WebView webView = getBridge().getWebView();
|
WebView webView = getBridge().getWebView();
|
||||||
webView.getSettings().setJavaScriptEnabled(true);
|
webView.getSettings().setJavaScriptEnabled(true);
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
internal object PgpMessageUid {
|
||||||
|
fun requireValid(value: Any?): Long {
|
||||||
|
require(value is Number) { "That message could not be identified." }
|
||||||
|
val number = value.toDouble()
|
||||||
|
require(number.isFinite() && number >= 1 && number <= 4294967295.0 && number == kotlin.math.floor(number)) {
|
||||||
|
"That message could not be identified."
|
||||||
|
}
|
||||||
|
return number.toLong()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,8 @@ class AndroidMailTransportTest {
|
|||||||
assertEquals("true", properties.getProperty("mail.imap.starttls.enable"))
|
assertEquals("true", properties.getProperty("mail.imap.starttls.enable"))
|
||||||
assertEquals("true", properties.getProperty("mail.imap.starttls.required"))
|
assertEquals("true", properties.getProperty("mail.imap.starttls.required"))
|
||||||
assertEquals("true", properties.getProperty("mail.imap.ssl.checkserveridentity"))
|
assertEquals("true", properties.getProperty("mail.imap.ssl.checkserveridentity"))
|
||||||
|
assertNull(properties.getProperty("mail.imap.ssl.trust"))
|
||||||
|
assertNull(properties.getProperty("mail.imap.ssl.socketFactory"))
|
||||||
assertNull(properties.getProperty("mail.imap.ssl.enable"))
|
assertNull(properties.getProperty("mail.imap.ssl.enable"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25,6 +27,8 @@ class AndroidMailTransportTest {
|
|||||||
assertEquals("imaps", properties.getProperty("mail.store.protocol"))
|
assertEquals("imaps", properties.getProperty("mail.store.protocol"))
|
||||||
assertEquals("true", properties.getProperty("mail.imaps.ssl.enable"))
|
assertEquals("true", properties.getProperty("mail.imaps.ssl.enable"))
|
||||||
assertEquals("true", properties.getProperty("mail.imaps.ssl.checkserveridentity"))
|
assertEquals("true", properties.getProperty("mail.imaps.ssl.checkserveridentity"))
|
||||||
|
assertNull(properties.getProperty("mail.imaps.ssl.trust"))
|
||||||
|
assertNull(properties.getProperty("mail.imaps.ssl.socketFactory"))
|
||||||
assertNull(properties.getProperty("mail.imaps.starttls.required"))
|
assertNull(properties.getProperty("mail.imaps.starttls.required"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,12 +39,16 @@ class AndroidMailTransportTest {
|
|||||||
)
|
)
|
||||||
assertEquals("true", startTls.getProperty("mail.smtp.starttls.enable"))
|
assertEquals("true", startTls.getProperty("mail.smtp.starttls.enable"))
|
||||||
assertEquals("true", startTls.getProperty("mail.smtp.starttls.required"))
|
assertEquals("true", startTls.getProperty("mail.smtp.starttls.required"))
|
||||||
|
assertNull(startTls.getProperty("mail.smtp.ssl.trust"))
|
||||||
|
assertNull(startTls.getProperty("mail.smtp.ssl.socketFactory"))
|
||||||
|
|
||||||
val implicitTls = AndroidMailTransport.smtpProperties(
|
val implicitTls = AndroidMailTransport.smtpProperties(
|
||||||
MailServerConnection("smtp.example.test", 465, true)
|
MailServerConnection("smtp.example.test", 465, true)
|
||||||
)
|
)
|
||||||
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.enable"))
|
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.enable"))
|
||||||
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.checkserveridentity"))
|
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.checkserveridentity"))
|
||||||
|
assertNull(implicitTls.getProperty("mail.smtp.ssl.trust"))
|
||||||
|
assertNull(implicitTls.getProperty("mail.smtp.ssl.socketFactory"))
|
||||||
assertNull(implicitTls.getProperty("mail.smtp.starttls.required"))
|
assertNull(implicitTls.getProperty("mail.smtp.starttls.required"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidPgpConfirmationGateTest {
|
||||||
|
@Test
|
||||||
|
fun cancelDoesNotRunProtectedActionAndCannotBeOverriddenLater() {
|
||||||
|
var prompt: AndroidPgpConfirmationGate.Prompt? = null
|
||||||
|
var protectedActionCount = 0
|
||||||
|
var cancelCount = 0
|
||||||
|
val gate = AndroidPgpConfirmationGate(
|
||||||
|
showPrompt = { prompt = it },
|
||||||
|
dispatch = { action -> action() }
|
||||||
|
)
|
||||||
|
|
||||||
|
gate.request(
|
||||||
|
title = "Confirm key change",
|
||||||
|
message = "Check the fingerprint",
|
||||||
|
confirmLabel = "Confirm",
|
||||||
|
onConfirmed = { protectedActionCount += 1 },
|
||||||
|
onCancelled = { cancelCount += 1 }
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(0, protectedActionCount)
|
||||||
|
assertEquals(0, cancelCount)
|
||||||
|
assertNotNull(prompt)
|
||||||
|
prompt!!.cancel()
|
||||||
|
prompt!!.confirm()
|
||||||
|
prompt!!.cancel()
|
||||||
|
|
||||||
|
assertEquals(0, protectedActionCount)
|
||||||
|
assertEquals(1, cancelCount)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun confirmRunsProtectedActionExactlyOnce() {
|
||||||
|
var prompt: AndroidPgpConfirmationGate.Prompt? = null
|
||||||
|
var protectedActionCount = 0
|
||||||
|
var cancelCount = 0
|
||||||
|
val gate = AndroidPgpConfirmationGate(
|
||||||
|
showPrompt = { prompt = it },
|
||||||
|
dispatch = { action -> action() }
|
||||||
|
)
|
||||||
|
|
||||||
|
gate.request(
|
||||||
|
title = "Send plaintext?",
|
||||||
|
message = "The message will not be encrypted",
|
||||||
|
confirmLabel = "Send plaintext",
|
||||||
|
onConfirmed = { protectedActionCount += 1 },
|
||||||
|
onCancelled = { cancelCount += 1 }
|
||||||
|
)
|
||||||
|
|
||||||
|
assertNotNull(prompt)
|
||||||
|
assertEquals("Send plaintext", prompt!!.confirmLabel)
|
||||||
|
prompt!!.confirm()
|
||||||
|
prompt!!.confirm()
|
||||||
|
prompt!!.cancel()
|
||||||
|
|
||||||
|
assertEquals(1, protectedActionCount)
|
||||||
|
assertEquals(0, cancelCount)
|
||||||
|
assertTrue(prompt!!.message.contains("not be encrypted"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Properties
|
||||||
|
import javax.mail.Session
|
||||||
|
import javax.mail.internet.MimeMessage
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Assume.assumeTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidPgpMimeValidationTest {
|
||||||
|
private fun message(contentType: String, parts: String): MimeMessage {
|
||||||
|
val source = "MIME-Version: 1.0\r\nContent-Type: $contentType; boundary=\"test\"\r\n\r\n$parts"
|
||||||
|
return MimeMessage(Session.getInstance(Properties()), ByteArrayInputStream(source.toByteArray(Charsets.UTF_8)))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun encrypted(version: String = "Version: 1", partType: String = "application/octet-stream", armor: String = "-----BEGIN PGP MESSAGE-----\r\nabc\r\n-----END PGP MESSAGE-----"): MimeMessage =
|
||||||
|
message("multipart/encrypted; protocol=\"application/pgp-encrypted\"",
|
||||||
|
"--test\r\nContent-Type: application/pgp-encrypted\r\n\r\n$version\r\n" +
|
||||||
|
"--test\r\nContent-Type: $partType\r\n\r\n$armor\r\n--test--\r\n")
|
||||||
|
|
||||||
|
private fun signed(armor: String = "-----BEGIN PGP SIGNATURE-----\r\nabc\r\n-----END PGP SIGNATURE-----"): MimeMessage =
|
||||||
|
message("multipart/signed; protocol=\"application/pgp-signature\"",
|
||||||
|
"--test\r\nContent-Type: text/plain\r\n\r\nhello\r\n" +
|
||||||
|
"--test\r\nContent-Type: application/pgp-signature\r\n\r\n$armor\r\n--test--\r\n")
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun acceptsValidEncryptedAndSignedMime() {
|
||||||
|
AndroidMailService.validateOpenPgpMime(encrypted())
|
||||||
|
AndroidMailService.validateOpenPgpMime(signed())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rejectsMalformedEncryptedAndSignedMime() {
|
||||||
|
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(version = "Version: 2")) }
|
||||||
|
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(partType = "text/plain")) }
|
||||||
|
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(encrypted(armor = "missing armor")) }
|
||||||
|
assertThrows(IllegalArgumentException::class.java) { AndroidMailService.validateOpenPgpMime(signed(armor = "missing signature")) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun acceptsMimeGeneratedByAndroidOpenPgpBuilder() {
|
||||||
|
val directory = System.getenv("EP_MAIL_PGP_MIME_FIXTURE_DIR")
|
||||||
|
assumeTrue("Set EP_MAIL_PGP_MIME_FIXTURE_DIR to run the JavaScript-to-JavaMail integration test.", !directory.isNullOrBlank())
|
||||||
|
for (name in listOf("encrypted", "signed", "encrypted-signed")) {
|
||||||
|
val file = File(directory, "$name.eml")
|
||||||
|
val parsed = file.inputStream().use { MimeMessage(Session.getInstance(Properties()), it) }
|
||||||
|
AndroidMailService.validateOpenPgpMime(parsed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,14 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class AndroidVaultKeyPolicyTest {
|
||||||
|
@Test
|
||||||
|
fun newKeyMayBeCreatedOnlyWhenThereIsNoEncryptedStore() {
|
||||||
|
assertTrue(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = false))
|
||||||
|
assertFalse(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = true))
|
||||||
|
assertTrue(AndroidVaultKeyPolicy.MISSING_KEY_MESSAGE.contains("not reset or replaced"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class BoundedInputReaderTest {
|
||||||
|
@Test
|
||||||
|
fun readsOnlyUpToTheRequestedLimit() {
|
||||||
|
val input = ByteArrayInputStream(byteArrayOf(1, 2, 3, 4, 5))
|
||||||
|
assertArrayEquals(byteArrayOf(1, 2, 3), BoundedInputReader.read(input, 3))
|
||||||
|
assertEquals(2, input.available())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun readsShortStreamsToEnd() {
|
||||||
|
assertArrayEquals(
|
||||||
|
byteArrayOf(1, 2),
|
||||||
|
BoundedInputReader.read(ByteArrayInputStream(byteArrayOf(1, 2)), 5)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package studio.daybreak.mail
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class PgpMessageUidTest {
|
||||||
|
@Test
|
||||||
|
fun acceptsJsonIntegerAndLongUids() {
|
||||||
|
assertEquals(42L, PgpMessageUid.requireValid(42))
|
||||||
|
assertEquals(42L, PgpMessageUid.requireValid(42L))
|
||||||
|
assertEquals(4294967295L, PgpMessageUid.requireValid(4294967295L))
|
||||||
|
assertEquals(42L, PgpMessageUid.requireValid(42.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun rejectsMissingAndInvalidUids() {
|
||||||
|
for (value in listOf(null, "42", 0, -1, 1.5, Double.NaN, Double.POSITIVE_INFINITY, 4294967296L)) {
|
||||||
|
assertThrows(IllegalArgumentException::class.java) { PgpMessageUid.requireValid(value) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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); },
|
||||||
|
|||||||
+12
-7
@@ -1,3 +1,5 @@
|
|||||||
|
const { BUILTIN_SERVER_IDS } = require('../pgp-keyservers.cjs');
|
||||||
|
|
||||||
function pgpFailure(error) {
|
function pgpFailure(error) {
|
||||||
return {
|
return {
|
||||||
failed: true,
|
failed: true,
|
||||||
@@ -207,12 +209,12 @@ function registerPgpIpcHandlers({
|
|||||||
});
|
});
|
||||||
registerIpcHandler('pgp:key-servers', async () => {
|
registerIpcHandler('pgp:key-servers', async () => {
|
||||||
const settings = await pgpKeys.getSettings();
|
const settings = await pgpKeys.getSettings();
|
||||||
return listServers(settings.customKeyServers, settings.enabledKeyServers);
|
return listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
|
||||||
});
|
});
|
||||||
registerIpcHandler('pgp:set-key-server-enabled', async (_event, input) => {
|
registerIpcHandler('pgp:set-key-server-enabled', async (_event, input) => {
|
||||||
if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
|
if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
|
||||||
const settings = await pgpKeys.getSettings();
|
const settings = await pgpKeys.getSettings();
|
||||||
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
|
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
|
||||||
const serverId = String(input?.serverId || '');
|
const serverId = String(input?.serverId || '');
|
||||||
if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.');
|
if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.');
|
||||||
const enabled = new Set(settings.enabledKeyServers);
|
const enabled = new Set(settings.enabledKeyServers);
|
||||||
@@ -221,7 +223,8 @@ function registerPgpIpcHandlers({
|
|||||||
await pgpKeys.setSettings({
|
await pgpKeys.setSettings({
|
||||||
cacheMinutes: settings.cacheMinutes,
|
cacheMinutes: settings.cacheMinutes,
|
||||||
customKeyServers: settings.customKeyServers,
|
customKeyServers: settings.customKeyServers,
|
||||||
enabledKeyServers: [...enabled]
|
enabledKeyServers: [...enabled],
|
||||||
|
removedBuiltinKeyServers: settings.removedBuiltinKeyServers
|
||||||
});
|
});
|
||||||
return { serverId, enabled: input.enabled };
|
return { serverId, enabled: input.enabled };
|
||||||
});
|
});
|
||||||
@@ -256,23 +259,25 @@ function registerPgpIpcHandlers({
|
|||||||
const id = String(serverId || '');
|
const id = String(serverId || '');
|
||||||
const settings = await pgpKeys.getSettings();
|
const settings = await pgpKeys.getSettings();
|
||||||
const customServers = settings.customKeyServers.filter(server => server.id !== id);
|
const customServers = settings.customKeyServers.filter(server => server.id !== id);
|
||||||
if (customServers.length === settings.customKeyServers.length) throw new Error('That custom key server was not found.');
|
const removesBuiltin = BUILTIN_SERVER_IDS.includes(id) && !settings.removedBuiltinKeyServers.includes(id);
|
||||||
|
if (customServers.length === settings.customKeyServers.length && !removesBuiltin) throw new Error('That key server was not found.');
|
||||||
await pgpKeys.setSettings({
|
await pgpKeys.setSettings({
|
||||||
cacheMinutes: settings.cacheMinutes,
|
cacheMinutes: settings.cacheMinutes,
|
||||||
customKeyServers,
|
customKeyServers: customServers,
|
||||||
|
removedBuiltinKeyServers: removesBuiltin ? [...settings.removedBuiltinKeyServers, id] : settings.removedBuiltinKeyServers,
|
||||||
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id)
|
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id)
|
||||||
});
|
});
|
||||||
return { removed: true };
|
return { removed: true };
|
||||||
});
|
});
|
||||||
registerIpcHandler('pgp:find-key', async (_event, input) => {
|
registerIpcHandler('pgp:find-key', async (_event, input) => {
|
||||||
const settings = await pgpKeys.getSettings();
|
const settings = await pgpKeys.getSettings();
|
||||||
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
|
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
|
||||||
return pgpKeyServers.lookupEnabled(servers, input?.email);
|
return pgpKeyServers.lookupEnabled(servers, input?.email);
|
||||||
});
|
});
|
||||||
registerIpcHandler('pgp:publish-key', async (event, input) => {
|
registerIpcHandler('pgp:publish-key', async (event, input) => {
|
||||||
const fingerprint = pgpFingerprint(input?.fingerprint);
|
const fingerprint = pgpFingerprint(input?.fingerprint);
|
||||||
const settings = await pgpKeys.getSettings();
|
const settings = await pgpKeys.getSettings();
|
||||||
const server = listServers(settings.customKeyServers, settings.enabledKeyServers).find(item => item.id === String(input?.serverId || ''));
|
const server = listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers).find(item => item.id === String(input?.serverId || ''));
|
||||||
if (!server) throw new Error('Choose a configured key server.');
|
if (!server) throw new Error('Choose a configured key server.');
|
||||||
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
|
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
|
||||||
const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint);
|
const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint);
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ const MAX_CUSTOM_SERVERS = 10;
|
|||||||
|
|
||||||
const BUILTIN_SERVERS = [
|
const BUILTIN_SERVERS = [
|
||||||
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
|
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
|
||||||
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true }
|
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true },
|
||||||
|
{ id: 'eternity-vks', name: 'keys.eternityproject.fi', url: 'https://keys.eternityproject.fi', protocol: 'vks', builtin: true }
|
||||||
];
|
];
|
||||||
|
const BUILTIN_SERVER_IDS = BUILTIN_SERVERS.map(server => server.id);
|
||||||
|
|
||||||
function normalizeBaseUrl(value) {
|
function normalizeBaseUrl(value) {
|
||||||
const raw = String(value || '').trim();
|
const raw = String(value || '').trim();
|
||||||
@@ -40,10 +42,11 @@ function normalizeCustomServer(input) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function listServers(customServers = [], enabledServerIds = []) {
|
function listServers(customServers = [], enabledServerIds = [], removedBuiltinIds = []) {
|
||||||
const enabled = new Set(enabledServerIds);
|
const enabled = new Set(enabledServerIds);
|
||||||
|
const removed = new Set(removedBuiltinIds);
|
||||||
return [
|
return [
|
||||||
...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })),
|
...BUILTIN_SERVERS.filter(server => !removed.has(server.id)).map(server => ({ ...server, enabled: enabled.has(server.id) })),
|
||||||
...customServers.map(server => {
|
...customServers.map(server => {
|
||||||
const normalized = normalizeCustomServer(server);
|
const normalized = normalizeCustomServer(server);
|
||||||
return { ...normalized, enabled: enabled.has(normalized.id) };
|
return { ...normalized, enabled: enabled.has(normalized.id) };
|
||||||
@@ -72,14 +75,17 @@ async function readResponseText(response) {
|
|||||||
const chunks = [];
|
const chunks = [];
|
||||||
let length = 0;
|
let length = 0;
|
||||||
for await (const chunk of response.body) {
|
for await (const chunk of response.body) {
|
||||||
const bytes = Buffer.from(chunk);
|
const bytes = typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;
|
||||||
length += bytes.length;
|
length += bytes.length;
|
||||||
if (length > MAX_RESPONSE_BYTES) {
|
if (length > MAX_RESPONSE_BYTES) {
|
||||||
throw new Error('The key server response is too large.');
|
throw new Error('The key server response is too large.');
|
||||||
}
|
}
|
||||||
chunks.push(bytes);
|
chunks.push(bytes);
|
||||||
}
|
}
|
||||||
return Buffer.concat(chunks, length).toString('utf8');
|
const joined = new Uint8Array(length);
|
||||||
|
let offset = 0;
|
||||||
|
for (const bytes of chunks) { joined.set(bytes, offset); offset += bytes.length; }
|
||||||
|
return new TextDecoder().decode(joined);
|
||||||
}
|
}
|
||||||
|
|
||||||
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
||||||
@@ -269,6 +275,7 @@ function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
BUILTIN_SERVERS,
|
BUILTIN_SERVERS,
|
||||||
|
BUILTIN_SERVER_IDS,
|
||||||
MAX_CUSTOM_SERVERS,
|
MAX_CUSTOM_SERVERS,
|
||||||
createKeyServerService,
|
createKeyServerService,
|
||||||
listServers,
|
listServers,
|
||||||
|
|||||||
@@ -198,11 +198,14 @@ function createKeyStore(storage) {
|
|||||||
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
|
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
|
||||||
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
|
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
|
||||||
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
|
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
|
||||||
|
: [],
|
||||||
|
removedBuiltinKeyServers: Array.isArray(settings.removedBuiltinKeyServers)
|
||||||
|
? [...new Set(settings.removedBuiltinKeyServers.filter(id => typeof id === 'string'))]
|
||||||
: []
|
: []
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) {
|
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers, removedBuiltinKeyServers }) {
|
||||||
const minutes = Number(cacheMinutes);
|
const minutes = Number(cacheMinutes);
|
||||||
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
||||||
const data = await read();
|
const data = await read();
|
||||||
@@ -224,11 +227,18 @@ function createKeyStore(storage) {
|
|||||||
}
|
}
|
||||||
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
|
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
|
||||||
}
|
}
|
||||||
|
if (removedBuiltinKeyServers !== undefined) {
|
||||||
|
if (!Array.isArray(removedBuiltinKeyServers) || removedBuiltinKeyServers.length > 12 || removedBuiltinKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
|
||||||
|
throw new Error('Choose no more than 12 valid built-in key servers to remove.');
|
||||||
|
}
|
||||||
|
data.settings.removedBuiltinKeyServers = [...new Set(removedBuiltinKeyServers)];
|
||||||
|
}
|
||||||
await storage.save(data);
|
await storage.save(data);
|
||||||
return {
|
return {
|
||||||
cacheMinutes: data.settings.cacheMinutes,
|
cacheMinutes: data.settings.cacheMinutes,
|
||||||
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
|
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
|
||||||
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : []
|
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : [],
|
||||||
|
removedBuiltinKeyServers: Array.isArray(data.settings.removedBuiltinKeyServers) ? [...data.settings.removedBuiltinKeyServers] : []
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
+256
-54
@@ -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 || '';
|
||||||
@@ -566,6 +595,7 @@ function setupDraftComposer() {
|
|||||||
contentBase64: btoa(binary)
|
contentBase64: btoa(binary)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (closed) return;
|
||||||
attachments.push(...selected);
|
attachments.push(...selected);
|
||||||
renderAttachments();
|
renderAttachments();
|
||||||
await persist();
|
await persist();
|
||||||
@@ -592,65 +622,78 @@ function setupDraftComposer() {
|
|||||||
modal.querySelector('.compose-footer').insertBefore(save, selectMailUi('#send'));
|
modal.querySelector('.compose-footer').insertBefore(save, selectMailUi('#send'));
|
||||||
let saveTimer;
|
let saveTimer;
|
||||||
let closed = false;
|
let closed = false;
|
||||||
const persist = async () => {
|
let pendingSave = Promise.resolve();
|
||||||
if (closed || !selectMailUi('#compose-to')) return;
|
const persist = () => {
|
||||||
|
if (closed || !modal.isConnected) return Promise.resolve(false);
|
||||||
const values = {
|
const values = {
|
||||||
id: modal.dataset.draftId || window.crypto.randomUUID(),
|
to: modal.querySelector('#compose-to').value,
|
||||||
to: selectMailUi('#compose-to').value,
|
cc: modal.querySelector('#compose-cc').value,
|
||||||
cc: selectMailUi('#compose-cc').value,
|
subject: modal.querySelector('#compose-subject').value,
|
||||||
subject: selectMailUi('#compose-subject').value,
|
text: modal.querySelector('#compose-body').value,
|
||||||
text: selectMailUi('#compose-body').value,
|
attachments: [...attachments]
|
||||||
attachments
|
|
||||||
};
|
};
|
||||||
if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
|
if (!modal.dataset.draftId && ![values.to, values.cc, values.subject, values.text].some(value => value.trim()) && !values.attachments.length) return Promise.resolve(false);
|
||||||
|
values.id = modal.dataset.draftId || window.crypto.randomUUID();
|
||||||
modal.dataset.draftId = values.id;
|
modal.dataset.draftId = values.id;
|
||||||
const result = await window.daybreakMail.saveDraft(values);
|
const operation = pendingSave.then(async () => {
|
||||||
modal.dataset.draftId = result.id;
|
await window.daybreakMail.saveDraft(values);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
pendingSave = operation.then(() => {}, () => {});
|
||||||
|
return operation;
|
||||||
};
|
};
|
||||||
save.onclick = async () => {
|
save.onclick = async () => {
|
||||||
try {
|
try {
|
||||||
await persist();
|
const saved = await persist();
|
||||||
toastMailUi('Draft saved on this device');
|
toastMailUi(saved ? 'Draft saved on this device' : 'Nothing to save in this draft');
|
||||||
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
if (saved && rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
||||||
} catch (error) { toastMailUi(error.message || 'Could not save draft'); }
|
} catch (error) { toastMailUi(error.message || 'Could not save draft'); }
|
||||||
};
|
};
|
||||||
modal.addEventListener('input', () => {
|
modal.addEventListener('input', () => {
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
saveTimer = setTimeout(() => persist().catch(error => toastMailUi(error.message || 'Could not save draft')), 700);
|
saveTimer = setTimeout(() => persist().catch(error => toastMailUi(error.message || 'Could not save draft')), 700);
|
||||||
});
|
});
|
||||||
modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
|
const saveAndClose = () => {
|
||||||
if (!event.target.classList.contains('modal-overlay')) return;
|
if (closed) return;
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
|
persist().then(saved => { if (saved && rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
|
||||||
.catch(error => toastMailUi(error.message || 'Could not save draft'));
|
.catch(error => toastMailUi(error.message || 'Could not save draft'));
|
||||||
closed = true;
|
closed = true;
|
||||||
|
};
|
||||||
|
root.querySelector('.modal-overlay')?.addEventListener('click', event => {
|
||||||
|
if (!event.target.classList.contains('modal-overlay')) return;
|
||||||
|
saveAndClose();
|
||||||
}, true);
|
}, true);
|
||||||
root.querySelector('.modal-close')?.addEventListener('click', () => {
|
root.querySelector('.modal-close')?.addEventListener('click', saveAndClose, true);
|
||||||
clearTimeout(saveTimer);
|
modal.addEventListener('keydown', event => {
|
||||||
persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
|
if (event.key === 'Escape') saveAndClose();
|
||||||
.catch(error => toastMailUi(error.message || 'Could not save draft'));
|
});
|
||||||
closed = true;
|
const deleteSavedDraft = async () => {
|
||||||
}, true);
|
|
||||||
selectMailUi('#discard').onclick = async () => {
|
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
closed = true;
|
closed = true;
|
||||||
|
await pendingSave;
|
||||||
|
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
|
||||||
|
};
|
||||||
|
modal._deleteSavedDraft = deleteSavedDraft;
|
||||||
|
selectMailUi('#discard').onclick = async () => {
|
||||||
try {
|
try {
|
||||||
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
|
await deleteSavedDraft();
|
||||||
root.innerHTML = '';
|
root.innerHTML = '';
|
||||||
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
||||||
} catch (error) { toastMailUi(error.message || 'Could not delete draft'); }
|
} catch (error) { toastMailUi(error.message || 'Could not delete draft'); }
|
||||||
};
|
};
|
||||||
selectMailUi('#send').addEventListener('click', () => {
|
|
||||||
clearTimeout(saveTimer);
|
|
||||||
closed = true;
|
|
||||||
}, true);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
mailFeatureState.syncQueued = true;
|
if (!isAndroid || mailFeatureState.syncMailboxKey === mailboxKey) {
|
||||||
return mailFeatureState.syncPromise;
|
mailFeatureState.syncQueued = true;
|
||||||
|
return mailFeatureState.syncPromise;
|
||||||
|
}
|
||||||
|
mailFeatureState.syncQueued = false;
|
||||||
}
|
}
|
||||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
||||||
openMailAccount();
|
openMailAccount();
|
||||||
@@ -658,19 +701,88 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
}
|
}
|
||||||
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 +791,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 selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
else {
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
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 (refresh) refresh.disabled = false;
|
if (!isAndroid || mailFeatureState.syncRequest === request) {
|
||||||
|
if (refresh) refresh.disabled = false;
|
||||||
|
if (loadMoreButton) loadMoreButton.disabled = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
})();
|
})();
|
||||||
@@ -713,12 +853,66 @@ 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) {
|
||||||
@@ -777,7 +971,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 +979,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 +1021,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;
|
||||||
@@ -860,15 +1062,15 @@ if (window.daybreakMail) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.queued) {
|
if (result.queued) {
|
||||||
const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
|
const modal = selectMailUi('#modal-root .compose-modal');
|
||||||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
if (modal?._deleteSavedDraft) await modal._deleteSavedDraft();
|
||||||
selectMailUi('#modal-root').innerHTML = '';
|
selectMailUi('#modal-root').innerHTML = '';
|
||||||
toastMailUi('Offline: message queued and will send when connected');
|
toastMailUi('Offline: message queued and will send when connected');
|
||||||
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
|
const modal = selectMailUi('#modal-root .compose-modal');
|
||||||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
if (modal?._deleteSavedDraft) await modal._deleteSavedDraft();
|
||||||
selectMailUi('#modal-root').innerHTML = '';
|
selectMailUi('#modal-root').innerHTML = '';
|
||||||
toastMailUi(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
|
toastMailUi(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
|
||||||
if (rendererState.activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
|
if (rendererState.activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.8",
|
"version": "0.5.23",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.8",
|
"version": "0.5.23",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@capacitor/android": "^8.5.2",
|
"@capacitor/android": "^8.5.2",
|
||||||
"@capacitor/core": "^8.5.2",
|
"@capacitor/core": "^8.5.2",
|
||||||
|
|||||||
+2
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.5.8",
|
"version": "0.5.23",
|
||||||
"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",
|
||||||
@@ -26,6 +26,7 @@
|
|||||||
"android:open": "npm run android:sync && cap open android",
|
"android:open": "npm run android:sync && cap open android",
|
||||||
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
|
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
|
||||||
"android:release-apk": "npm run android:sync && node scripts/build-android-release-apk.cjs",
|
"android:release-apk": "npm run android:sync && node scripts/build-android-release-apk.cjs",
|
||||||
|
"build": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build.ps1",
|
||||||
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
|
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
+194
-165
@@ -6,164 +6,193 @@ const selectAllPgpMailUi = pgpMailUi.selectAll;
|
|||||||
const toastPgpMailUi = pgpMailUi.toast;
|
const toastPgpMailUi = pgpMailUi.toast;
|
||||||
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
||||||
const pgpApi = () => window.daybreakMail?.pgp;
|
const pgpApi = () => window.daybreakMail?.pgp;
|
||||||
|
|
||||||
function pgpAskPassphrase(title, detail) {
|
function pgpAskPassphrase(title, detail) {
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
const overlay = document.createElement('div');
|
const overlay = document.createElement('div');
|
||||||
overlay.className = 'modal-overlay pgp-prompt';
|
overlay.className = 'modal-overlay pgp-prompt';
|
||||||
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
||||||
overlay.querySelector('.modal-head span').textContent = title;
|
overlay.querySelector('.modal-head span').textContent = title;
|
||||||
overlay.querySelector('.account-note').textContent = detail;
|
overlay.querySelector('.account-note').textContent = detail;
|
||||||
const finish = value => { overlay.remove(); resolve(value); };
|
const finish = value => { overlay.remove(); resolve(value); };
|
||||||
overlay.querySelector('form').onsubmit = event => {
|
overlay.querySelector('form').onsubmit = event => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const value = overlay.querySelector('input').value;
|
const value = overlay.querySelector('input').value;
|
||||||
if (value) finish(value);
|
if (value) finish(value);
|
||||||
};
|
};
|
||||||
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
||||||
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
||||||
document.body.append(overlay);
|
document.body.append(overlay);
|
||||||
overlay.querySelector('input').focus();
|
overlay.querySelector('input').focus();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpFormatFingerprint(value) {
|
function pgpFormatFingerprint(value) {
|
||||||
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpSignatureHtml(signatures, encrypted) {
|
function pgpSignatureHtml(signatures, encrypted) {
|
||||||
const items = Array.isArray(signatures) ? signatures : [];
|
const items = Array.isArray(signatures) ? signatures : [];
|
||||||
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
||||||
}
|
}
|
||||||
return items.map(signature => {
|
return items.map(signature => {
|
||||||
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
||||||
const notes = [];
|
const notes = [];
|
||||||
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
||||||
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
||||||
if (signature.status === 'valid') {
|
if (signature.status === 'valid') {
|
||||||
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
||||||
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
||||||
}
|
}
|
||||||
if (signature.status === 'unknown-key') {
|
if (signature.status === 'unknown-key') {
|
||||||
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
||||||
}
|
}
|
||||||
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
||||||
}).join('');
|
}).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpAddAttachedKey(key) {
|
async function pgpAddAttachedKey(key) {
|
||||||
const emails = key.emails.join(', ') || 'unknown address';
|
const emails = key.emails.join(', ') || 'unknown address';
|
||||||
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
||||||
try {
|
try {
|
||||||
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
||||||
toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastPgpMailUi(error.message || 'Could not add the key');
|
toastPgpMailUi(error.message || 'Could not add the key');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpRenderReaderState(message) {
|
function pgpRenderReaderState(message) {
|
||||||
const reader = selectPgpMailUi('#reader-pane');
|
const reader = selectPgpMailUi('#reader-pane');
|
||||||
const header = reader.querySelector('.reader-header');
|
const header = reader.querySelector('.reader-header');
|
||||||
if (!header) return;
|
if (!header) return;
|
||||||
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
||||||
let html = '';
|
let html = '';
|
||||||
if (message.encrypted && !message.pgpDecrypted) {
|
if (message.encrypted && !message.pgpDecrypted) {
|
||||||
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
||||||
} else if (message.encrypted) {
|
} else if (message.encrypted) {
|
||||||
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
||||||
} else if (message.pgpSignatures) {
|
} else if (message.signed && Array.isArray(message.pgpSignatures)) {
|
||||||
html = pgpSignatureHtml(message.pgpSignatures, false);
|
html = pgpSignatureHtml(message.pgpSignatures, false);
|
||||||
}
|
} else if (message.signed && message.pgpVerifyFailed) {
|
||||||
const keys = message.pgpResult?.attachedKeys || [];
|
html = `<section class="pgp-status pgp-warn" role="status"><strong>Could not check the OpenPGP signature</strong><span>${escapePgpMailUi(message.pgpVerifyFailed)}</span></section>`;
|
||||||
|
} else if (message.signed) {
|
||||||
|
html = '<section class="pgp-status pgp-warn" role="status"><strong>Checking OpenPGP signature…</strong><span>Do not rely on this message until verification completes.</span></section>';
|
||||||
|
} else if (message.pgpSignatures) {
|
||||||
|
html = pgpSignatureHtml(message.pgpSignatures, false);
|
||||||
|
}
|
||||||
|
const keys = message.pgpResult?.attachedKeys || [];
|
||||||
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
||||||
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
||||||
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
||||||
});
|
});
|
||||||
const unlock = selectPgpMailUi('#pgp-unlock');
|
const unlock = selectPgpMailUi('#pgp-unlock');
|
||||||
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpUnlockMessage(message, interactive) {
|
async function pgpUnlockMessage(message, interactive) {
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastPgpMailUi(error.message || 'Could not open this message');
|
toastPgpMailUi(error.message || 'Could not open this message');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
Object.assign(message, {
|
Object.assign(message, {
|
||||||
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
||||||
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
||||||
});
|
});
|
||||||
if (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'
|
||||||
if (passphrase === null) return;
|
? 'That passphrase was incorrect. Try again.'
|
||||||
continue;
|
: result.code === 'BIOMETRIC_INVALIDATED'
|
||||||
}
|
? `${result.message} Enter the passphrase to continue.`
|
||||||
const text = selectPgpMailUi('#pgp-banner-text');
|
: `Enter the passphrase for ${result.email || 'your key'}.`;
|
||||||
if (text) text.textContent = result.message;
|
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
|
||||||
else toastPgpMailUi(result.message);
|
if (passphrase === null) return;
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
const text = selectPgpMailUi('#pgp-banner-text');
|
||||||
|
if (text) text.textContent = result.message;
|
||||||
|
else toastPgpMailUi(result.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pgpVerifyMessage(message) {
|
||||||
|
try {
|
||||||
|
const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid });
|
||||||
|
if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.';
|
||||||
|
else {
|
||||||
|
message.pgpSignatures = result.signatures || [];
|
||||||
|
message.pgpVerifyFailed = null;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
message.pgpVerifyFailed = error.message || 'The signature could not be checked.';
|
||||||
|
}
|
||||||
|
if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message);
|
||||||
|
}
|
||||||
|
|
||||||
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = pgpMailUi.state.messages.find(item => item.id === id);
|
const message = pgpMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message || !pgpApi()) return;
|
if (!message || !pgpApi()) return;
|
||||||
pgpRenderReaderState(message);
|
pgpRenderReaderState(message);
|
||||||
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
||||||
message.pgpAutoTried = true;
|
message.pgpAutoTried = true;
|
||||||
void pgpUnlockMessage(message, false);
|
void pgpUnlockMessage(message, false);
|
||||||
}
|
}
|
||||||
|
if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) {
|
||||||
|
message.pgpVerifyTried = true;
|
||||||
|
void pgpVerifyMessage(message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Compose: encrypt/sign options.
|
// Compose: encrypt/sign options.
|
||||||
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false, draft = null) {
|
||||||
baseShowCompose(reply, forward);
|
baseShowCompose(reply, forward, draft);
|
||||||
const footer = selectPgpMailUi('#modal-root .compose-footer');
|
const footer = selectPgpMailUi('#modal-root .compose-footer');
|
||||||
if (!footer || !pgpApi()) return;
|
if (!footer || !pgpApi()) return;
|
||||||
const box = document.createElement('div');
|
const box = document.createElement('div');
|
||||||
box.className = 'pgp-compose';
|
box.className = 'pgp-compose';
|
||||||
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
|
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
|
||||||
footer.prepend(box);
|
footer.prepend(box);
|
||||||
let touched = false;
|
let touched = false;
|
||||||
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
||||||
const sign = selectPgpMailUi('#pgp-sign');
|
const sign = selectPgpMailUi('#pgp-sign');
|
||||||
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
||||||
if (touched) encrypt.dataset.touched = '1';
|
if (touched) encrypt.dataset.touched = '1';
|
||||||
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
||||||
let timer = null;
|
let timer = null;
|
||||||
const refresh = async () => {
|
const refresh = async () => {
|
||||||
const to = selectPgpMailUi('#compose-to')?.value || '';
|
const to = selectPgpMailUi('#compose-to')?.value || '';
|
||||||
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
||||||
const hint = selectPgpMailUi('#pgp-hint');
|
const hint = selectPgpMailUi('#pgp-hint');
|
||||||
if (!hint) return;
|
if (!hint) return;
|
||||||
if (!to.trim()) { hint.textContent = ''; return; }
|
if (!to.trim()) { hint.textContent = ''; return; }
|
||||||
try {
|
try {
|
||||||
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
||||||
if (!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 = ''; }
|
||||||
};
|
};
|
||||||
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
||||||
['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
|
['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
|
||||||
sign.addEventListener('change', schedule);
|
sign.addEventListener('change', schedule);
|
||||||
schedule();
|
schedule();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
||||||
@@ -172,30 +201,30 @@ async function prepareSend(to, cc) {
|
|||||||
const plaintextFallback = () => pgpApi().platform === 'android'
|
const plaintextFallback = () => pgpApi().platform === 'android'
|
||||||
? { encrypt: false, sign: false, plaintextFallback: true }
|
? { encrypt: false, sign: false, plaintextFallback: true }
|
||||||
: null;
|
: null;
|
||||||
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
||||||
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
||||||
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
||||||
const status = await pgpApi().checkSend({ to, cc, sign });
|
const status = await pgpApi().checkSend({ to, cc, sign });
|
||||||
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
||||||
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
||||||
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
||||||
if (!sign) return plaintextFallback();
|
if (!sign) return plaintextFallback();
|
||||||
} else return false;
|
} else return false;
|
||||||
}
|
}
|
||||||
if (!encrypt && !sign) return null;
|
if (!encrypt && !sign) return null;
|
||||||
if (encrypt && status.missing.length) {
|
if (encrypt && status.missing.length) {
|
||||||
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
||||||
if (!sendPlain) return false;
|
if (!sendPlain) return false;
|
||||||
encrypt = false;
|
encrypt = false;
|
||||||
if (!sign) return plaintextFallback();
|
if (!sign) return plaintextFallback();
|
||||||
}
|
}
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { encrypt, sign, passphrase };
|
return { encrypt, sign, passphrase };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,14 +14,12 @@ async function saveAndroidPgpExport(label, value) {
|
|||||||
else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true };
|
else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true };
|
||||||
return { saved: true };
|
return { saved: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEncryptionKeys() {
|
function openEncryptionKeys() {
|
||||||
const root = selectPgpKeyUi('#modal-root');
|
const root = selectPgpKeyUi('#modal-root');
|
||||||
const account = window.epMailFeatures.mail.connectedAccount || {};
|
const account = window.epMailFeatures.mail.connectedAccount || {};
|
||||||
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
|
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
|
||||||
const serverSettings = androidPgp
|
const serverSettings = `<h3 class="pgp-heading">Public key servers</h3>
|
||||||
? '<h3 class="pgp-heading">Public key servers</h3><p class="account-note">Key-server lookup and publication are disabled in Android testing. Import a public key directly and compare its fingerprint with the owner.</p><div hidden><div id="pgp-server-list"></div><input id="pgp-search-email"><button id="pgp-find-key"></button><div id="pgp-found-keys"></div><select id="pgp-publish-server"></select><input id="pgp-server-name"><input id="pgp-server-url"><select id="pgp-server-protocol"></select><button id="pgp-add-server"></button></div>'
|
|
||||||
: `<h3 class="pgp-heading">Public key servers</h3>
|
|
||||||
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
|
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
|
||||||
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
|
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
|
||||||
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
@@ -34,402 +32,438 @@ function openEncryptionKeys() {
|
|||||||
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
|
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
|
||||||
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
|
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
|
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal pgp-keys-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
||||||
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. 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>
|
||||||
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
||||||
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
||||||
<h3 class="pgp-heading">Contact public keys</h3>
|
<h3 class="pgp-heading">Contact public keys</h3>
|
||||||
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
||||||
${serverSettings}
|
${serverSettings}
|
||||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||||
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
||||||
<h3 class="pgp-heading">Create a key</h3>
|
<h3 class="pgp-heading">Create a key</h3>
|
||||||
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${escapePgpKeyUi(account.displayName || '')}"></label>
|
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${escapePgpKeyUi(account.displayName || '')}"></label>
|
||||||
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div>
|
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">${androidPgp ? 'Import private key from file…' : 'Import private key…'}</button>${androidPgp ? '<button class="discard" id="pgp-import-paste">Paste private key…</button>' : ''}</div>
|
||||||
<p class="account-note" id="pgp-status" role="status"></p>
|
<p class="account-note" id="pgp-status" role="status"></p>
|
||||||
</div></div></div>`;
|
</div></div></div>`;
|
||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
root.querySelector('.modal-close').onclick = close;
|
root.querySelector('.modal-close').onclick = close;
|
||||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||||
const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
||||||
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
||||||
let keyServers = [];
|
let keyServers = [];
|
||||||
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
||||||
const updatePublishButtons = () => {
|
const updatePublishButtons = () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
||||||
button.disabled = !server;
|
button.disabled = !server;
|
||||||
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const needPassphrase = () => {
|
const needPassphrase = () => {
|
||||||
const value = passphraseField().value;
|
const value = passphraseField().value;
|
||||||
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function render() {
|
async function render() {
|
||||||
const list = selectPgpKeyUi('#pgp-key-list');
|
const list = selectPgpKeyUi('#pgp-key-list');
|
||||||
let keys = [];
|
let keys = [];
|
||||||
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
||||||
keys.forEach(key => {
|
keys.forEach(key => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = key.email || 'OpenPGP key';
|
title.textContent = key.email || 'OpenPGP key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
row.append(info);
|
row.append(info);
|
||||||
const actions = [
|
const actions = [
|
||||||
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
||||||
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
||||||
];
|
];
|
||||||
const changePassphrase = document.createElement('button');
|
const changePassphrase = document.createElement('button');
|
||||||
changePassphrase.className = 'discard';
|
changePassphrase.className = 'discard';
|
||||||
changePassphrase.textContent = 'Change passphrase…';
|
changePassphrase.textContent = 'Change passphrase…';
|
||||||
changePassphrase.onclick = async () => {
|
changePassphrase.onclick = async () => {
|
||||||
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
||||||
if (!currentPassphrase) {
|
if (!currentPassphrase) {
|
||||||
status('Enter the current passphrase for this key.');
|
status('Enter the current passphrase for this key.');
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
||||||
if (newPassphrase.length < 8) {
|
if (newPassphrase.length < 8) {
|
||||||
status('Use a new passphrase of at least 8 characters.');
|
status('Use a new passphrase of at least 8 characters.');
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
||||||
status('The new passphrases do not match.');
|
status('The new passphrases do not match.');
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
changePassphrase.disabled = true;
|
changePassphrase.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.changePassphrase({
|
await window.daybreakMail.pgp.changePassphrase({
|
||||||
fingerprint: key.fingerprint,
|
fingerprint: key.fingerprint,
|
||||||
currentPassphrase,
|
currentPassphrase,
|
||||||
newPassphrase
|
newPassphrase
|
||||||
});
|
});
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
||||||
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
||||||
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
||||||
finally {
|
finally {
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
||||||
changePassphrase.disabled = false;
|
changePassphrase.disabled = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
row.append(changePassphrase);
|
row.append(changePassphrase);
|
||||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
if (androidPgp) {
|
||||||
actions.push(['Delete', async () => {
|
const biometric = document.createElement('button');
|
||||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
biometric.className = 'discard';
|
||||||
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
biometric.textContent = 'Checking biometric unlock…';
|
||||||
await render();
|
biometric.disabled = true;
|
||||||
return { deleted: true };
|
row.append(biometric);
|
||||||
}, true]);
|
window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => {
|
||||||
actions.forEach(([label, run, secret]) => {
|
if (!biometric.isConnected) return;
|
||||||
const button = document.createElement('button');
|
biometric.dataset.enabled = String(enabled);
|
||||||
button.className = 'discard';
|
biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…';
|
||||||
button.textContent = label;
|
biometric.disabled = false;
|
||||||
button.onclick = async () => {
|
}).catch(error => {
|
||||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.');
|
||||||
try {
|
});
|
||||||
|
biometric.onclick = async () => {
|
||||||
|
biometric.disabled = true;
|
||||||
|
try {
|
||||||
|
if (biometric.dataset.enabled === 'true') {
|
||||||
|
if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return;
|
||||||
|
await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint);
|
||||||
|
status('Biometric unlock disabled.');
|
||||||
|
} else {
|
||||||
|
const passphrase = needPassphrase();
|
||||||
|
if (!passphrase) return;
|
||||||
|
await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase });
|
||||||
|
passphraseField().value = '';
|
||||||
|
status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.');
|
||||||
|
}
|
||||||
|
await render();
|
||||||
|
} catch (error) {
|
||||||
|
status(error.message || 'Could not update biometric key unlock.');
|
||||||
|
} finally {
|
||||||
|
biometric.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||||
|
actions.push(['Delete', async () => {
|
||||||
|
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||||
|
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
||||||
|
await render();
|
||||||
|
return { deleted: true };
|
||||||
|
}, true]);
|
||||||
|
actions.forEach(([label, run, secret]) => {
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.className = 'discard';
|
||||||
|
button.textContent = label;
|
||||||
|
button.onclick = async () => {
|
||||||
|
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||||
|
try {
|
||||||
const result = await saveAndroidPgpExport(label, await run());
|
const result = await saveAndroidPgpExport(label, await run());
|
||||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||||
} catch (error) { status(error.message || 'That action failed.'); }
|
} catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
const publish = document.createElement('button');
|
const publish = document.createElement('button');
|
||||||
publish.className = 'discard pgp-publish';
|
publish.className = 'discard pgp-publish';
|
||||||
publish.onclick = async () => {
|
publish.onclick = async () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
||||||
publish.disabled = true;
|
publish.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
||||||
if (result.canceled) return;
|
if (result.canceled) return;
|
||||||
if (result.warning) status(result.warning);
|
if (result.warning) status(result.warning);
|
||||||
else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${server.name}. Check ${key.email || 'your email'} for a verification message before the key becomes searchable.`);
|
else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${server.name}. Check ${key.email || 'your email'} for a verification message before the key becomes searchable.`);
|
||||||
else if (result.verification === 'published') status(`The key is already published and searchable on ${server.name}.`);
|
else if (result.verification === 'published') status(`The key is already published and searchable on ${server.name}.`);
|
||||||
else if (result.verification === 'request-failed') status('The key was uploaded, but the server could not request email verification.');
|
else if (result.verification === 'request-failed') status('The key was uploaded, but the server could not request email verification.');
|
||||||
else if (result.verification === 'check-email') status(`${server.name} accepted the key. Check ${key.email || 'your email'} for its verification message. ${result.message || ''}`.trim());
|
else if (result.verification === 'check-email') status(`${server.name} accepted the key. Check ${key.email || 'your email'} for its verification message. ${result.message || ''}`.trim());
|
||||||
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
||||||
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
||||||
finally { updatePublishButtons(); }
|
finally { updatePublishButtons(); }
|
||||||
};
|
};
|
||||||
row.append(publish);
|
row.append(publish);
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
updatePublishButtons();
|
updatePublishButtons();
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#pgp-generate');
|
const button = selectPgpKeyUi('#pgp-generate');
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
status('Creating key…');
|
status('Creating key…');
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.generate({
|
await window.daybreakMail.pgp.generate({
|
||||||
name: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
name: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
||||||
});
|
});
|
||||||
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
||||||
await render();
|
await render();
|
||||||
} catch (error) { status(error.message || 'Could not create the key.'); }
|
} catch (error) { status(error.message || 'Could not create the key.'); }
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-import').onclick = async () => {
|
const importPrivateKey = async source => {
|
||||||
const passphrase = needPassphrase();
|
const passphrase = needPassphrase();
|
||||||
if (!passphrase) return;
|
if (!passphrase) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null, ...(androidPgp ? { source } : {}) });
|
||||||
status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.');
|
status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.');
|
||||||
await render();
|
if (!result.canceled) await render();
|
||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
async function renderContacts() {
|
selectPgpKeyUi('#pgp-import').onclick = () => importPrivateKey(androidPgp ? 'file' : undefined);
|
||||||
const list = selectPgpKeyUi('#pgp-contact-list');
|
if (androidPgp) selectPgpKeyUi('#pgp-import-paste').onclick = () => importPrivateKey('paste');
|
||||||
let contacts = [];
|
async function renderContacts() {
|
||||||
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
const list = selectPgpKeyUi('#pgp-contact-list');
|
||||||
list.replaceChildren();
|
let contacts = [];
|
||||||
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
||||||
contacts.forEach(contact => {
|
list.replaceChildren();
|
||||||
const row = document.createElement('div');
|
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
||||||
row.className = 'attachment-row';
|
contacts.forEach(contact => {
|
||||||
const info = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
row.className = 'attachment-row';
|
||||||
const title = document.createElement('strong');
|
const info = document.createElement('div');
|
||||||
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
info.className = 'attachment-row-info';
|
||||||
const meta = document.createElement('small');
|
const title = document.createElement('strong');
|
||||||
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
||||||
const fingerprint = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
||||||
info.append(title, meta, fingerprint);
|
const fingerprint = document.createElement('small');
|
||||||
const trust = document.createElement('select');
|
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
trust.className = 'pgp-trust';
|
info.append(title, meta, fingerprint);
|
||||||
trust.setAttribute('aria-label', 'Key trust');
|
const trust = document.createElement('select');
|
||||||
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
trust.className = 'pgp-trust';
|
||||||
const option = document.createElement('option');
|
trust.setAttribute('aria-label', 'Key trust');
|
||||||
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
||||||
trust.append(option);
|
const option = document.createElement('option');
|
||||||
});
|
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
||||||
trust.onchange = async () => {
|
trust.append(option);
|
||||||
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
});
|
||||||
trust.value = contact.trust;
|
trust.onchange = async () => {
|
||||||
return;
|
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
||||||
}
|
trust.value = contact.trust;
|
||||||
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
return;
|
||||||
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
}
|
||||||
};
|
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
||||||
const actions = [
|
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
||||||
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
};
|
||||||
['Remove', async () => {
|
const actions = [
|
||||||
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
||||||
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
['Remove', async () => {
|
||||||
await renderContacts();
|
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
||||||
return { deleted: true };
|
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
||||||
}]
|
await renderContacts();
|
||||||
];
|
return { deleted: true };
|
||||||
row.append(info, trust);
|
}]
|
||||||
actions.forEach(([label, run]) => {
|
];
|
||||||
const button = document.createElement('button');
|
row.append(info, trust);
|
||||||
button.className = 'discard';
|
actions.forEach(([label, run]) => {
|
||||||
button.textContent = label;
|
const button = document.createElement('button');
|
||||||
button.onclick = async () => {
|
button.className = 'discard';
|
||||||
|
button.textContent = label;
|
||||||
|
button.onclick = async () => {
|
||||||
try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); }
|
try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||||
catch (error) { status(error.message || 'That action failed.'); }
|
catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#pgp-add-contact').onclick = async () => {
|
selectPgpKeyUi('#pgp-add-contact').onclick = async () => {
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.addContact({});
|
const result = await window.daybreakMail.pgp.addContact({});
|
||||||
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
||||||
await renderContacts();
|
await renderContacts();
|
||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
async function renderKeyServers() {
|
async function renderKeyServers() {
|
||||||
const list = selectPgpKeyUi('#pgp-server-list');
|
const list = selectPgpKeyUi('#pgp-server-list');
|
||||||
const selector = selectPgpKeyUi('#pgp-publish-server');
|
const selector = selectPgpKeyUi('#pgp-publish-server');
|
||||||
const selectedId = selector.value;
|
const selectedId = selector.value;
|
||||||
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
||||||
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
||||||
selector.replaceChildren();
|
selector.replaceChildren();
|
||||||
const enabledServers = keyServers.filter(server => server.enabled);
|
const enabledServers = keyServers.filter(server => server.enabled);
|
||||||
if (!enabledServers.length) {
|
if (!enabledServers.length) {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = '';
|
option.value = '';
|
||||||
option.textContent = 'No enabled servers';
|
option.textContent = 'No enabled servers';
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
} else enabledServers.forEach(server => {
|
} else enabledServers.forEach(server => {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = server.id;
|
option.value = server.id;
|
||||||
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
||||||
option.selected = server.id === selectedId;
|
option.selected = server.id === selectedId;
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
});
|
});
|
||||||
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
||||||
selector.onchange = updatePublishButtons;
|
selector.onchange = updatePublishButtons;
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
keyServers.forEach(server => {
|
keyServers.forEach(server => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = server.name;
|
title.textContent = server.name;
|
||||||
const details = document.createElement('small');
|
const details = document.createElement('small');
|
||||||
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
||||||
info.append(title, details);
|
info.append(title, details);
|
||||||
const enabledLabel = document.createElement('label');
|
const enabledLabel = document.createElement('label');
|
||||||
enabledLabel.className = 'compose-line';
|
enabledLabel.className = 'compose-line';
|
||||||
const enabledText = document.createElement('span');
|
const enabledText = document.createElement('span');
|
||||||
enabledText.textContent = 'Use for lookup and publishing';
|
enabledText.textContent = 'Use for lookup and publishing';
|
||||||
const enabled = document.createElement('input');
|
const enabled = document.createElement('input');
|
||||||
enabled.type = 'checkbox';
|
enabled.type = 'checkbox';
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
||||||
enabled.onchange = async () => {
|
enabled.onchange = async () => {
|
||||||
enabled.disabled = true;
|
enabled.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
status(error.message || `Could not update ${server.name}.`);
|
status(error.message || `Could not update ${server.name}.`);
|
||||||
} finally { enabled.disabled = false; }
|
} finally { enabled.disabled = false; }
|
||||||
};
|
};
|
||||||
enabledLabel.append(enabledText, enabled);
|
enabledLabel.append(enabledText, enabled);
|
||||||
row.append(info, enabledLabel);
|
row.append(info, enabledLabel);
|
||||||
if (!server.builtin) {
|
const remove = document.createElement('button');
|
||||||
const remove = document.createElement('button');
|
remove.className = 'discard';
|
||||||
remove.className = 'discard';
|
remove.textContent = 'Remove';
|
||||||
remove.textContent = 'Remove';
|
remove.onclick = async () => {
|
||||||
remove.onclick = async () => {
|
try {
|
||||||
try {
|
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
||||||
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
await renderKeyServers();
|
||||||
await renderKeyServers();
|
status(`${server.name} removed.`);
|
||||||
status('Custom key server removed.');
|
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
||||||
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
};
|
||||||
};
|
row.append(remove);
|
||||||
row.append(remove);
|
list.append(row);
|
||||||
}
|
});
|
||||||
list.append(row);
|
}
|
||||||
});
|
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
||||||
}
|
const button = selectPgpKeyUi('#pgp-find-key');
|
||||||
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
const results = selectPgpKeyUi('#pgp-found-keys');
|
||||||
const button = selectPgpKeyUi('#pgp-find-key');
|
button.disabled = true;
|
||||||
const results = selectPgpKeyUi('#pgp-found-keys');
|
results.textContent = 'Searching…';
|
||||||
button.disabled = true;
|
try {
|
||||||
results.textContent = 'Searching…';
|
const found = await window.daybreakMail.pgp.findKey({
|
||||||
try {
|
email: selectPgpKeyUi('#pgp-search-email').value
|
||||||
const found = await window.daybreakMail.pgp.findKey({
|
});
|
||||||
email: selectPgpKeyUi('#pgp-search-email').value
|
results.replaceChildren();
|
||||||
});
|
found.keys.forEach(key => {
|
||||||
results.replaceChildren();
|
const row = document.createElement('div');
|
||||||
found.keys.forEach(key => {
|
row.className = 'attachment-row';
|
||||||
const row = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
info.className = 'attachment-row-info';
|
||||||
const info = document.createElement('div');
|
const title = document.createElement('strong');
|
||||||
info.className = 'attachment-row-info';
|
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
||||||
const title = document.createElement('strong');
|
const meta = document.createElement('small');
|
||||||
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
||||||
const meta = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
const fingerprint = document.createElement('small');
|
info.append(title, meta, fingerprint);
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
const add = document.createElement('button');
|
||||||
info.append(title, meta, fingerprint);
|
add.className = 'discard';
|
||||||
const add = document.createElement('button');
|
add.textContent = 'Add to contacts…';
|
||||||
add.className = 'discard';
|
add.onclick = async () => {
|
||||||
add.textContent = 'Add to contacts…';
|
add.disabled = true;
|
||||||
add.onclick = async () => {
|
try {
|
||||||
add.disabled = true;
|
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||||
try {
|
if (result.canceled) return;
|
||||||
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
status(result.keyChangedFrom?.length ? 'Key added. You already had another key for this address; compare fingerprints before trusting either key.' : 'Key added as unverified. Compare its fingerprint with the owner before trusting it.');
|
||||||
if (result.canceled) return;
|
await renderContacts();
|
||||||
status(result.keyChangedFrom?.length ? 'Key added. You already had another key for this address; compare fingerprints before trusting either key.' : 'Key added as unverified. Compare its fingerprint with the owner before trusting it.');
|
row.remove();
|
||||||
await renderContacts();
|
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
||||||
row.remove();
|
finally { add.disabled = false; }
|
||||||
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
};
|
||||||
finally { add.disabled = false; }
|
row.append(info, add);
|
||||||
};
|
results.append(row);
|
||||||
row.append(info, add);
|
});
|
||||||
results.append(row);
|
found.errors.forEach(error => {
|
||||||
});
|
const warning = document.createElement('small');
|
||||||
found.errors.forEach(error => {
|
warning.textContent = `${error.name}: ${error.message}`;
|
||||||
const warning = document.createElement('small');
|
results.append(warning);
|
||||||
warning.textContent = `${error.name}: ${error.message}`;
|
});
|
||||||
results.append(warning);
|
if (!found.keys.length && !found.errors.length) results.textContent = 'No matching public key was found on the enabled servers.';
|
||||||
});
|
if (found.keys.length) status(`Found ${found.keys.length} public key(s) on ${found.searchedServers.map(server => server.name).join(', ')}. They remain unverified until you check their fingerprints independently.${found.errors.length ? ` ${found.errors.length} server(s) could not be searched; see details above.` : ''}`);
|
||||||
if (!found.keys.length && !found.errors.length) results.textContent = 'No matching public key was found on the enabled servers.';
|
else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`);
|
||||||
if (found.keys.length) status(`Found ${found.keys.length} public key(s) on ${found.searchedServers.map(server => server.name).join(', ')}. They remain unverified until you check their fingerprints independently.${found.errors.length ? ` ${found.errors.length} server(s) could not be searched; see details above.` : ''}`);
|
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
||||||
else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`);
|
} catch (error) {
|
||||||
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
results.textContent = '';
|
||||||
} catch (error) {
|
status(error.message || 'Could not search the key server.');
|
||||||
results.textContent = '';
|
} finally { button.disabled = false; }
|
||||||
status(error.message || 'Could not search the key server.');
|
};
|
||||||
} finally { button.disabled = false; }
|
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
||||||
};
|
const button = selectPgpKeyUi('#pgp-add-server');
|
||||||
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
button.disabled = true;
|
||||||
const button = selectPgpKeyUi('#pgp-add-server');
|
try {
|
||||||
button.disabled = true;
|
const result = await window.daybreakMail.pgp.addKeyServer({
|
||||||
try {
|
name: selectPgpKeyUi('#pgp-server-name').value,
|
||||||
const result = await window.daybreakMail.pgp.addKeyServer({
|
url: selectPgpKeyUi('#pgp-server-url').value,
|
||||||
name: selectPgpKeyUi('#pgp-server-name').value,
|
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
||||||
url: selectPgpKeyUi('#pgp-server-url').value,
|
});
|
||||||
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
if (result.canceled) return;
|
||||||
});
|
selectPgpKeyUi('#pgp-server-name').value = '';
|
||||||
if (result.canceled) return;
|
selectPgpKeyUi('#pgp-server-url').value = '';
|
||||||
selectPgpKeyUi('#pgp-server-name').value = '';
|
await renderKeyServers();
|
||||||
selectPgpKeyUi('#pgp-server-url').value = '';
|
status('Custom key server added.');
|
||||||
await renderKeyServers();
|
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
||||||
status('Custom key server added.');
|
finally { button.disabled = false; }
|
||||||
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
};
|
||||||
finally { button.disabled = false; }
|
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||||
};
|
selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
|
||||||
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number(selectPgpKeyUi('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
||||||
selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
|
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||||
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number(selectPgpKeyUi('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
};
|
||||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||||
};
|
void renderKeyServers();
|
||||||
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
void renderContacts();
|
||||||
if (!androidPgp) void renderKeyServers();
|
void render();
|
||||||
void renderContacts();
|
}
|
||||||
void render();
|
|
||||||
}
|
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => async function () {
|
||||||
|
await baseOpenPreferences();
|
||||||
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
|
const fields = selectPgpKeyUi('#modal-root .compose-fields');
|
||||||
baseOpenPreferences();
|
if (!fields || !pgpAvailable()) return;
|
||||||
const fields = selectPgpKeyUi('#modal-root .compose-fields');
|
const button = document.createElement('button');
|
||||||
if (!fields || !pgpAvailable()) return;
|
button.type = 'button';
|
||||||
const button = document.createElement('button');
|
button.className = 'discard';
|
||||||
button.type = 'button';
|
button.id = 'open-encryption-keys';
|
||||||
button.className = 'discard';
|
button.textContent = 'Encryption keys…';
|
||||||
button.id = 'open-encryption-keys';
|
button.onclick = openEncryptionKeys;
|
||||||
button.textContent = 'Encryption keys…';
|
fields.append(button);
|
||||||
button.onclick = openEncryptionKeys;
|
|
||||||
fields.append(button);
|
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
+5976
-5120
File diff suppressed because one or more lines are too long
+46
-43
@@ -6,58 +6,61 @@ const selectAllProductivityUi = productivityMailUi.selectAll;
|
|||||||
const toastProductivityUi = productivityMailUi.toast;
|
const toastProductivityUi = productivityMailUi.toast;
|
||||||
const escapeProductivityUi = productivityMailUi.escapeHtml;
|
const escapeProductivityUi = productivityMailUi.escapeHtml;
|
||||||
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
|
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
|
||||||
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
|
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
|
||||||
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
|
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
|
||||||
let profileSettings = productRead(productKeys.profile, { name: '' });
|
let profileSettings = productRead(productKeys.profile, { name: '' });
|
||||||
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
||||||
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
||||||
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
||||||
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
||||||
productWrite(productKeys.contacts, savedContacts);
|
productWrite(productKeys.contacts, savedContacts);
|
||||||
let savedEvents = productRead(productKeys.events, []);
|
let savedEvents = productRead(productKeys.events, []);
|
||||||
let customLabels = productRead(productKeys.labels, []);
|
let customLabels = productRead(productKeys.labels, []);
|
||||||
let snoozedIds = productRead(productKeys.snoozed, []);
|
let snoozedIds = productRead(productKeys.snoozed, []);
|
||||||
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=selectProductivityUi('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=selectProductivityUi('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (productivityMailUi.connectedAccount) productivityMailUi.updateAccountCard(productivityMailUi.connectedAccount); }
|
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=selectProductivityUi('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=selectProductivityUi('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (productivityMailUi.connectedAccount) productivityMailUi.updateAccountCard(productivityMailUi.connectedAccount); }
|
||||||
function openAccountSettings() {
|
function openAccountSettings() {
|
||||||
const root=selectProductivityUi('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
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-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
|
selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
|
||||||
selectProductivityUi('#profile-name').focus();
|
selectProductivityUi('#profile-name').focus();
|
||||||
}
|
}
|
||||||
async function openPreferences() {
|
async function openPreferences() {
|
||||||
const root=selectProductivityUi('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
||||||
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
||||||
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
||||||
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>`:'';
|
||||||
const close=()=>root.innerHTML='';
|
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>`;
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
const close=()=>root.innerHTML='';
|
||||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=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('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
selectProductivityUi('#theme-select').focus();
|
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.')}};
|
||||||
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(); }
|
selectProductivityUi('#theme-select').focus();
|
||||||
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
}
|
||||||
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
|
function 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 renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}}
|
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
||||||
function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
|
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
|
||||||
function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})}
|
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}}
|
||||||
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
|
function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
|
||||||
function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
|
function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})}
|
||||||
async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
|
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
|
||||||
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh†to sync, or “account†to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
|
function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
|
||||||
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
|
async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
|
||||||
|
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh†to sync, or “account†to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
|
||||||
|
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
|
||||||
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
||||||
const state = productivityMailUi.state;
|
const state = productivityMailUi.state;
|
||||||
if (state.activeFolder === 'Drafts') {
|
if (state.activeFolder === 'Drafts') {
|
||||||
@@ -79,7 +82,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return baseMessageRenderer();
|
return baseMessageRenderer();
|
||||||
});
|
});
|
||||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}const decrypted=message?.attachments?.find(file=>file.filename===filename&&file.contentBase64);const saving=decrypted&&window.daybreakMail?.savePgpAttachment?window.daybreakMail.savePgpAttachment(decrypted):message?.uid&&window.daybreakMail?.saveAttachment?window.daybreakMail.saveAttachment({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,filename}):null;if(!saving){toastProductivityUi('Attachment download is available for connected mailbox messages');return}saving.then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
|
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}const decrypted=message?.attachments?.find(file=>file.filename===filename&&file.contentBase64);const saving=decrypted&&window.daybreakMail?.savePgpAttachment?window.daybreakMail.savePgpAttachment(decrypted):message?.uid&&window.daybreakMail?.saveAttachment?window.daybreakMail.saveAttachment({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,filename}):null;if(!saving){toastProductivityUi('Attachment download is available for connected mailbox messages');return}saving.then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
|
||||||
|
|
||||||
window.epMailFeatures.productivity = Object.freeze({
|
window.epMailFeatures.productivity = Object.freeze({
|
||||||
|
|||||||
+50
-31
@@ -1,15 +1,33 @@
|
|||||||
import { Capacitor, registerPlugin } from '@capacitor/core';
|
import { Capacitor, CapacitorHttp, registerPlugin } from '@capacitor/core';
|
||||||
import { createAndroidPgp } from './android-pgp.js';
|
import { createAndroidPgp } from './android-pgp.js';
|
||||||
|
|
||||||
const EpMail = registerPlugin('EpMail');
|
const EpMail = registerPlugin('EpMail');
|
||||||
|
|
||||||
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
// Native HTTP avoids WebView CORS limits; redirects are refused like on desktop.
|
||||||
const daybreakMail = {
|
async function nativeFetch(url, options = {}) {
|
||||||
|
const headers = options.headers || {};
|
||||||
|
const contentType = String(headers['content-type'] || '');
|
||||||
|
let data = options.body;
|
||||||
|
if (typeof data === 'string' && contentType.includes('json')) data = JSON.parse(data);
|
||||||
|
else if (typeof data === 'string' && contentType.includes('x-www-form-urlencoded')) data = Object.fromEntries(new URLSearchParams(data));
|
||||||
|
const response = await CapacitorHttp.request({ url: String(url), method: options.method || 'GET', headers, data,
|
||||||
|
responseType: 'text', disableRedirects: true, connectTimeout: 15000, readTimeout: 15000 });
|
||||||
|
const text = typeof response.data === 'string' ? response.data : JSON.stringify(response.data ?? '');
|
||||||
|
const lowered = Object.fromEntries(Object.entries(response.headers || {}).map(([name, value]) => [name.toLowerCase(), value]));
|
||||||
|
return { status: response.status, ok: response.status >= 200 && response.status < 300,
|
||||||
|
headers: { get: name => lowered[String(name).toLowerCase()] ?? null }, body: [new TextEncoder().encode(text)] };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
||||||
|
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 +35,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(),
|
||||||
@@ -30,24 +49,24 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
|||||||
previewAttachment: details => EpMail.previewAttachment(details),
|
previewAttachment: details => EpMail.previewAttachment(details),
|
||||||
saveAttachment: details => EpMail.saveAttachment(details),
|
saveAttachment: details => EpMail.saveAttachment(details),
|
||||||
openExternal: url => EpMail.openExternal({ url }),
|
openExternal: url => EpMail.openExternal({ url }),
|
||||||
send: async message => {
|
send: async message => {
|
||||||
if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) {
|
if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) {
|
||||||
if (message?.pgp?.plaintextFallback) {
|
if (message?.pgp?.plaintextFallback) {
|
||||||
const { pgp: _options, ...plainMessage } = message;
|
const { pgp: _options, ...plainMessage } = message;
|
||||||
return EpMail.send({ ...plainMessage, pgpRequested: true });
|
return EpMail.send({ ...plainMessage, pgpRequested: true });
|
||||||
}
|
}
|
||||||
return EpMail.send(message);
|
return EpMail.send(message);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const { rawBase64, to, from } = await daybreakMail.pgp.buildOutgoing(message);
|
const { rawBase64, to, from } = await daybreakMail.pgp.buildOutgoing(message);
|
||||||
const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message;
|
const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message;
|
||||||
return await EpMail.send({ ...headers, rawBase64, envelope: { from, to }, text: '', attachments: [] });
|
return await EpMail.send({ ...headers, rawBase64, envelope: { from, to }, text: '', attachments: [] });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { failed: true, code: error.code || 'PGP_ERROR', message: error.message || 'Could not encrypt this message.' };
|
return { failed: true, code: error.code || 'PGP_ERROR', message: error.message || 'Could not encrypt this message.' };
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
pgpGetMessageSource: details => EpMail.pgpGetMessageSource(details),
|
pgpGetMessageSource: details => EpMail.pgpGetMessageSource(details),
|
||||||
savePgpAttachment: details => EpMail.savePgpAttachment(details),
|
savePgpAttachment: details => EpMail.savePgpAttachment(details),
|
||||||
disconnect: id => EpMail.removeAccount({ id }),
|
disconnect: id => EpMail.removeAccount({ id }),
|
||||||
davList: () => EpMail.davList(),
|
davList: () => EpMail.davList(),
|
||||||
davConnect: config => EpMail.davConnect(config),
|
davConnect: config => EpMail.davConnect(config),
|
||||||
@@ -57,8 +76,8 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
|||||||
davSaveEvent: event => EpMail.davSaveEvent(event),
|
davSaveEvent: event => EpMail.davSaveEvent(event),
|
||||||
davDeleteEvent: remote => EpMail.davDeleteEvent(remote),
|
davDeleteEvent: remote => EpMail.davDeleteEvent(remote),
|
||||||
davSaveContact: contact => EpMail.davSaveContact(contact),
|
davSaveContact: contact => EpMail.davSaveContact(contact),
|
||||||
davDeleteContact: remote => EpMail.davDeleteContact(remote)
|
davDeleteContact: remote => EpMail.davDeleteContact(remote)
|
||||||
};
|
};
|
||||||
daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount() });
|
daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount(), fetchImpl: nativeFetch });
|
||||||
window.daybreakMail = daybreakMail;
|
window.daybreakMail = daybreakMail;
|
||||||
}
|
}
|
||||||
|
|||||||
+252
-28
@@ -1,4 +1,7 @@
|
|||||||
import * as openpgp from 'openpgp';
|
import * as openpgp from 'openpgp';
|
||||||
|
import keyServers from '../desktop/pgp-keyservers.cjs';
|
||||||
|
|
||||||
|
const { BUILTIN_SERVER_IDS, MAX_CUSTOM_SERVERS, createKeyServerService, listServers, normalizeCustomServer } = keyServers;
|
||||||
|
|
||||||
const MAX_KEY_LENGTH = 200000;
|
const MAX_KEY_LENGTH = 200000;
|
||||||
const MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
|
const MAX_MESSAGE_BYTES = 25 * 1024 * 1024;
|
||||||
@@ -118,6 +121,26 @@ function parseInnerMime(bytes) {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function attachedPublicKeys(attachments) {
|
||||||
|
const found = [];
|
||||||
|
for (const file of attachments || []) {
|
||||||
|
const type = String(file.contentType || '').toLowerCase();
|
||||||
|
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
|
||||||
|
if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue;
|
||||||
|
try {
|
||||||
|
const binary = atob(file.contentBase64);
|
||||||
|
const armoredKey = decoder.decode(Uint8Array.from(binary, char => char.charCodeAt(0))).trim();
|
||||||
|
if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) ||
|
||||||
|
/-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue;
|
||||||
|
const key = await openpgp.readKey({ armoredKey });
|
||||||
|
await key.getPrimaryUser();
|
||||||
|
found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
|
||||||
|
if (found.length === 5) break;
|
||||||
|
} catch { /* ignore malformed, expired or non-public key attachments */ }
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
function randomBoundary() {
|
function randomBoundary() {
|
||||||
const bytes = crypto.getRandomValues(new Uint8Array(18));
|
const bytes = crypto.getRandomValues(new Uint8Array(18));
|
||||||
return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`;
|
return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`;
|
||||||
@@ -171,8 +194,83 @@ function toBase64(bytes) {
|
|||||||
return btoa(binary);
|
return btoa(binary);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createAndroidPgp({ EpMail, getAccount }) {
|
function bytesToLatin1(bytes) {
|
||||||
|
let text = '';
|
||||||
|
for (let index = 0; index < bytes.length; index += 0x8000) {
|
||||||
|
text += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
|
||||||
|
}
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitSignedMime(source, boundary) {
|
||||||
|
if (!boundary || boundary.length > 200) return null;
|
||||||
|
const text = bytesToLatin1(source);
|
||||||
|
const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||||
|
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
|
||||||
|
const marks = [...text.matchAll(delimiter)];
|
||||||
|
if (marks.length < 3) return null;
|
||||||
|
const contentAfter = mark => {
|
||||||
|
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
|
||||||
|
return lineEnd < 0 ? text.length : lineEnd + 1;
|
||||||
|
};
|
||||||
|
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n');
|
||||||
|
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
|
||||||
|
const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
|
||||||
|
if (!signature) return null;
|
||||||
|
return { signed: Uint8Array.from(signed, char => char.charCodeAt(0) & 255), signature };
|
||||||
|
}
|
||||||
|
|
||||||
|
function senderFrom(headers) {
|
||||||
|
const value = String(headers.from || '');
|
||||||
|
return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || '').toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function invalidSignature() {
|
||||||
|
return { status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null,
|
||||||
|
matchesSender: false, keyChanged: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signatureStatuses(signatures, verification, sender) {
|
||||||
|
const results = [];
|
||||||
|
for (const signature of signatures || []) {
|
||||||
|
const keyId = signature.keyID.toHex().toUpperCase();
|
||||||
|
const known = verification.find(candidate => candidate.key.getKeys()
|
||||||
|
.some(key => key.getKeyID().toHex().toUpperCase() === keyId));
|
||||||
|
let status = 'valid';
|
||||||
|
try { await signature.verified; }
|
||||||
|
catch { status = known ? 'invalid' : 'unknown-key'; }
|
||||||
|
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
|
||||||
|
const matchesSender = Boolean(sender && keyEmails.includes(sender));
|
||||||
|
const changed = Boolean(sender && verification.some(candidate =>
|
||||||
|
!candidate.entry.own && candidate.entry.emails?.includes(sender) &&
|
||||||
|
candidate.entry.fingerprint !== known?.entry.fingerprint));
|
||||||
|
results.push({
|
||||||
|
status,
|
||||||
|
keyId,
|
||||||
|
fingerprint: known?.entry.fingerprint || null,
|
||||||
|
trust: known?.entry.trust || null,
|
||||||
|
email: keyEmails[0] || null,
|
||||||
|
matchesSender,
|
||||||
|
keyChanged: changed,
|
||||||
|
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.confirm, fetchImpl }) {
|
||||||
|
const keyServerService = createKeyServerService({ fetchImpl });
|
||||||
let storePromise;
|
let storePromise;
|
||||||
|
function serverSettings(data) {
|
||||||
|
const settings = data.settings || {};
|
||||||
|
const ids = value => Array.isArray(value) ? [...new Set(value.filter(id => typeof id === 'string'))] : [];
|
||||||
|
return { ...settings, customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
|
||||||
|
enabledKeyServers: ids(settings.enabledKeyServers), removedBuiltinKeyServers: ids(settings.removedBuiltinKeyServers) };
|
||||||
|
}
|
||||||
|
function currentServers(data) {
|
||||||
|
const settings = serverSettings(data);
|
||||||
|
return listServers(settings.customKeyServers, settings.enabledKeyServers, settings.removedBuiltinKeyServers);
|
||||||
|
}
|
||||||
const passphrases = new Map();
|
const passphrases = new Map();
|
||||||
let cacheMinutes = 10;
|
let cacheMinutes = 10;
|
||||||
|
|
||||||
@@ -226,7 +324,7 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
}
|
}
|
||||||
const user = await key.getPrimaryUser();
|
const user = await key.getPrimaryUser();
|
||||||
data.contacts.push({ fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown',
|
data.contacts.push({ fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown',
|
||||||
source: ['import', 'message', 'paste'].includes(source) ? source : 'import', addedAt: Date.now(), publicKey: key.armor() });
|
source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import', addedAt: Date.now(), publicKey: key.armor() });
|
||||||
await persist(data);
|
await persist(data);
|
||||||
return { contact: { fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source, addedAt: Date.now() }, keyChangedFrom };
|
return { contact: { fingerprint, name: user.user.userID?.name || '', emails, trust: 'unknown', source, addedAt: Date.now() }, keyChangedFrom };
|
||||||
}
|
}
|
||||||
@@ -251,16 +349,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) {
|
||||||
@@ -279,6 +387,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)}`,
|
||||||
@@ -341,6 +459,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); }
|
||||||
@@ -351,28 +470,55 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); }
|
try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); }
|
||||||
catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; }
|
catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; }
|
||||||
const content = parseInnerMime(decrypted.data);
|
const content = parseInnerMime(decrypted.data);
|
||||||
const signatures = [];
|
const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
|
||||||
for (const item of decrypted.signatures || []) {
|
const attachedKeys = await attachedPublicKeys(content.attachments);
|
||||||
const known = verify.find(candidate => candidate.key.getKeys().some(key => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
|
|
||||||
let status = 'valid';
|
|
||||||
try { await item.verified; } catch { status = known ? 'invalid' : 'unknown-key'; }
|
|
||||||
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || '';
|
|
||||||
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || '').toLowerCase();
|
|
||||||
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
|
|
||||||
const changed = Boolean(sender && data.contacts.some(entry => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
|
|
||||||
const matchesSender = Boolean(sender && keyEmails.includes(sender));
|
|
||||||
signatures.push({ status, keyId: item.keyID.toHex().toUpperCase(), fingerprint: known?.entry.fingerprint || null,
|
|
||||||
trust: known?.entry.trust || null, email: keyEmails[0] || null, matchesSender, keyChanged: changed,
|
|
||||||
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {}) });
|
|
||||||
}
|
|
||||||
return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html,
|
return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html,
|
||||||
links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null,
|
links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null,
|
||||||
size: content.attachments[0]?.size || '', signatures, attachedKeys: [] };
|
size: content.attachments[0]?.size || '', signatures, attachedKeys };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' };
|
return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function verifyMessage({ folder = 'Inbox', uid }) {
|
||||||
|
try {
|
||||||
|
const source = await EpMail.pgpGetMessageSource({ folder, uid });
|
||||||
|
const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0));
|
||||||
|
if (raw.byteLength > MAX_MESSAGE_BYTES) {
|
||||||
|
return { failed: true, code: 'TOO_LARGE', message: 'This signed message is too large to verify.' };
|
||||||
|
}
|
||||||
|
const entity = splitEntity(raw);
|
||||||
|
const contentType = entity.headers['content-type'] || '';
|
||||||
|
const sender = senderFrom(entity.headers);
|
||||||
|
const data = await store();
|
||||||
|
const verification = await verificationKeys(data);
|
||||||
|
if (/^multipart\/signed/i.test(contentType) &&
|
||||||
|
parameter(contentType, 'protocol').toLowerCase() === 'application/pgp-signature') {
|
||||||
|
const parts = splitSignedMime(raw, parameter(contentType, 'boundary'));
|
||||||
|
if (!parts) return { signatures: [invalidSignature()] };
|
||||||
|
try {
|
||||||
|
const result = await openpgp.verify({
|
||||||
|
message: await openpgp.createMessage({ binary: parts.signed }),
|
||||||
|
signature: await openpgp.readSignature({ armoredSignature: parts.signature }),
|
||||||
|
verificationKeys: verification.map(item => item.key)
|
||||||
|
});
|
||||||
|
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
|
||||||
|
} catch { return { signatures: [invalidSignature()] }; }
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = decoder.decode(decodePart(entity.body, entity.headers['content-transfer-encoding']));
|
||||||
|
const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0];
|
||||||
|
if (!armored) return { signatures: [] };
|
||||||
|
try {
|
||||||
|
const message = await openpgp.readCleartextMessage({ cleartextMessage: armored });
|
||||||
|
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
|
||||||
|
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
|
||||||
|
} catch { return { signatures: [invalidSignature()] }; }
|
||||||
|
} catch (error) {
|
||||||
|
return { failed: true, code: error.code || 'VERIFY_ERROR', message: error.message || 'Could not verify this message.' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const api = {
|
const api = {
|
||||||
platform: 'android',
|
platform: 'android',
|
||||||
async list() { return (await store()).keys.map(publicInfo); },
|
async list() { return (await store()).keys.map(publicInfo); },
|
||||||
@@ -391,8 +537,15 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
await persist(data);
|
await persist(data);
|
||||||
return { key: publicInfo(entry), revocationCertificate: generated.revocationCertificate };
|
return { key: publicInfo(entry), revocationCertificate: generated.revocationCertificate };
|
||||||
},
|
},
|
||||||
async importKey({ armoredKey, passphrase, accountId = null }) {
|
async importKey({ armoredKey, passphrase, accountId = null, source = 'paste' }) {
|
||||||
if (!armoredKey) armoredKey = prompt('Paste an ASCII-armored OpenPGP private key (up to 200 KB):') || '';
|
if (!armoredKey && source === 'file') {
|
||||||
|
const selected = await EpMail.pickPgpPrivateKey();
|
||||||
|
if (selected.canceled) return { canceled: true };
|
||||||
|
armoredKey = selected.armoredKey;
|
||||||
|
if (typeof armoredKey !== 'string' || !armoredKey.trim()) throw new Error('That key file is empty.');
|
||||||
|
} else if (!armoredKey) {
|
||||||
|
armoredKey = prompt('Paste an ASCII-armored OpenPGP private key (up to 200 KB):') || '';
|
||||||
|
}
|
||||||
const armored = String(armoredKey).trim();
|
const armored = String(armoredKey).trim();
|
||||||
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
|
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
|
||||||
if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.');
|
if (typeof passphrase !== 'string' || passphrase.length < 8) throw new Error('Use a passphrase of at least 8 characters.');
|
||||||
@@ -418,6 +571,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):') || '';
|
||||||
@@ -436,10 +606,16 @@ 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,
|
||||||
async getSettings() { const data = await store(); return { cacheMinutes }; },
|
async getSettings() { const data = await store(); return { cacheMinutes }; },
|
||||||
async setSettings({ cacheMinutes: value }) {
|
async setSettings({ cacheMinutes: value }) {
|
||||||
const number = Number(value);
|
const number = Number(value);
|
||||||
@@ -452,12 +628,60 @@ export function createAndroidPgp({ EpMail, getAccount }) {
|
|||||||
return { cacheMinutes };
|
return { cacheMinutes };
|
||||||
},
|
},
|
||||||
async forgetPassphrases() { clear(); return { cleared: true }; },
|
async forgetPassphrases() { clear(); return { cleared: true }; },
|
||||||
async keyServers() { return []; },
|
async keyServers() { return currentServers(await store()); },
|
||||||
async findKey() { throw new Error('Key-server lookup is not included in Android testing. Import a public key directly.'); },
|
async findKey({ email } = {}) { return keyServerService.lookupEnabled(currentServers(await store()), email); },
|
||||||
async addKeyServer() { throw new Error('Key-server support is not included in Android testing.'); },
|
async addKeyServer(input) {
|
||||||
async removeKeyServer() { throw new Error('Key-server support is not included in Android testing.'); },
|
const candidate = normalizeCustomServer(input);
|
||||||
async setKeyServerEnabled() { throw new Error('Key-server support is not included in Android testing.'); },
|
const data = await store();
|
||||||
async publishKey() { throw new Error('Key-server support is not included in Android testing.'); },
|
const settings = serverSettings(data);
|
||||||
|
const custom = settings.customKeyServers.map(normalizeCustomServer);
|
||||||
|
if (custom.length >= MAX_CUSTOM_SERVERS) throw new Error(`You can configure up to ${MAX_CUSTOM_SERVERS} custom key servers.`);
|
||||||
|
if (currentServers(data).some(server => server.url === candidate.url && server.protocol === candidate.protocol)) throw new Error('That key server is already configured.');
|
||||||
|
const host = new URL(candidate.url).host;
|
||||||
|
if (!confirm(`Allow ep-mail to contact ${host} for OpenPGP keys?\n\nProtocol: ${candidate.protocol.toUpperCase()}\nThe server may learn which email addresses you search for. Only add a server you trust.`)) return { canceled: true };
|
||||||
|
candidate.id = crypto.randomUUID();
|
||||||
|
data.settings = { ...serverSettings(data), customKeyServers: [...custom, candidate] };
|
||||||
|
await persist(data);
|
||||||
|
return { server: candidate };
|
||||||
|
},
|
||||||
|
async removeKeyServer(serverId) {
|
||||||
|
const id = String(serverId || '');
|
||||||
|
const data = await store();
|
||||||
|
const settings = serverSettings(data);
|
||||||
|
const custom = settings.customKeyServers.filter(server => server.id !== id);
|
||||||
|
const removesBuiltin = BUILTIN_SERVER_IDS.includes(id) && !settings.removedBuiltinKeyServers.includes(id);
|
||||||
|
if (custom.length === settings.customKeyServers.length && !removesBuiltin) throw new Error('That key server was not found.');
|
||||||
|
data.settings = { ...settings, customKeyServers: custom,
|
||||||
|
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id),
|
||||||
|
removedBuiltinKeyServers: removesBuiltin ? [...settings.removedBuiltinKeyServers, id] : settings.removedBuiltinKeyServers };
|
||||||
|
await persist(data);
|
||||||
|
return { removed: true };
|
||||||
|
},
|
||||||
|
async setKeyServerEnabled(serverId, enabled) {
|
||||||
|
if (typeof enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
|
||||||
|
const id = String(serverId || '');
|
||||||
|
const data = await store();
|
||||||
|
if (!currentServers(data).some(server => server.id === id)) throw new Error('That key server was not found.');
|
||||||
|
const settings = serverSettings(data);
|
||||||
|
const next = new Set(settings.enabledKeyServers);
|
||||||
|
if (enabled) next.add(id); else next.delete(id);
|
||||||
|
data.settings = { ...settings, enabledKeyServers: [...next] };
|
||||||
|
await persist(data);
|
||||||
|
return { serverId: id, enabled };
|
||||||
|
},
|
||||||
|
async publishKey({ fingerprint, serverId } = {}) {
|
||||||
|
const data = await store();
|
||||||
|
const server = currentServers(data).find(item => item.id === String(serverId || ''));
|
||||||
|
if (!server) throw new Error('Choose a configured key server.');
|
||||||
|
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
|
||||||
|
const entry = data.keys.find(item => item.fingerprint === fingerprint);
|
||||||
|
if (!entry) throw new Error('That key was not found.');
|
||||||
|
if (!entry.email) throw new Error('This key has no email address to publish.');
|
||||||
|
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
|
||||||
|
if (!emailsOf(publicKey).includes(String(entry.email).toLowerCase())) throw new Error('The selected key no longer matches its stored email address.');
|
||||||
|
if (!confirm(`Publish the public key for ${entry.email} to ${server.name}?\n\nFingerprint:\n${fingerprint.match(/.{1,4}/g).join(' ')}\n\nOnly the public key will be sent. This exposes the email address in the key to the server, which may retain it. The server may send a verification email before the key becomes searchable.`)) return { canceled: true };
|
||||||
|
return keyServerService.publish(server, entry.email, entry.publicKey, fingerprint);
|
||||||
|
},
|
||||||
clearPassphrases: clear,
|
clearPassphrases: clear,
|
||||||
buildOutgoing
|
buildOutgoing
|
||||||
};
|
};
|
||||||
|
|||||||
+16
-13
@@ -1,19 +1,22 @@
|
|||||||
# Builds the Android APK and the Windows portable exe into .\release
|
param(
|
||||||
|
[string]$WslDistribution
|
||||||
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
Set-Location $PSScriptRoot\..
|
Set-Location $PSScriptRoot\..
|
||||||
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
||||||
if (-not $env:JAVA_HOME) { $env:JAVA_HOME = 'C:\Program Files\Android\Android Studio\jbr' }
|
|
||||||
if (-not $env:ANDROID_HOME) { $env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
|
|
||||||
New-Item -ItemType Directory -Force release | Out-Null
|
|
||||||
|
|
||||||
Write-Host "== Building APK $version =="
|
& "$PSScriptRoot\build.ps1"
|
||||||
npm run android:apk
|
|
||||||
if ($LASTEXITCODE) { throw 'APK build failed' }
|
|
||||||
Copy-Item android\app\build\outputs\apk\debug\app-debug.apk "release\ep-mail $version.apk" -Force
|
|
||||||
|
|
||||||
Write-Host "== Building portable exe $version =="
|
Write-Host "`n== Building Windows installer $version =="
|
||||||
npm run dist:win:portable
|
npm run dist:win:installer
|
||||||
if ($LASTEXITCODE) { throw 'Portable build failed' }
|
if ($LASTEXITCODE) { throw 'Windows installer build failed' }
|
||||||
|
|
||||||
Write-Host "`nDone:"
|
Write-Host "`n== Building Linux AppImage and deb $version in WSL =="
|
||||||
Get-ChildItem release | Where-Object { $_.Name -like "ep-mail $version.*" } | ForEach-Object { " $($_.FullName)" }
|
$wslArguments = @()
|
||||||
|
if ($WslDistribution) { $wslArguments += @('--distribution', $WslDistribution) }
|
||||||
|
$wslArguments += @('--exec', 'bash', './scripts/build-linux-wsl.sh')
|
||||||
|
& wsl.exe @wslArguments
|
||||||
|
if ($LASTEXITCODE) { throw 'WSL Linux build failed' }
|
||||||
|
|
||||||
|
Write-Host "`nAll platform builds completed for $version. Artifacts are in release\."
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
source_dir="$(pwd -P)"
|
||||||
|
if [[ ! -f "$source_dir/package.json" || ! -f "$source_dir/package-lock.json" ]]; then
|
||||||
|
echo "Run this script from the project root." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
work_dir="$(mktemp -d "${TMPDIR:-/tmp}/ep-mail-linux-build.XXXXXXXX")"
|
||||||
|
trap 'rm -rf -- "$work_dir"' EXIT
|
||||||
|
|
||||||
|
echo "Copying sources to an isolated Linux workspace..."
|
||||||
|
tar -C "$source_dir" --exclude='./.git' --exclude='./node_modules' \
|
||||||
|
--exclude='./release' --exclude='./dist' --exclude='./android' --exclude='./www' \
|
||||||
|
-cf - . | tar -C "$work_dir" -xf -
|
||||||
|
cd "$work_dir"
|
||||||
|
|
||||||
|
echo "Installing Linux dependencies from package-lock.json..."
|
||||||
|
npm ci
|
||||||
|
version="$(node -p "require('./package.json').version")"
|
||||||
|
echo "Building Linux packages for $version..."
|
||||||
|
npm run dist:linux
|
||||||
|
|
||||||
|
shopt -s nullglob
|
||||||
|
appimages=(release/ep-mail-"$version"*.AppImage)
|
||||||
|
debs=(release/ep-mail_"$version"_*.deb)
|
||||||
|
if (( ${#appimages[@]} != 1 || ${#debs[@]} != 1 )); then
|
||||||
|
echo "Expected exactly one AppImage and one deb for version $version." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
mkdir -p "$source_dir/release"
|
||||||
|
cp -- "${appimages[0]}" "${debs[0]}" "$source_dir/release/"
|
||||||
|
printf 'Linux artifacts copied to release/:\n %s\n %s\n' "${appimages[0]##*/}" "${debs[0]##*/}"
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Builds the Android debug APK and the Windows portable exe into .\release
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
Set-Location $PSScriptRoot\..
|
||||||
|
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
|
||||||
|
if (-not $env:JAVA_HOME) { $env:JAVA_HOME = 'C:\Program Files\Android\Android Studio\jbr' }
|
||||||
|
if (-not $env:ANDROID_HOME) { $env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
|
||||||
|
New-Item -ItemType Directory -Force release | Out-Null
|
||||||
|
|
||||||
|
Write-Host "== Building APK $version =="
|
||||||
|
npm run android:apk
|
||||||
|
if ($LASTEXITCODE) { throw 'APK build failed' }
|
||||||
|
Write-Warning "The legacy ep-mail $version.apk copy is a debug APK and overwrites any existing file with that name."
|
||||||
|
Copy-Item android\app\build\outputs\apk\debug\app-debug.apk "release\ep-mail $version.apk" -Force
|
||||||
|
|
||||||
|
Write-Host "== Building portable exe $version =="
|
||||||
|
npm run dist:win:portable
|
||||||
|
if ($LASTEXITCODE) { throw 'Portable build failed' }
|
||||||
|
|
||||||
|
Write-Host "`nDone:"
|
||||||
|
Get-ChildItem release | Where-Object { $_.Name -like "ep-mail $version.*" } | ForEach-Object { " $($_.FullName)" }
|
||||||
+25
-2
@@ -1,5 +1,28 @@
|
|||||||
const CACHE='ep-mail-v18';
|
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;
|
||||||
|
})());
|
||||||
|
});
|
||||||
|
|||||||
+49
-39
@@ -65,43 +65,53 @@ document.addEventListener('keydown', event => {
|
|||||||
action.run();
|
action.run();
|
||||||
});
|
});
|
||||||
|
|
||||||
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
function openShortcutSettings() {
|
||||||
baseOpenPreferences();
|
const root = selectShortcutUi('#modal-root');
|
||||||
const fields = selectShortcutUi('#modal-root .compose-fields');
|
const shortcuts = loadShortcuts();
|
||||||
const save = selectShortcutUi('#save-appearance');
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Keyboard shortcuts</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
||||||
if (!fields || !save) return;
|
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-shortcuts">Save shortcuts</button></div></div></div>`;
|
||||||
const shortcuts = loadShortcuts();
|
const close = () => { root.innerHTML = ''; };
|
||||||
const section = document.createElement('div');
|
root.querySelectorAll('.modal-close').forEach(button => { button.onclick = close; });
|
||||||
section.className = 'shortcut-settings';
|
selectShortcutUi('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||||
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
fields.addEventListener('keydown', event => {
|
||||||
fields.append(section);
|
const input = event.target.closest('.shortcut-input');
|
||||||
section.addEventListener('keydown', event => {
|
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
||||||
const input = event.target.closest('.shortcut-input');
|
event.preventDefault();
|
||||||
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
||||||
event.preventDefault();
|
const combo = eventShortcut(event);
|
||||||
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
if (combo) input.value = combo;
|
||||||
const combo = eventShortcut(event);
|
});
|
||||||
if (combo) input.value = combo;
|
selectShortcutUi('#reset-shortcuts').onclick = () => {
|
||||||
|
fields.querySelectorAll('.shortcut-input').forEach(input => {
|
||||||
|
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
||||||
});
|
});
|
||||||
selectShortcutUi('#reset-shortcuts').onclick = () => {
|
};
|
||||||
section.querySelectorAll('.shortcut-input').forEach(input => {
|
selectShortcutUi('#save-shortcuts').onclick = () => {
|
||||||
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
const values = {};
|
||||||
});
|
const used = new Map();
|
||||||
};
|
for (const input of fields.querySelectorAll('.shortcut-input')) {
|
||||||
const baseSave = save.onclick;
|
const value = normalizeShortcut(input.value);
|
||||||
save.onclick = event => {
|
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
||||||
const values = {};
|
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||||
const used = new Map();
|
if (value) used.set(value, label);
|
||||||
for (const input of section.querySelectorAll('.shortcut-input')) {
|
values[input.dataset.action] = value;
|
||||||
const value = normalizeShortcut(input.value);
|
}
|
||||||
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
||||||
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
close();
|
||||||
if (value) used.set(value, label);
|
toastShortcutUi('Keyboard shortcuts saved');
|
||||||
values[input.dataset.action] = value;
|
};
|
||||||
}
|
}
|
||||||
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
|
||||||
baseSave?.call(save, event);
|
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => async function () {
|
||||||
};
|
await baseOpenPreferences();
|
||||||
});
|
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||||
})();
|
if (!fields || !selectShortcutUi('#save-appearance')) return;
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.type = 'button';
|
||||||
|
button.className = 'discard';
|
||||||
|
button.id = 'open-keyboard-shortcuts';
|
||||||
|
button.textContent = 'Keyboard shortcuts…';
|
||||||
|
button.onclick = openShortcutSettings;
|
||||||
|
fields.append(button);
|
||||||
|
});})();
|
||||||
|
|||||||
+7
-4
@@ -114,7 +114,7 @@ body.ep-daylight .compose-line input::placeholder,body.ep-daylight .compose-body
|
|||||||
body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b}
|
body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b}
|
||||||
body.ep-daylight .toast{background:#11212b;color:#f1f1e9}
|
body.ep-daylight .toast{background:#11212b;color:#f1f1e9}
|
||||||
body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||||
.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-fields{min-height:0;flex:1 1 auto;overflow-y:auto}
|
.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-modal>.modal-head,.compose-modal>.compose-footer{flex:none}.compose-fields{min-height:0;flex:0 1 auto;overflow-y:auto}.compose-modal>.compose-body{flex:1 1 120px;min-height:90px;height:auto}
|
||||||
.snooze-options .outline-button{width:100%;text-align:left}
|
.snooze-options .outline-button{width:100%;text-align:left}
|
||||||
.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap}
|
.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap}
|
||||||
@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}}
|
@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}}
|
||||||
@@ -126,9 +126,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
|||||||
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
|
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
|
||||||
|
|
||||||
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
|
.compose-fields code{font-family:monospace}.shortcut-input{text-transform:none}#reset-shortcuts{margin-top:8px}
|
||||||
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
||||||
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
|
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
|
||||||
|
.pgp-keys-modal .attachment-list{grid-template-columns:minmax(0,1fr)}.pgp-keys-modal .attachment-row{min-width:0}.pgp-keys-modal .attachment-row-info{flex:1 0 100%}.pgp-keys-modal .attachment-row-info strong,.pgp-keys-modal .attachment-row-info small{overflow:visible;text-overflow:clip;white-space:normal;overflow-wrap:anywhere}.pgp-keys-modal .attachment-row>button{max-width:100%;padding:8px;font-size:12px}.pgp-keys-modal .attachment-row>.compose-line{flex:1 1 180px;min-width:0}.pgp-keys-modal .pgp-trust{margin-left:0;max-width:100%}.pgp-keys-modal .pgp-actions{flex-wrap:wrap}
|
||||||
|
|
||||||
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
|
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
|
||||||
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
|
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
|
||||||
@@ -199,8 +200,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
|||||||
.compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px}
|
.compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px}
|
||||||
.compose-line span{flex:0 1 54%;line-height:1.25}
|
.compose-line span{flex:0 1 54%;line-height:1.25}
|
||||||
.compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0}
|
.compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0}
|
||||||
.compose-footer{gap:8px;padding:10px 12px}
|
.compose-footer{gap:8px;padding:10px 12px;flex-wrap:wrap;justify-content:flex-end}
|
||||||
.compose-body{height:30vh;padding:12px}
|
.compose-footer .pgp-compose{flex:1 0 100%;flex-wrap:wrap;margin-right:0;gap:4px 12px}
|
||||||
|
.compose-footer .send-button{order:99;padding:10px 18px;font-size:12px}
|
||||||
|
.compose-body{padding:12px}
|
||||||
.account-note,.account-status{font-size:12px}
|
.account-note,.account-status{font-size:12px}
|
||||||
.mail-rule-row{grid-template-columns:1fr;gap:6px}
|
.mail-rule-row{grid-template-columns:1fr;gap:6px}
|
||||||
.mail-rule-row>*{grid-column:1}
|
.mail-rule-row>*{grid-column:1}
|
||||||
|
|||||||
@@ -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/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { spawnSync } = require('node:child_process');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const os = require('node:os');
|
||||||
|
const path = require('node:path');
|
||||||
|
const vm = require('node:vm');
|
||||||
|
const esbuild = require('esbuild');
|
||||||
|
const openpgp = require('openpgp');
|
||||||
|
const { simpleParser } = require('mailparser');
|
||||||
|
const { webcrypto } = require('node:crypto');
|
||||||
|
|
||||||
|
global.crypto ||= webcrypto;
|
||||||
|
global.document ||= { addEventListener() {} };
|
||||||
|
|
||||||
|
const bundled = esbuild.buildSync({
|
||||||
|
entryPoints: [path.join(__dirname, '..', 'scripts', 'android-pgp.js')],
|
||||||
|
bundle: true,
|
||||||
|
platform: 'browser',
|
||||||
|
format: 'iife',
|
||||||
|
globalName: 'AndroidPgpInteropBundle',
|
||||||
|
write: false
|
||||||
|
}).outputFiles[0].text;
|
||||||
|
vm.runInThisContext(bundled);
|
||||||
|
const { createAndroidPgp } = global.AndroidPgpInteropBundle;
|
||||||
|
|
||||||
|
const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe']
|
||||||
|
.filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0);
|
||||||
|
const skip = gpgPath ? false : 'GnuPG is not installed';
|
||||||
|
const PASSPHRASE = 'Android GnuPG test passphrase';
|
||||||
|
|
||||||
|
function makeEndpoint(account) {
|
||||||
|
const vault = { keys: [], contacts: [], settings: {} };
|
||||||
|
let messageSource = null;
|
||||||
|
const EpMail = {
|
||||||
|
async pgpLoadStore() { return JSON.parse(JSON.stringify(vault)); },
|
||||||
|
async pgpSaveStore({ store }) { Object.assign(vault, JSON.parse(JSON.stringify(store))); return { ok: true }; },
|
||||||
|
async pgpGetMessageSource() { return messageSource; }
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
api: createAndroidPgp({ EpMail, getAccount: async () => account, confirm: () => true }),
|
||||||
|
setMessage(rawBase64) { messageSource = { rawBase64 }; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupGpg() {
|
||||||
|
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-android-gnupg-'));
|
||||||
|
const gpg = (args, input) => {
|
||||||
|
const result = spawnSync(gpgPath, [
|
||||||
|
'--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback',
|
||||||
|
'--passphrase', PASSPHRASE, '--trust-model', 'always', ...args
|
||||||
|
], { input });
|
||||||
|
if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`);
|
||||||
|
return { out: result.stdout, err: result.stderr.toString() };
|
||||||
|
};
|
||||||
|
gpg(['--quick-generate-key', 'Gina Gnu <gina@example.test>', 'ed25519', 'cert', 'never']);
|
||||||
|
const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(
|
||||||
|
gpg(['--list-keys', '--with-colons', 'gina@example.test']).out.toString()
|
||||||
|
)?.[1];
|
||||||
|
if (!fingerprint) throw new Error('Could not find the generated GnuPG test key fingerprint.');
|
||||||
|
gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']);
|
||||||
|
gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']);
|
||||||
|
return { home, fingerprint, gpg };
|
||||||
|
}
|
||||||
|
|
||||||
|
function encryptedMime(from, to, armor) {
|
||||||
|
const boundary = 'android-gnupg-encrypted';
|
||||||
|
return Buffer.from([
|
||||||
|
`From: ${from}`,
|
||||||
|
`To: ${to}`,
|
||||||
|
'Subject: Android GnuPG interoperability',
|
||||||
|
'MIME-Version: 1.0',
|
||||||
|
`Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`,
|
||||||
|
'',
|
||||||
|
`--${boundary}`,
|
||||||
|
'Content-Type: application/pgp-encrypted',
|
||||||
|
'',
|
||||||
|
'Version: 1',
|
||||||
|
`--${boundary}`,
|
||||||
|
'Content-Type: application/octet-stream; name="encrypted.asc"',
|
||||||
|
'',
|
||||||
|
armor.trim(),
|
||||||
|
`--${boundary}--`,
|
||||||
|
''
|
||||||
|
].join('\r\n'));
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Android OpenPGP PGP/MIME interoperates with GnuPG for send, read, and signature verification', { skip }, async () => {
|
||||||
|
const { home, fingerprint, gpg } = setupGpg();
|
||||||
|
try {
|
||||||
|
const android = makeEndpoint({ email: 'android@example.test', displayName: 'Android User', signature: '' });
|
||||||
|
const own = await android.api.generate({
|
||||||
|
name: 'Android User', email: 'android@example.test', passphrase: 'android key test passphrase'
|
||||||
|
});
|
||||||
|
const gpgPublic = gpg(['--armor', '--export', 'gina@example.test']).out.toString();
|
||||||
|
await android.api.addContact({ armoredKey: gpgPublic });
|
||||||
|
gpg(['--import'], Buffer.from(await android.api.exportPublic(own.key.fingerprint)));
|
||||||
|
|
||||||
|
const outgoing = await android.api.buildOutgoing({
|
||||||
|
to: 'Gina Gnu <gina@example.test>',
|
||||||
|
cc: '',
|
||||||
|
subject: 'Android to GnuPG',
|
||||||
|
text: 'Encrypted and signed from the Android OpenPGP module',
|
||||||
|
messageId: '<android-to-gnupg@example.test>',
|
||||||
|
pgp: { encrypt: true, sign: true, passphrase: 'android key test passphrase' },
|
||||||
|
attachments: []
|
||||||
|
});
|
||||||
|
const outboundText = Buffer.from(outgoing.rawBase64, 'base64').toString('utf8');
|
||||||
|
const outboundArmor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(outboundText)?.[0];
|
||||||
|
assert.ok(outboundArmor, 'Android output should contain an armored encrypted message');
|
||||||
|
const decrypted = gpg(['--decrypt'], Buffer.from(outboundArmor));
|
||||||
|
assert.match((await simpleParser(decrypted.out)).text, /Encrypted and signed from the Android OpenPGP module/);
|
||||||
|
assert.match(decrypted.err, /Good signature from/);
|
||||||
|
|
||||||
|
const incomingInner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nSigned and encrypted by GnuPG\r\n');
|
||||||
|
const incomingArmor = gpg([
|
||||||
|
'--armor', '--encrypt', '--sign', '--local-user', 'gina@example.test', '--recipient', 'android@example.test'
|
||||||
|
], incomingInner).out.toString();
|
||||||
|
android.setMessage(encryptedMime('Gina Gnu <gina@example.test>', 'android@example.test', incomingArmor).toString('base64'));
|
||||||
|
const opened = await android.api.decryptMessage({ folder: 'Inbox', uid: 11, passphrase: 'android key test passphrase' });
|
||||||
|
assert.equal(opened.ok, true, opened.message);
|
||||||
|
assert.deepEqual(opened.body, ['Signed and encrypted by GnuPG']);
|
||||||
|
assert.equal(opened.signatures[0].status, 'valid');
|
||||||
|
assert.equal(opened.signatures[0].matchesSender, true);
|
||||||
|
|
||||||
|
const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nGnuPG detached signed body';
|
||||||
|
const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.test'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim();
|
||||||
|
const signedBoundary = 'android-gnupg-signed';
|
||||||
|
const signedMime = Buffer.from([
|
||||||
|
'From: Gina Gnu <gina@example.test>',
|
||||||
|
'To: android@example.test',
|
||||||
|
'MIME-Version: 1.0',
|
||||||
|
`Content-Type: multipart/signed; protocol="application/pgp-signature"; boundary="${signedBoundary}"`,
|
||||||
|
'',
|
||||||
|
`--${signedBoundary}`,
|
||||||
|
signedPart,
|
||||||
|
`--${signedBoundary}`,
|
||||||
|
'Content-Type: application/pgp-signature',
|
||||||
|
'',
|
||||||
|
detached,
|
||||||
|
`--${signedBoundary}--`,
|
||||||
|
''
|
||||||
|
].join('\r\n'));
|
||||||
|
android.setMessage(signedMime.toString('base64'));
|
||||||
|
const signedMimeResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 12 });
|
||||||
|
assert.equal(signedMimeResult.signatures[0].status, 'valid');
|
||||||
|
assert.equal(signedMimeResult.signatures[0].matchesSender, true);
|
||||||
|
|
||||||
|
const clearSigned = gpg(['--clearsign', '--local-user', 'gina@example.test'], Buffer.from('GnuPG clear-signed body\n')).out.toString();
|
||||||
|
const clearSource = Buffer.from(
|
||||||
|
`From: Gina Gnu <gina@example.test>\r\nTo: android@example.test\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${clearSigned}\r\n`
|
||||||
|
);
|
||||||
|
android.setMessage(clearSource.toString('base64'));
|
||||||
|
const clearResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 13 });
|
||||||
|
assert.equal(clearResult.signatures[0].status, 'valid');
|
||||||
|
assert.equal(clearResult.signatures[0].matchesSender, true);
|
||||||
|
} finally {
|
||||||
|
fs.rmSync(home, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
+209
-3
@@ -1,9 +1,11 @@
|
|||||||
const test = require('node:test');
|
const test = require('node:test');
|
||||||
const assert = require('node:assert/strict');
|
const assert = require('node:assert/strict');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
|
const fs = require('node:fs');
|
||||||
const vm = require('node:vm');
|
const vm = require('node:vm');
|
||||||
const esbuild = require('esbuild');
|
const esbuild = require('esbuild');
|
||||||
const { webcrypto } = require('node:crypto');
|
const { webcrypto } = require('node:crypto');
|
||||||
|
const openpgp = require('openpgp');
|
||||||
|
|
||||||
global.crypto ||= webcrypto;
|
global.crypto ||= webcrypto;
|
||||||
global.document ||= { addEventListener() {} };
|
global.document ||= { addEventListener() {} };
|
||||||
@@ -19,7 +21,13 @@ const bundled = esbuild.buildSync({
|
|||||||
vm.runInThisContext(bundled);
|
vm.runInThisContext(bundled);
|
||||||
const { createAndroidPgp } = global.AndroidPgpBundle;
|
const { createAndroidPgp } = global.AndroidPgpBundle;
|
||||||
|
|
||||||
function makeEndpoint(account) {
|
function saveMimeFixture(name, rawBase64) {
|
||||||
|
if (process.env.EP_MAIL_PGP_MIME_FIXTURE_DIR) {
|
||||||
|
fs.writeFileSync(path.join(process.env.EP_MAIL_PGP_MIME_FIXTURE_DIR, `${name}.eml`), Buffer.from(rawBase64, 'base64'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 = {
|
||||||
@@ -28,26 +36,66 @@ 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
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test('Android imports an armored private key selected from a file', async () => {
|
||||||
|
const source = makeEndpoint({ email: 'alice@example.test' });
|
||||||
|
const target = makeEndpoint({ email: 'alice@example.test' });
|
||||||
|
const passphrase = 'alice test passphrase';
|
||||||
|
const generated = await source.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase });
|
||||||
|
const armoredKey = await source.api.exportPrivate(generated.key.fingerprint, passphrase);
|
||||||
|
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey });
|
||||||
|
|
||||||
|
await assert.rejects(target.api.importKey({ source: 'file', passphrase: 'incorrect passphrase' }), /passphrase is incorrect/);
|
||||||
|
assert.equal(target.vault.keys.length, 0);
|
||||||
|
const result = await target.api.importKey({ source: 'file', passphrase, accountId: 'account-1' });
|
||||||
|
assert.equal(result.key.fingerprint, generated.key.fingerprint);
|
||||||
|
assert.equal(target.vault.keys[0].accountId, 'account-1');
|
||||||
|
assert.equal((await openpgp.readPrivateKey({ armoredKey: target.vault.keys[0].privateKey })).isDecrypted(), false);
|
||||||
|
await assert.rejects(target.api.importKey({ source: 'file', passphrase }), /already in your keyring/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android file import handles cancellation, picker errors and invalid content', async () => {
|
||||||
|
const target = makeEndpoint({ email: 'alice@example.test' });
|
||||||
|
const options = { source: 'file', passphrase: 'test passphrase' };
|
||||||
|
target.EpMail.pickPgpPrivateKey = async () => ({ canceled: true });
|
||||||
|
assert.deepEqual(await target.api.importKey(options), { canceled: true });
|
||||||
|
target.EpMail.pickPgpPrivateKey = async () => { throw new Error('Picker failed'); };
|
||||||
|
await assert.rejects(target.api.importKey(options), /Picker failed/);
|
||||||
|
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey: '' });
|
||||||
|
await assert.rejects(target.api.importKey(options), /empty/);
|
||||||
|
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey: 'not a private key' });
|
||||||
|
await assert.rejects(target.api.importKey(options), /not a valid OpenPGP private key/);
|
||||||
|
target.EpMail.pickPgpPrivateKey = async () => ({ armoredKey: 'x'.repeat(200001) });
|
||||||
|
await assert.rejects(target.api.importKey(options), /too large/);
|
||||||
|
assert.equal(target.vault.keys.length, 0);
|
||||||
|
});
|
||||||
|
|
||||||
test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => {
|
test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', 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: '' });
|
||||||
|
const thirdParty = makeEndpoint({ email: 'charlie@example.test', displayName: 'Charlie', signature: '' });
|
||||||
const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
|
const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
|
||||||
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
|
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
|
||||||
|
const charlie = await thirdParty.api.generate({ name: 'Charlie', email: 'charlie@example.test', passphrase: 'charlie test passphrase' });
|
||||||
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
|
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
|
||||||
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) });
|
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) });
|
||||||
|
|
||||||
const built = await sender.api.buildOutgoing({
|
const built = await sender.api.buildOutgoing({
|
||||||
to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
|
to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
|
||||||
messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
|
messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
|
||||||
attachments: [{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') }]
|
attachments: [
|
||||||
|
{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') },
|
||||||
|
{ filename: 'charlie.asc', contentType: 'application/pgp-keys', contentBase64: Buffer.from(await thirdParty.api.exportPublic(charlie.key.fingerprint)).toString('base64') }
|
||||||
|
]
|
||||||
});
|
});
|
||||||
assert.ok(built.rawBase64);
|
assert.ok(built.rawBase64);
|
||||||
|
saveMimeFixture('encrypted-signed', built.rawBase64);
|
||||||
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
|
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
|
||||||
assert.match(raw, /multipart\/encrypted; protocol="application\/pgp-encrypted"/i);
|
assert.match(raw, /multipart\/encrypted; protocol="application\/pgp-encrypted"/i);
|
||||||
assert.doesNotMatch(raw, /hello from Android|private attachment/);
|
assert.doesNotMatch(raw, /hello from Android|private attachment/);
|
||||||
@@ -62,6 +110,8 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke
|
|||||||
assert.deepEqual(opened.body, ['hello from Android']);
|
assert.deepEqual(opened.body, ['hello from Android']);
|
||||||
assert.equal(opened.attachments[0].filename, 'note.txt');
|
assert.equal(opened.attachments[0].filename, 'note.txt');
|
||||||
assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment');
|
assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment');
|
||||||
|
assert.equal(opened.attachedKeys[0].fingerprint, charlie.key.fingerprint);
|
||||||
|
assert.deepEqual(opened.attachedKeys[0].emails, ['charlie@example.test']);
|
||||||
assert.equal(opened.signatures[0].status, 'valid');
|
assert.equal(opened.signatures[0].status, 'valid');
|
||||||
await recipient.api.setSettings({ cacheMinutes: 0 });
|
await recipient.api.setSettings({ cacheMinutes: 0 });
|
||||||
assert.equal((await recipient.api.getSettings()).cacheMinutes, 0);
|
assert.equal((await recipient.api.getSettings()).cacheMinutes, 0);
|
||||||
@@ -75,3 +125,159 @@ test('Android OpenPGP refuses encryption when any recipient key is missing', asy
|
|||||||
to: 'nobody@example.test', text: 'must not escape as plaintext', pgp: { encrypt: true }, attachments: []
|
to: 'nobody@example.test', text: 'must not escape as plaintext', pgp: { encrypt: true }, attachments: []
|
||||||
}), 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 () => {
|
||||||
|
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
|
||||||
|
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
|
||||||
|
const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
|
||||||
|
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) });
|
||||||
|
|
||||||
|
const signedMime = await sender.api.buildOutgoing({
|
||||||
|
to: 'Bob <bob@example.test>', cc: '', subject: 'Signed note', text: 'signed MIME body',
|
||||||
|
pgp: { encrypt: false, sign: true, passphrase: 'alice test passphrase' }, attachments: []
|
||||||
|
});
|
||||||
|
saveMimeFixture('signed', signedMime.rawBase64);
|
||||||
|
recipient.setMessage({ rawBase64: signedMime.rawBase64 });
|
||||||
|
const mimeResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 8 });
|
||||||
|
assert.equal(mimeResult.signatures[0].status, 'valid');
|
||||||
|
assert.equal(mimeResult.signatures[0].matchesSender, true);
|
||||||
|
|
||||||
|
const protectedPrivateKey = await sender.api.exportPrivate(created.key.fingerprint, 'alice test passphrase');
|
||||||
|
const signingKey = await openpgp.decryptKey({
|
||||||
|
privateKey: await openpgp.readPrivateKey({ armoredKey: protectedPrivateKey }),
|
||||||
|
passphrase: 'alice test passphrase'
|
||||||
|
});
|
||||||
|
const cleartext = await openpgp.createCleartextMessage({ text: 'clear-signed body' });
|
||||||
|
const clearSigned = await openpgp.sign({ message: cleartext, signingKeys: signingKey });
|
||||||
|
const raw = [
|
||||||
|
'From: Alice <alice@example.test>',
|
||||||
|
'To: Bob <bob@example.test>',
|
||||||
|
'Subject: Clear-signed note',
|
||||||
|
'Content-Type: text/plain; charset=utf-8',
|
||||||
|
'',
|
||||||
|
clearSigned,
|
||||||
|
''
|
||||||
|
].join('\r\n');
|
||||||
|
recipient.setMessage({ rawBase64: Buffer.from(raw).toString('base64') });
|
||||||
|
const clearResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 9 });
|
||||||
|
assert.equal(clearResult.signatures[0].status, 'valid');
|
||||||
|
assert.equal(clearResult.signatures[0].matchesSender, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android marks a damaged PGP/MIME signature invalid', async () => {
|
||||||
|
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
|
||||||
|
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
|
||||||
|
const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
|
||||||
|
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) });
|
||||||
|
const signed = await sender.api.buildOutgoing({
|
||||||
|
to: 'bob@example.test', subject: 'Signed', text: 'change me',
|
||||||
|
pgp: { sign: true, passphrase: 'alice test passphrase' }, attachments: []
|
||||||
|
});
|
||||||
|
const raw = Buffer.from(signed.rawBase64, 'base64').toString('utf8');
|
||||||
|
const armor = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(raw)?.[0];
|
||||||
|
const signatureLine = armor?.split(/\r?\n/).find(line => /^[A-Za-z0-9+/]{20,}$/.test(line));
|
||||||
|
assert.ok(signatureLine, 'signed MIME output should contain an armored signature');
|
||||||
|
const tampered = raw.replace(signatureLine, `${signatureLine[0] === 'A' ? 'B' : 'A'}${signatureLine.slice(1)}`);
|
||||||
|
recipient.setMessage({ rawBase64: Buffer.from(tampered).toString('base64') });
|
||||||
|
const result = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 10 });
|
||||||
|
assert.equal(result.signatures[0].status, 'invalid');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Android rejects tampered, malformed, and oversized encrypted input', async () => {
|
||||||
|
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
|
||||||
|
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
|
||||||
|
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
|
||||||
|
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
|
||||||
|
const built = await sender.api.buildOutgoing({
|
||||||
|
to: 'bob@example.test', subject: 'Encrypted test', text: 'tamper test',
|
||||||
|
pgp: { encrypt: true }, attachments: []
|
||||||
|
});
|
||||||
|
saveMimeFixture('encrypted', built.rawBase64);
|
||||||
|
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
|
||||||
|
const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(raw)?.[0];
|
||||||
|
assert.ok(armor);
|
||||||
|
const lines = armor.split(/\r?\n/);
|
||||||
|
const armorLineIndex = lines.findIndex(line => /^[A-Za-z0-9+/]{20,}$/.test(line));
|
||||||
|
assert.notEqual(armorLineIndex, -1);
|
||||||
|
lines[armorLineIndex] = `${lines[armorLineIndex][0] === 'A' ? 'B' : 'A'}${lines[armorLineIndex].slice(1)}`;
|
||||||
|
recipient.setMessage({ rawBase64: Buffer.from(raw.replace(armor, lines.join('\r\n'))).toString('base64') });
|
||||||
|
assert.equal((await recipient.api.decryptMessage({ uid: 20, passphrase: 'bob test passphrase' })).code, 'CORRUPT');
|
||||||
|
|
||||||
|
recipient.setMessage({ rawBase64: Buffer.from(
|
||||||
|
'From: Alice <alice@example.test>\r\nContent-Type: multipart/encrypted; boundary="broken"\r\n\r\nnot a valid PGP payload'
|
||||||
|
).toString('base64') });
|
||||||
|
assert.equal((await recipient.api.decryptMessage({ uid: 21, passphrase: 'bob test passphrase' })).code, 'CORRUPT');
|
||||||
|
|
||||||
|
recipient.setMessage({ rawBase64: 'A'.repeat(35_000_000) });
|
||||||
|
assert.equal((await recipient.api.decryptMessage({ uid: 22, passphrase: 'bob test passphrase' })).code, 'TOO_LARGE');
|
||||||
|
});
|
||||||
|
|
||||||
|
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/);
|
||||||
|
});
|
||||||
@@ -10,13 +10,22 @@ const app = fs.readFileSync(path.join(root, 'app.js'), 'utf8');
|
|||||||
const transport = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailTransport.kt'), 'utf8');
|
const transport = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailTransport.kt'), 'utf8');
|
||||||
const mainActivity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8');
|
const mainActivity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8');
|
||||||
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
|
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
|
||||||
|
const vault = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidAccountVault.kt'), 'utf8');
|
||||||
const androidMailService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
|
const androidMailService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
|
||||||
const androidPgpPolicy = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpPolicy.kt'), 'utf8');
|
const androidPgpPolicy = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpPolicy.kt'), 'utf8');
|
||||||
|
const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpConfirmationGate.kt'), 'utf8');
|
||||||
const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
||||||
const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8');
|
const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8');
|
||||||
const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8');
|
const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8');
|
||||||
|
const pgpUi = fs.readFileSync(path.join(root, 'pgp-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/);
|
||||||
@@ -31,6 +40,14 @@ test('mobile layout removes desktop minimum width and provides a compact reader
|
|||||||
assert.match(app, /if\(!m\)\{state\.activeMessage=null;document\.body\.classList\.remove\('reader-open'\);return;\}/);
|
assert.match(app, /if\(!m\)\{state\.activeMessage=null;document\.body\.classList\.remove\('reader-open'\);return;\}/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('key settings cards keep key details readable and actions wrapped', () => {
|
||||||
|
assert.match(pgpUi, /compose-modal attachments-modal pgp-keys-modal/);
|
||||||
|
assert.match(styles, /\.pgp-keys-modal \.attachment-list\{grid-template-columns:minmax\(0,1fr\)\}/);
|
||||||
|
assert.match(styles, /\.pgp-keys-modal \.attachment-row-info\{flex:1 0 100%\}/);
|
||||||
|
assert.match(styles, /\.pgp-keys-modal \.attachment-row-info small\{[^}]*white-space:normal;overflow-wrap:anywhere/);
|
||||||
|
assert.match(styles, /\.pgp-keys-modal \.pgp-actions\{flex-wrap:wrap\}/);
|
||||||
|
});
|
||||||
|
|
||||||
test('mailbox setup exposes ports and TLS modes and submits them to Android', () => {
|
test('mailbox setup exposes ports and TLS modes and submits them to Android', () => {
|
||||||
for (const id of ['mail-account-imap-port', 'mail-account-imap-secure', 'mail-account-smtp-port', 'mail-account-smtp-secure']) {
|
for (const id of ['mail-account-imap-port', 'mail-account-imap-secure', 'mail-account-smtp-port', 'mail-account-smtp-secure']) {
|
||||||
assert.ok(mailUi.includes(`id="${id}"`), `missing account field ${id}`);
|
assert.ok(mailUi.includes(`id="${id}"`), `missing account field ${id}`);
|
||||||
@@ -65,9 +82,84 @@ 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(mainActivity, /createConfirmDeviceCredentialIntent/);
|
assert.match(mainActivity, /createConfirmDeviceCredentialIntent/);
|
||||||
assert.match(mainActivity, /android\.R\.id\.content/);
|
assert.match(mainActivity, /android\.R\.id\.content/);
|
||||||
|
assert.match(mainActivity, /settings\.setAllowFileAccess\(false\)/);
|
||||||
|
assert.match(mainActivity, /settings\.setAllowContentAccess\(false\)/);
|
||||||
|
assert.match(mainActivity, /setJavaScriptCanOpenWindowsAutomatically\(false\)/);
|
||||||
|
assert.match(mainActivity, /MIXED_CONTENT_NEVER_ALLOW/);
|
||||||
|
assert.match(mainActivity, /setWebContentsDebuggingEnabled\(BuildConfig\.DEBUG\)/);
|
||||||
|
assert.match(mainActivity, /addFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
|
||||||
|
assert.match(mainActivity, /clearFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
|
||||||
|
assert.match(mainActivity, /createVaultRecoveryOverlay/);
|
||||||
|
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
|
||||||
assert.match(androidBridge, /getAppLockSettings/);
|
assert.match(androidBridge, /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 private-key picker preserves WebView restrictions and checks app lock', () => {
|
||||||
|
assert.match(plugin, /fun pickPgpPrivateKey\(call: PluginCall\)/);
|
||||||
|
assert.match(plugin, /AndroidAccountVault\.appLockEnabled\(\)/);
|
||||||
|
assert.match(plugin, /Intent\.ACTION_OPEN_DOCUMENT/);
|
||||||
|
assert.match(plugin, /uri\.scheme != "content"/);
|
||||||
|
assert.match(plugin, /BoundedInputReader\.read\(it, 200001\)/);
|
||||||
|
assert.match(plugin, /bytes\.isEmpty\(\) \|\| bytes\.size > 200000/);
|
||||||
|
});
|
||||||
|
|
||||||
|
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', () => {
|
||||||
@@ -76,20 +168,38 @@ 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, /\.setNegativeButton\("Cancel"\) \{ _, _ -> call\.reject\("OpenPGP key change cancelled\."\) \}/);
|
assert.match(plugin, /showPgpConfirmation\(/);
|
||||||
assert.match(plugin, /\.setPositiveButton\("Confirm changes"\)[\s\S]*bridge\.execute \{[\s\S]*AndroidAccountVault\.savePgpStore\(next\)/);
|
assert.match(plugin, /onCancelled = \{ call\.reject\("OpenPGP key change cancelled\."\) \}/);
|
||||||
assert.match(plugin, /\.setNegativeButton\("Cancel"\)[\s\S]*PLAINTEXT_CANCELLED/);
|
assert.match(plugin, /onConfirmed = \{ sendPrepared\(call, input\) \}/);
|
||||||
assert.match(plugin, /\.setPositiveButton\("Send plaintext"\)[\s\S]*sendPrepared\(call, input\)/);
|
assert.match(plugin, /PLAINTEXT_CANCELLED/);
|
||||||
|
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, /readCleartextMessage/);
|
||||||
|
assert.match(androidPgp, /readSignature/);
|
||||||
|
assert.match(pgpMailUi, /message\.signed/);
|
||||||
assert.match(androidBridge, /buildOutgoing\(message\)/);
|
assert.match(androidBridge, /buildOutgoing\(message\)/);
|
||||||
|
assert.match(plugin, /PgpMessageUid\.requireValid\(call\.data\.opt\("uid"\)\)/);
|
||||||
assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/);
|
assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/);
|
||||||
assert.match(androidMailService, /validateOpenPgpMime\(message\)/);
|
assert.match(androidMailService, /validateOpenPgpMime\(message\)/);
|
||||||
assert.match(androidMailService, /private fun validateOpenPgpMime/);
|
assert.match(androidMailService, /internal fun validateOpenPgpMime/);
|
||||||
assert.match(androidMailService, /"send" -> send\(account, data\)/);
|
assert.match(androidMailService, /"send" -> send\(account, data\)/);
|
||||||
assert.match(androidMailService, /private fun isEncryptedMessage/);
|
assert.match(androidMailService, /private fun isEncryptedMessage/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Android vault refuses to replace a missing key when encrypted data exists', () => {
|
||||||
|
assert.match(vault, /shouldCreateKey\(hasEncryptedData\)/);
|
||||||
|
assert.match(vault, /MISSING_KEY_MESSAGE/);
|
||||||
|
assert.match(mainActivity, /AndroidAccountVault\.INSTANCE\.read\(\)/);
|
||||||
|
assert.match(mainActivity, /Saved data could not be opened/);
|
||||||
|
assert.match(mainActivity, /ACTION_APPLICATION_DETAILS_SETTINGS/);
|
||||||
|
});
|
||||||
|
|||||||
@@ -8,9 +8,14 @@ const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'),
|
|||||||
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 androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8');
|
const androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8');
|
||||||
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
|
const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8');
|
||||||
|
const build = fs.readFileSync(path.join(root, 'scripts', 'build.ps1'), 'utf8');
|
||||||
|
const linuxBuild = fs.readFileSync(path.join(root, 'scripts', 'build-linux-wsl.sh'), 'utf8');
|
||||||
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);
|
||||||
@@ -31,10 +36,27 @@ test('Android version name and code derive from the canonical package version',
|
|||||||
|
|
||||||
test('release scripts and desktop artifact labels use package.json version', () => {
|
test('release scripts and desktop artifact labels use package.json version', () => {
|
||||||
assert.match(buildAll, /package\.json/);
|
assert.match(buildAll, /package\.json/);
|
||||||
|
assert.match(build, /package\.json/);
|
||||||
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
|
assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/);
|
||||||
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
|
assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('build scripts retain the basic targets and add the Windows installer and isolated WSL builds', () => {
|
||||||
|
assert.match(build, /npm run android:apk/);
|
||||||
|
assert.match(build, /npm run dist:win:portable/);
|
||||||
|
assert.match(buildAll, /build\.ps1/);
|
||||||
|
assert.match(buildAll, /npm run dist:win:installer/);
|
||||||
|
assert.match(buildAll, /--distribution/);
|
||||||
|
assert.match(buildAll, /build-linux-wsl\.sh/);
|
||||||
|
assert.match(linuxBuild, /mktemp -d/);
|
||||||
|
assert.match(linuxBuild, /--exclude='\.\/node_modules'/);
|
||||||
|
assert.match(linuxBuild, /npm ci/);
|
||||||
|
assert.match(linuxBuild, /npm run dist:linux/);
|
||||||
|
assert.match(linuxBuild, /appimages=/);
|
||||||
|
assert.match(linuxBuild, /debs=/);
|
||||||
|
assert.doesNotMatch(linuxBuild, /\r/);
|
||||||
|
});
|
||||||
|
|
||||||
test('Android debug APK is labeled as debug and release APK requires signing credentials', () => {
|
test('Android debug APK is labeled as debug and release APK requires signing credentials', () => {
|
||||||
assert.match(androidDebugScript, /assembleDebug/);
|
assert.match(androidDebugScript, /assembleDebug/);
|
||||||
assert.match(androidDebugScript, /ep-mail \$\{version\}-debug\.apk/);
|
assert.match(androidDebugScript, /ep-mail \$\{version\}-debug\.apk/);
|
||||||
@@ -45,3 +67,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,178 @@
|
|||||||
|
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 mailSource = fs.readFileSync(path.join(root, 'mail-ui.js'), 'utf8');
|
||||||
|
const pgpSource = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
|
||||||
|
const setupSource = mailSource.slice(mailSource.indexOf('function setupDraftComposer()'), mailSource.indexOf('\nasync function syncMailbox('));
|
||||||
|
|
||||||
|
function harness(initialDraft = null) {
|
||||||
|
const saved = [];
|
||||||
|
const deleted = [];
|
||||||
|
const toasts = [];
|
||||||
|
const elements = new Map();
|
||||||
|
const timers = new Map();
|
||||||
|
let nextTimer = 0;
|
||||||
|
let wrapped;
|
||||||
|
let saveDraft = async values => { saved.push(structuredClone(values)); return { id: values.id }; };
|
||||||
|
function node() {
|
||||||
|
const listeners = {};
|
||||||
|
return {
|
||||||
|
value: '', dataset: {}, isConnected: true, files: [], children: [],
|
||||||
|
classList: { contains: () => false },
|
||||||
|
append(...items) { this.children.push(...items); },
|
||||||
|
replaceChildren() { this.children = []; },
|
||||||
|
insertBefore(item) { this.children.push(item); },
|
||||||
|
setAttribute() {},
|
||||||
|
addEventListener(type, handler) { (listeners[type] ||= []).push(handler); },
|
||||||
|
dispatch(type, event = {}) { for (const handler of listeners[type] || []) handler(event); },
|
||||||
|
querySelector(selector) { return elements.get(selector); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
for (const name of ['#compose-to', '#compose-cc', '#compose-subject', '#compose-body', '#send', '#discard', '.modal-head span', '.compose-fields', '.compose-footer', '.modal-close', '.modal-overlay']) elements.set(name, node());
|
||||||
|
const modal = node();
|
||||||
|
const modalRoot = node();
|
||||||
|
modalRoot.querySelector = selector => selector === '.compose-modal' ? modal : elements.get(selector);
|
||||||
|
const context = {
|
||||||
|
appShell: { wrapShowCompose(fn) { wrapped = fn(() => {}); } },
|
||||||
|
selectMailUi: selector => selector === '#modal-root' ? modalRoot : elements.get(selector),
|
||||||
|
document: { createElement: node },
|
||||||
|
window: { crypto: { randomUUID: () => 'new-id' }, daybreakMail: {
|
||||||
|
saveDraft: values => saveDraft(values),
|
||||||
|
async deleteDraft(id) { deleted.push(id); }
|
||||||
|
} },
|
||||||
|
rendererState: { activeFolder: 'Inbox' },
|
||||||
|
syncMailbox() {},
|
||||||
|
toastMailUi: message => toasts.push(message),
|
||||||
|
setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; },
|
||||||
|
clearTimeout(id) { timers.delete(id); },
|
||||||
|
btoa: value => Buffer.from(value, 'binary').toString('base64')
|
||||||
|
};
|
||||||
|
vm.runInNewContext(`${setupSource}\nsetupDraftComposer();`, context);
|
||||||
|
wrapped(null, false, initialDraft);
|
||||||
|
return {
|
||||||
|
modal, modalRoot, elements, saved, deleted, toasts,
|
||||||
|
setSave(fn) { saveDraft = fn; },
|
||||||
|
async runTimers() { for (const fn of [...timers.values()]) fn(); timers.clear(); await new Promise(resolve => setImmediate(resolve)); },
|
||||||
|
async settle() { await new Promise(resolve => setImmediate(resolve)); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('PGP composer forwards the complete draft to the wrapped composer', () => {
|
||||||
|
const start = pgpSource.indexOf('pgpMailUi.wrapShowCompose(');
|
||||||
|
const end = pgpSource.indexOf('\n// Called by the send handler', start);
|
||||||
|
let args;
|
||||||
|
const context = {
|
||||||
|
pgpMailUi: { wrapShowCompose(decorator) { decorator((...values) => { args = values; })(null, false, { id: 'existing', text: 'saved text' }); } },
|
||||||
|
selectPgpMailUi: () => null
|
||||||
|
};
|
||||||
|
vm.runInNewContext(pgpSource.slice(start, end), context);
|
||||||
|
assert.equal(args[2].id, 'existing');
|
||||||
|
assert.equal(args[2].text, 'saved text');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('reopening a draft restores fields, attachments, and its identity', () => {
|
||||||
|
const draft = { id: 'existing', to: 'a@example.test', cc: 'b@example.test', subject: 'Subject', text: 'Message', attachments: [{ filename: 'note.txt' }] };
|
||||||
|
const h = harness(draft);
|
||||||
|
assert.equal(h.modal.dataset.draftId, draft.id);
|
||||||
|
for (const [field, value] of [['to', draft.to], ['cc', draft.cc], ['subject', draft.subject], ['body', draft.text]]) {
|
||||||
|
assert.equal(h.elements.get(`#compose-${field}`).value, value);
|
||||||
|
}
|
||||||
|
assert.equal(h.modal._composeAttachments[0].filename, 'note.txt');
|
||||||
|
assert.equal(h.elements.get('.modal-head span').textContent, 'Edit draft');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('blank and whitespace-only new messages are not saved on close or manual save', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.elements.get('#compose-body').value = ' \n ';
|
||||||
|
h.modal.dispatch('input');
|
||||||
|
await h.runTimers();
|
||||||
|
const save = h.elements.get('.compose-footer').children.find(item => item.id === 'save-draft');
|
||||||
|
await save.onclick();
|
||||||
|
assert.equal(h.toasts.at(-1), 'Nothing to save in this draft');
|
||||||
|
h.elements.get('.modal-close').dispatch('click');
|
||||||
|
await h.settle();
|
||||||
|
assert.equal(h.saved.length, 0);
|
||||||
|
assert.equal(h.modal.dataset.draftId, '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('closing via overlay or Escape saves meaningful unsaved text', async () => {
|
||||||
|
for (const method of ['overlay', 'escape']) {
|
||||||
|
const h = harness();
|
||||||
|
h.elements.get('#compose-subject').value = 'Saved subject';
|
||||||
|
if (method === 'overlay') h.elements.get('.modal-overlay').dispatch('click', { target: { classList: { contains: () => true } } });
|
||||||
|
else h.modal.dispatch('keydown', { key: 'Escape' });
|
||||||
|
await h.settle();
|
||||||
|
assert.equal(h.saved.length, 1);
|
||||||
|
assert.equal(h.saved[0].subject, 'Saved subject');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('attachment-only drafts are saved and picker cancellation creates nothing', async () => {
|
||||||
|
const h = harness();
|
||||||
|
const attachmentRow = h.elements.get('.compose-fields').children[0];
|
||||||
|
const input = attachmentRow.children[1].children[1];
|
||||||
|
await input.onchange();
|
||||||
|
assert.equal(h.saved.length, 0);
|
||||||
|
input.files = [{ name: 'note.txt', type: 'text/plain', size: 3, async arrayBuffer() { return Uint8Array.from([97, 98, 99]).buffer; } }];
|
||||||
|
await input.onchange();
|
||||||
|
assert.equal(h.saved.length, 1);
|
||||||
|
assert.equal(h.saved[0].attachments[0].contentBase64, 'YWJj');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pending saves are serialized and discard waits before deleting', async () => {
|
||||||
|
const h = harness();
|
||||||
|
let finishFirst;
|
||||||
|
const calls = [];
|
||||||
|
h.setSave(values => {
|
||||||
|
calls.push(values.text);
|
||||||
|
if (calls.length === 1) return new Promise(resolve => { finishFirst = resolve; });
|
||||||
|
return Promise.resolve({ id: values.id });
|
||||||
|
});
|
||||||
|
h.elements.get('#compose-body').value = 'first';
|
||||||
|
h.modal.dispatch('input');
|
||||||
|
await h.runTimers();
|
||||||
|
h.elements.get('#compose-body').value = 'second';
|
||||||
|
h.modal.dispatch('input');
|
||||||
|
await h.runTimers();
|
||||||
|
const discard = h.elements.get('#discard').onclick();
|
||||||
|
assert.deepEqual(calls, ['first']);
|
||||||
|
assert.deepEqual(h.deleted, []);
|
||||||
|
finishFirst({ id: 'new-id' });
|
||||||
|
await discard;
|
||||||
|
assert.deepEqual(calls, ['first', 'second']);
|
||||||
|
assert.deepEqual(h.deleted, ['new-id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sent draft cleanup cancels unsaved timers and waits for in-flight saves', async () => {
|
||||||
|
const h = harness();
|
||||||
|
let finishSave;
|
||||||
|
h.setSave(() => new Promise(resolve => { finishSave = resolve; }));
|
||||||
|
h.elements.get('#compose-body').value = 'sent message';
|
||||||
|
h.modal.dispatch('input');
|
||||||
|
await h.runTimers();
|
||||||
|
h.elements.get('#compose-body').value = 'newer edit';
|
||||||
|
h.modal.dispatch('input');
|
||||||
|
const cleanup = h.modal._deleteSavedDraft();
|
||||||
|
await h.runTimers();
|
||||||
|
assert.deepEqual(h.deleted, []);
|
||||||
|
finishSave({ id: 'new-id' });
|
||||||
|
await cleanup;
|
||||||
|
assert.deepEqual(h.deleted, ['new-id']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed save reports an error and a later save can retry', async () => {
|
||||||
|
const h = harness();
|
||||||
|
h.elements.get('#compose-body').value = 'message';
|
||||||
|
h.setSave(async () => { throw new Error('Storage unavailable'); });
|
||||||
|
const save = h.elements.get('.compose-footer').children.find(item => item.id === 'save-draft');
|
||||||
|
await save.onclick();
|
||||||
|
assert.equal(h.toasts.at(-1), 'Storage unavailable');
|
||||||
|
h.setSave(async values => { h.saved.push(values); return { id: values.id }; });
|
||||||
|
await save.onclick();
|
||||||
|
assert.equal(h.saved.length, 1);
|
||||||
|
assert.equal(h.toasts.at(-1), 'Draft saved on this device');
|
||||||
|
});
|
||||||
@@ -52,8 +52,11 @@ test('all built-in and custom key servers start disabled', () => {
|
|||||||
url: 'https://keys.example.org',
|
url: 'https://keys.example.org',
|
||||||
protocol: 'hkp'
|
protocol: 'hkp'
|
||||||
}]);
|
}]);
|
||||||
assert.equal(servers.length, 3);
|
assert.equal(servers.length, 4);
|
||||||
|
assert.ok(servers.some(server => server.id === 'eternity-vks' && server.url === 'https://keys.eternityproject.fi' && server.protocol === 'vks'));
|
||||||
assert.ok(servers.every(server => server.enabled === false));
|
assert.ok(servers.every(server => server.enabled === false));
|
||||||
|
const trimmed = listServers([], [], ['openpgp-vks', 'mailvelope-hkp']);
|
||||||
|
assert.deepEqual(trimmed.map(server => server.id), ['eternity-vks']);
|
||||||
const enabled = listServers([], ['openpgp-vks']);
|
const enabled = listServers([], ['openpgp-vks']);
|
||||||
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
|
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
|
||||||
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
|
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
|
||||||
|
|||||||
@@ -195,7 +195,7 @@ test('keyring: contacts, trust levels, expired passphrase cache and settings', a
|
|||||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
|
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
|
||||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
|
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
|
||||||
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
|
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
|
||||||
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [] });
|
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [], removedBuiltinKeyServers: [] });
|
||||||
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
|
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
|
||||||
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] });
|
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] });
|
||||||
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
|
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
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, '..', 'pgp-ui.js'), 'utf8');
|
||||||
|
|
||||||
|
async function openKeySettings(platform) {
|
||||||
|
const elements = new Map();
|
||||||
|
function element(selector) {
|
||||||
|
if (!elements.has(selector)) elements.set(selector, {
|
||||||
|
value: '', textContent: '', innerHTML: '',
|
||||||
|
append() {}, replaceChildren() {}, focus() { this.focused = true; },
|
||||||
|
querySelector: element
|
||||||
|
});
|
||||||
|
return elements.get(selector);
|
||||||
|
}
|
||||||
|
const calls = [];
|
||||||
|
const pgp = {
|
||||||
|
platform,
|
||||||
|
async list() { return []; },
|
||||||
|
async contacts() { return []; },
|
||||||
|
async keyServers() { return []; },
|
||||||
|
async getSettings() { return { cacheMinutes: 0 }; },
|
||||||
|
async importKey(input) { calls.push(input); return { canceled: false }; }
|
||||||
|
};
|
||||||
|
let wrap;
|
||||||
|
const window = {
|
||||||
|
daybreakMail: { pgp },
|
||||||
|
epMailFeatures: {
|
||||||
|
mail: { select: element, selectAll: () => [], escapeHtml: value => value, toast() {}, connectedAccount: { id: 'account-1' } },
|
||||||
|
productivity: { wrapOpenPreferences(fn) { wrap = fn; } }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let openButton;
|
||||||
|
const document = { createElement() { openButton = {}; return openButton; } };
|
||||||
|
element('#modal-root .compose-fields').append = button => { openButton = button; };
|
||||||
|
vm.runInNewContext(source, { window, document });
|
||||||
|
await wrap(async () => {})();
|
||||||
|
openButton.onclick();
|
||||||
|
return { element, calls, pgp };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Android private-key controls route file and paste imports with the account and passphrase', async () => {
|
||||||
|
const { element, calls, pgp } = await openKeySettings('android');
|
||||||
|
assert.match(element('#modal-root').innerHTML, /Import private key from file/);
|
||||||
|
await element('#pgp-import').onclick();
|
||||||
|
assert.equal(calls.length, 0);
|
||||||
|
assert.equal(element('#pgp-passphrase').focused, true);
|
||||||
|
element('#pgp-passphrase').value = 'test passphrase';
|
||||||
|
await element('#pgp-import').onclick();
|
||||||
|
await element('#pgp-import-paste').onclick();
|
||||||
|
assert.equal(calls[0].source, 'file');
|
||||||
|
assert.equal(calls[1].source, 'paste');
|
||||||
|
assert.equal(calls[0].passphrase, 'test passphrase');
|
||||||
|
assert.equal(calls[0].accountId, 'account-1');
|
||||||
|
pgp.importKey = async () => { throw new Error('File read failed'); };
|
||||||
|
await element('#pgp-import').onclick();
|
||||||
|
assert.equal(element('#pgp-status').textContent, 'File read failed');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('desktop private-key import retains its existing file-picker API', async () => {
|
||||||
|
const { element, calls } = await openKeySettings('desktop');
|
||||||
|
assert.doesNotMatch(element('#modal-root').innerHTML, /pgp-import-paste/);
|
||||||
|
element('#pgp-passphrase').value = 'test passphrase';
|
||||||
|
await element('#pgp-import').onclick();
|
||||||
|
assert.equal(calls.length, 1);
|
||||||
|
assert.equal(Object.hasOwn(calls[0], 'source'), false);
|
||||||
|
});
|
||||||
@@ -80,6 +80,7 @@ test('account and snooze UI consume the explicit mail API instead of selected le
|
|||||||
const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8');
|
const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8');
|
||||||
const productivityUi = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
const productivityUi = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
|
||||||
assert.match(accountUi, /window\.epMailFeatures\.mail/);
|
assert.match(accountUi, /window\.epMailFeatures\.mail/);
|
||||||
|
assert.match(accountUi, /Downloaded attachment files and OpenPGP keys are kept/);
|
||||||
assert.match(attachmentUi, /^\(\(\) => \{/);
|
assert.match(attachmentUi, /^\(\(\) => \{/);
|
||||||
assert.match(snoozeUi, /window\.epMailFeatures\.mail/);
|
assert.match(snoozeUi, /window\.epMailFeatures\.mail/);
|
||||||
assert.match(snoozeUi, /^\(\(\) => \{/);
|
assert.match(snoozeUi, /^\(\(\) => \{/);
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
});
|
||||||
+1
-1
@@ -21,7 +21,7 @@ async function openAccountManager(){
|
|||||||
const editButton=event.target.closest('[data-edit-account]');
|
const editButton=event.target.closest('[data-edit-account]');
|
||||||
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
|
||||||
const removeButton=event.target.closest('[data-remove-account]');
|
const removeButton=event.target.closest('[data-remove-account]');
|
||||||
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?\n\nIts cached mail, drafts and pending sends will be removed. Downloaded attachment files and OpenPGP keys are kept; delete those separately if you want to remove them too.`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
|
||||||
};
|
};
|
||||||
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
|
||||||
}
|
}
|
||||||
|
|||||||
+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); },
|
||||||
|
|||||||
+256
-54
@@ -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 || '';
|
||||||
@@ -566,6 +595,7 @@ function setupDraftComposer() {
|
|||||||
contentBase64: btoa(binary)
|
contentBase64: btoa(binary)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (closed) return;
|
||||||
attachments.push(...selected);
|
attachments.push(...selected);
|
||||||
renderAttachments();
|
renderAttachments();
|
||||||
await persist();
|
await persist();
|
||||||
@@ -592,65 +622,78 @@ function setupDraftComposer() {
|
|||||||
modal.querySelector('.compose-footer').insertBefore(save, selectMailUi('#send'));
|
modal.querySelector('.compose-footer').insertBefore(save, selectMailUi('#send'));
|
||||||
let saveTimer;
|
let saveTimer;
|
||||||
let closed = false;
|
let closed = false;
|
||||||
const persist = async () => {
|
let pendingSave = Promise.resolve();
|
||||||
if (closed || !selectMailUi('#compose-to')) return;
|
const persist = () => {
|
||||||
|
if (closed || !modal.isConnected) return Promise.resolve(false);
|
||||||
const values = {
|
const values = {
|
||||||
id: modal.dataset.draftId || window.crypto.randomUUID(),
|
to: modal.querySelector('#compose-to').value,
|
||||||
to: selectMailUi('#compose-to').value,
|
cc: modal.querySelector('#compose-cc').value,
|
||||||
cc: selectMailUi('#compose-cc').value,
|
subject: modal.querySelector('#compose-subject').value,
|
||||||
subject: selectMailUi('#compose-subject').value,
|
text: modal.querySelector('#compose-body').value,
|
||||||
text: selectMailUi('#compose-body').value,
|
attachments: [...attachments]
|
||||||
attachments
|
|
||||||
};
|
};
|
||||||
if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
|
if (!modal.dataset.draftId && ![values.to, values.cc, values.subject, values.text].some(value => value.trim()) && !values.attachments.length) return Promise.resolve(false);
|
||||||
|
values.id = modal.dataset.draftId || window.crypto.randomUUID();
|
||||||
modal.dataset.draftId = values.id;
|
modal.dataset.draftId = values.id;
|
||||||
const result = await window.daybreakMail.saveDraft(values);
|
const operation = pendingSave.then(async () => {
|
||||||
modal.dataset.draftId = result.id;
|
await window.daybreakMail.saveDraft(values);
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
pendingSave = operation.then(() => {}, () => {});
|
||||||
|
return operation;
|
||||||
};
|
};
|
||||||
save.onclick = async () => {
|
save.onclick = async () => {
|
||||||
try {
|
try {
|
||||||
await persist();
|
const saved = await persist();
|
||||||
toastMailUi('Draft saved on this device');
|
toastMailUi(saved ? 'Draft saved on this device' : 'Nothing to save in this draft');
|
||||||
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
if (saved && rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
||||||
} catch (error) { toastMailUi(error.message || 'Could not save draft'); }
|
} catch (error) { toastMailUi(error.message || 'Could not save draft'); }
|
||||||
};
|
};
|
||||||
modal.addEventListener('input', () => {
|
modal.addEventListener('input', () => {
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
saveTimer = setTimeout(() => persist().catch(error => toastMailUi(error.message || 'Could not save draft')), 700);
|
saveTimer = setTimeout(() => persist().catch(error => toastMailUi(error.message || 'Could not save draft')), 700);
|
||||||
});
|
});
|
||||||
modal.querySelector('.modal-overlay')?.addEventListener('click', event => {
|
const saveAndClose = () => {
|
||||||
if (!event.target.classList.contains('modal-overlay')) return;
|
if (closed) return;
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
|
persist().then(saved => { if (saved && rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
|
||||||
.catch(error => toastMailUi(error.message || 'Could not save draft'));
|
.catch(error => toastMailUi(error.message || 'Could not save draft'));
|
||||||
closed = true;
|
closed = true;
|
||||||
|
};
|
||||||
|
root.querySelector('.modal-overlay')?.addEventListener('click', event => {
|
||||||
|
if (!event.target.classList.contains('modal-overlay')) return;
|
||||||
|
saveAndClose();
|
||||||
}, true);
|
}, true);
|
||||||
root.querySelector('.modal-close')?.addEventListener('click', () => {
|
root.querySelector('.modal-close')?.addEventListener('click', saveAndClose, true);
|
||||||
clearTimeout(saveTimer);
|
modal.addEventListener('keydown', event => {
|
||||||
persist().then(() => { if (rendererState.activeFolder === 'Drafts') void syncMailbox(false); })
|
if (event.key === 'Escape') saveAndClose();
|
||||||
.catch(error => toastMailUi(error.message || 'Could not save draft'));
|
});
|
||||||
closed = true;
|
const deleteSavedDraft = async () => {
|
||||||
}, true);
|
|
||||||
selectMailUi('#discard').onclick = async () => {
|
|
||||||
clearTimeout(saveTimer);
|
clearTimeout(saveTimer);
|
||||||
closed = true;
|
closed = true;
|
||||||
|
await pendingSave;
|
||||||
|
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
|
||||||
|
};
|
||||||
|
modal._deleteSavedDraft = deleteSavedDraft;
|
||||||
|
selectMailUi('#discard').onclick = async () => {
|
||||||
try {
|
try {
|
||||||
if (modal.dataset.draftId) await window.daybreakMail.deleteDraft(modal.dataset.draftId);
|
await deleteSavedDraft();
|
||||||
root.innerHTML = '';
|
root.innerHTML = '';
|
||||||
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
||||||
} catch (error) { toastMailUi(error.message || 'Could not delete draft'); }
|
} catch (error) { toastMailUi(error.message || 'Could not delete draft'); }
|
||||||
};
|
};
|
||||||
selectMailUi('#send').addEventListener('click', () => {
|
|
||||||
clearTimeout(saveTimer);
|
|
||||||
closed = true;
|
|
||||||
}, true);
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
mailFeatureState.syncQueued = true;
|
if (!isAndroid || mailFeatureState.syncMailboxKey === mailboxKey) {
|
||||||
return mailFeatureState.syncPromise;
|
mailFeatureState.syncQueued = true;
|
||||||
|
return mailFeatureState.syncPromise;
|
||||||
|
}
|
||||||
|
mailFeatureState.syncQueued = false;
|
||||||
}
|
}
|
||||||
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
if (!mailFeatureState.connectedAccount || !window.daybreakMail) {
|
||||||
openMailAccount();
|
openMailAccount();
|
||||||
@@ -658,19 +701,88 @@ async function syncMailbox(showToast, options = {}) {
|
|||||||
}
|
}
|
||||||
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 +791,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 selectMailUi('#reader-pane').innerHTML = appShell.emptyReader();
|
else {
|
||||||
|
document.body.classList.remove('reader-open');
|
||||||
|
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 (refresh) refresh.disabled = false;
|
if (!isAndroid || mailFeatureState.syncRequest === request) {
|
||||||
|
if (refresh) refresh.disabled = false;
|
||||||
|
if (loadMoreButton) loadMoreButton.disabled = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
})();
|
})();
|
||||||
@@ -713,12 +853,66 @@ 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) {
|
||||||
@@ -777,7 +971,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 +979,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 +1021,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;
|
||||||
@@ -860,15 +1062,15 @@ if (window.daybreakMail) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.queued) {
|
if (result.queued) {
|
||||||
const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
|
const modal = selectMailUi('#modal-root .compose-modal');
|
||||||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
if (modal?._deleteSavedDraft) await modal._deleteSavedDraft();
|
||||||
selectMailUi('#modal-root').innerHTML = '';
|
selectMailUi('#modal-root').innerHTML = '';
|
||||||
toastMailUi('Offline: message queued and will send when connected');
|
toastMailUi('Offline: message queued and will send when connected');
|
||||||
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
if (rendererState.activeFolder === 'Drafts') void syncMailbox(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const draftId = selectMailUi('#modal-root .compose-modal')?.dataset.draftId;
|
const modal = selectMailUi('#modal-root .compose-modal');
|
||||||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
if (modal?._deleteSavedDraft) await modal._deleteSavedDraft();
|
||||||
selectMailUi('#modal-root').innerHTML = '';
|
selectMailUi('#modal-root').innerHTML = '';
|
||||||
toastMailUi(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
|
toastMailUi(result.savedToSent ? 'Message sent and saved in Sent' : 'Message sent, but its Sent copy could not be saved');
|
||||||
if (rendererState.activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
|
if (rendererState.activeFolder === 'Sent') syncMailbox(false, { offset: 0 });
|
||||||
|
|||||||
+194
-165
@@ -6,164 +6,193 @@ const selectAllPgpMailUi = pgpMailUi.selectAll;
|
|||||||
const toastPgpMailUi = pgpMailUi.toast;
|
const toastPgpMailUi = pgpMailUi.toast;
|
||||||
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
const escapePgpMailUi = pgpMailUi.escapeHtml;
|
||||||
const pgpApi = () => window.daybreakMail?.pgp;
|
const pgpApi = () => window.daybreakMail?.pgp;
|
||||||
|
|
||||||
function pgpAskPassphrase(title, detail) {
|
function pgpAskPassphrase(title, detail) {
|
||||||
return new Promise(resolve => {
|
return new Promise(resolve => {
|
||||||
const overlay = document.createElement('div');
|
const overlay = document.createElement('div');
|
||||||
overlay.className = 'modal-overlay pgp-prompt';
|
overlay.className = 'modal-overlay pgp-prompt';
|
||||||
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
overlay.innerHTML = `<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
||||||
overlay.querySelector('.modal-head span').textContent = title;
|
overlay.querySelector('.modal-head span').textContent = title;
|
||||||
overlay.querySelector('.account-note').textContent = detail;
|
overlay.querySelector('.account-note').textContent = detail;
|
||||||
const finish = value => { overlay.remove(); resolve(value); };
|
const finish = value => { overlay.remove(); resolve(value); };
|
||||||
overlay.querySelector('form').onsubmit = event => {
|
overlay.querySelector('form').onsubmit = event => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const value = overlay.querySelector('input').value;
|
const value = overlay.querySelector('input').value;
|
||||||
if (value) finish(value);
|
if (value) finish(value);
|
||||||
};
|
};
|
||||||
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
||||||
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
||||||
document.body.append(overlay);
|
document.body.append(overlay);
|
||||||
overlay.querySelector('input').focus();
|
overlay.querySelector('input').focus();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpFormatFingerprint(value) {
|
function pgpFormatFingerprint(value) {
|
||||||
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpSignatureHtml(signatures, encrypted) {
|
function pgpSignatureHtml(signatures, encrypted) {
|
||||||
const items = Array.isArray(signatures) ? signatures : [];
|
const items = Array.isArray(signatures) ? signatures : [];
|
||||||
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
||||||
if (!items.length) {
|
if (!items.length) {
|
||||||
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
||||||
}
|
}
|
||||||
return items.map(signature => {
|
return items.map(signature => {
|
||||||
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
||||||
const notes = [];
|
const notes = [];
|
||||||
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
||||||
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
||||||
if (signature.status === 'valid') {
|
if (signature.status === 'valid') {
|
||||||
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
||||||
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}</strong><span>${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
||||||
}
|
}
|
||||||
if (signature.status === 'unknown-key') {
|
if (signature.status === 'unknown-key') {
|
||||||
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${escapePgpMailUi(note)}</small>`).join('')}</section>`;
|
||||||
}
|
}
|
||||||
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
||||||
}).join('');
|
}).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpAddAttachedKey(key) {
|
async function pgpAddAttachedKey(key) {
|
||||||
const emails = key.emails.join(', ') || 'unknown address';
|
const emails = key.emails.join(', ') || 'unknown address';
|
||||||
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
||||||
try {
|
try {
|
||||||
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
||||||
toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
toastPgpMailUi(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastPgpMailUi(error.message || 'Could not add the key');
|
toastPgpMailUi(error.message || 'Could not add the key');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function pgpRenderReaderState(message) {
|
function pgpRenderReaderState(message) {
|
||||||
const reader = selectPgpMailUi('#reader-pane');
|
const reader = selectPgpMailUi('#reader-pane');
|
||||||
const header = reader.querySelector('.reader-header');
|
const header = reader.querySelector('.reader-header');
|
||||||
if (!header) return;
|
if (!header) return;
|
||||||
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
||||||
let html = '';
|
let html = '';
|
||||||
if (message.encrypted && !message.pgpDecrypted) {
|
if (message.encrypted && !message.pgpDecrypted) {
|
||||||
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
||||||
} else if (message.encrypted) {
|
} else if (message.encrypted) {
|
||||||
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
||||||
} else if (message.pgpSignatures) {
|
} else if (message.signed && Array.isArray(message.pgpSignatures)) {
|
||||||
html = pgpSignatureHtml(message.pgpSignatures, false);
|
html = pgpSignatureHtml(message.pgpSignatures, false);
|
||||||
}
|
} else if (message.signed && message.pgpVerifyFailed) {
|
||||||
const keys = message.pgpResult?.attachedKeys || [];
|
html = `<section class="pgp-status pgp-warn" role="status"><strong>Could not check the OpenPGP signature</strong><span>${escapePgpMailUi(message.pgpVerifyFailed)}</span></section>`;
|
||||||
|
} else if (message.signed) {
|
||||||
|
html = '<section class="pgp-status pgp-warn" role="status"><strong>Checking OpenPGP signature…</strong><span>Do not rely on this message until verification completes.</span></section>';
|
||||||
|
} else if (message.pgpSignatures) {
|
||||||
|
html = pgpSignatureHtml(message.pgpSignatures, false);
|
||||||
|
}
|
||||||
|
const keys = message.pgpResult?.attachedKeys || [];
|
||||||
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
||||||
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
||||||
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
||||||
});
|
});
|
||||||
const unlock = selectPgpMailUi('#pgp-unlock');
|
const unlock = selectPgpMailUi('#pgp-unlock');
|
||||||
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function pgpUnlockMessage(message, interactive) {
|
async function pgpUnlockMessage(message, interactive) {
|
||||||
let passphrase = null;
|
let passphrase = null;
|
||||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||||
let result;
|
let result;
|
||||||
try {
|
try {
|
||||||
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
toastPgpMailUi(error.message || 'Could not open this message');
|
toastPgpMailUi(error.message || 'Could not open this message');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (result.ok) {
|
if (result.ok) {
|
||||||
Object.assign(message, {
|
Object.assign(message, {
|
||||||
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
||||||
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
||||||
});
|
});
|
||||||
if (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'
|
||||||
if (passphrase === null) return;
|
? 'That passphrase was incorrect. Try again.'
|
||||||
continue;
|
: result.code === 'BIOMETRIC_INVALIDATED'
|
||||||
}
|
? `${result.message} Enter the passphrase to continue.`
|
||||||
const text = selectPgpMailUi('#pgp-banner-text');
|
: `Enter the passphrase for ${result.email || 'your key'}.`;
|
||||||
if (text) text.textContent = result.message;
|
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
|
||||||
else toastPgpMailUi(result.message);
|
if (passphrase === null) return;
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
}
|
const text = selectPgpMailUi('#pgp-banner-text');
|
||||||
|
if (text) text.textContent = result.message;
|
||||||
|
else toastPgpMailUi(result.message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pgpVerifyMessage(message) {
|
||||||
|
try {
|
||||||
|
const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid });
|
||||||
|
if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.';
|
||||||
|
else {
|
||||||
|
message.pgpSignatures = result.signatures || [];
|
||||||
|
message.pgpVerifyFailed = null;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
message.pgpVerifyFailed = error.message || 'The signature could not be checked.';
|
||||||
|
}
|
||||||
|
if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message);
|
||||||
|
}
|
||||||
|
|
||||||
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
|
||||||
baseOpenMessage(id);
|
baseOpenMessage(id);
|
||||||
const message = pgpMailUi.state.messages.find(item => item.id === id);
|
const message = pgpMailUi.state.messages.find(item => item.id === id);
|
||||||
if (!message || !pgpApi()) return;
|
if (!message || !pgpApi()) return;
|
||||||
pgpRenderReaderState(message);
|
pgpRenderReaderState(message);
|
||||||
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
||||||
message.pgpAutoTried = true;
|
message.pgpAutoTried = true;
|
||||||
void pgpUnlockMessage(message, false);
|
void pgpUnlockMessage(message, false);
|
||||||
}
|
}
|
||||||
|
if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) {
|
||||||
|
message.pgpVerifyTried = true;
|
||||||
|
void pgpVerifyMessage(message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Compose: encrypt/sign options.
|
// Compose: encrypt/sign options.
|
||||||
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
|
pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false, draft = null) {
|
||||||
baseShowCompose(reply, forward);
|
baseShowCompose(reply, forward, draft);
|
||||||
const footer = selectPgpMailUi('#modal-root .compose-footer');
|
const footer = selectPgpMailUi('#modal-root .compose-footer');
|
||||||
if (!footer || !pgpApi()) return;
|
if (!footer || !pgpApi()) return;
|
||||||
const box = document.createElement('div');
|
const box = document.createElement('div');
|
||||||
box.className = 'pgp-compose';
|
box.className = 'pgp-compose';
|
||||||
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
|
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label>${pgpApi().platform === 'android' ? '<small class="account-note">Experimental Android OpenPGP test build; not independently reviewed. Do not rely on it for sensitive mail.</small>' : ''}<small id="pgp-hint"></small>`;
|
||||||
footer.prepend(box);
|
footer.prepend(box);
|
||||||
let touched = false;
|
let touched = false;
|
||||||
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
const encrypt = selectPgpMailUi('#pgp-encrypt');
|
||||||
const sign = selectPgpMailUi('#pgp-sign');
|
const sign = selectPgpMailUi('#pgp-sign');
|
||||||
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
||||||
if (touched) encrypt.dataset.touched = '1';
|
if (touched) encrypt.dataset.touched = '1';
|
||||||
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
||||||
let timer = null;
|
let timer = null;
|
||||||
const refresh = async () => {
|
const refresh = async () => {
|
||||||
const to = selectPgpMailUi('#compose-to')?.value || '';
|
const to = selectPgpMailUi('#compose-to')?.value || '';
|
||||||
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
const cc = selectPgpMailUi('#compose-cc')?.value || '';
|
||||||
const hint = selectPgpMailUi('#pgp-hint');
|
const hint = selectPgpMailUi('#pgp-hint');
|
||||||
if (!hint) return;
|
if (!hint) return;
|
||||||
if (!to.trim()) { hint.textContent = ''; return; }
|
if (!to.trim()) { hint.textContent = ''; return; }
|
||||||
try {
|
try {
|
||||||
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
||||||
if (!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 = ''; }
|
||||||
};
|
};
|
||||||
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
||||||
['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
|
['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule));
|
||||||
sign.addEventListener('change', schedule);
|
sign.addEventListener('change', schedule);
|
||||||
schedule();
|
schedule();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
||||||
@@ -172,30 +201,30 @@ async function prepareSend(to, cc) {
|
|||||||
const plaintextFallback = () => pgpApi().platform === 'android'
|
const plaintextFallback = () => pgpApi().platform === 'android'
|
||||||
? { encrypt: false, sign: false, plaintextFallback: true }
|
? { encrypt: false, sign: false, plaintextFallback: true }
|
||||||
: null;
|
: null;
|
||||||
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked);
|
||||||
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked);
|
||||||
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null;
|
||||||
const status = await pgpApi().checkSend({ to, cc, sign });
|
const status = await pgpApi().checkSend({ to, cc, sign });
|
||||||
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
|
||||||
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') {
|
||||||
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
|
||||||
if (!sign) return plaintextFallback();
|
if (!sign) return plaintextFallback();
|
||||||
} else return false;
|
} else return false;
|
||||||
}
|
}
|
||||||
if (!encrypt && !sign) return null;
|
if (!encrypt && !sign) return null;
|
||||||
if (encrypt && status.missing.length) {
|
if (encrypt && status.missing.length) {
|
||||||
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
|
||||||
if (!sendPlain) return false;
|
if (!sendPlain) return false;
|
||||||
encrypt = false;
|
encrypt = false;
|
||||||
if (!sign) return plaintextFallback();
|
if (!sign) return plaintextFallback();
|
||||||
}
|
}
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { encrypt, sign, passphrase };
|
return { encrypt, sign, passphrase };
|
||||||
}
|
}
|
||||||
|
|||||||
+432
-398
@@ -14,14 +14,12 @@ async function saveAndroidPgpExport(label, value) {
|
|||||||
else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true };
|
else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true };
|
||||||
return { saved: true };
|
return { saved: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
function openEncryptionKeys() {
|
function openEncryptionKeys() {
|
||||||
const root = selectPgpKeyUi('#modal-root');
|
const root = selectPgpKeyUi('#modal-root');
|
||||||
const account = window.epMailFeatures.mail.connectedAccount || {};
|
const account = window.epMailFeatures.mail.connectedAccount || {};
|
||||||
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
|
const androidPgp = window.daybreakMail?.pgp?.platform === 'android';
|
||||||
const serverSettings = androidPgp
|
const serverSettings = `<h3 class="pgp-heading">Public key servers</h3>
|
||||||
? '<h3 class="pgp-heading">Public key servers</h3><p class="account-note">Key-server lookup and publication are disabled in Android testing. Import a public key directly and compare its fingerprint with the owner.</p><div hidden><div id="pgp-server-list"></div><input id="pgp-search-email"><button id="pgp-find-key"></button><div id="pgp-found-keys"></div><select id="pgp-publish-server"></select><input id="pgp-server-name"><input id="pgp-server-url"><select id="pgp-server-protocol"></select><button id="pgp-add-server"></button></div>'
|
|
||||||
: `<h3 class="pgp-heading">Public key servers</h3>
|
|
||||||
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
|
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
|
||||||
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
|
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
|
||||||
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
@@ -34,402 +32,438 @@ function openEncryptionKeys() {
|
|||||||
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
|
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
|
||||||
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
|
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
|
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
|
||||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal pgp-keys-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
||||||
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. 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>
|
||||||
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
||||||
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
||||||
<h3 class="pgp-heading">Contact public keys</h3>
|
<h3 class="pgp-heading">Contact public keys</h3>
|
||||||
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
||||||
${serverSettings}
|
${serverSettings}
|
||||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||||
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
||||||
<h3 class="pgp-heading">Create a key</h3>
|
<h3 class="pgp-heading">Create a key</h3>
|
||||||
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${escapePgpKeyUi(account.displayName || '')}"></label>
|
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${escapePgpKeyUi(account.displayName || '')}"></label>
|
||||||
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${escapePgpKeyUi(account.email || '')}"></label>
|
||||||
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||||
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div>
|
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">${androidPgp ? 'Import private key from file…' : 'Import private key…'}</button>${androidPgp ? '<button class="discard" id="pgp-import-paste">Paste private key…</button>' : ''}</div>
|
||||||
<p class="account-note" id="pgp-status" role="status"></p>
|
<p class="account-note" id="pgp-status" role="status"></p>
|
||||||
</div></div></div>`;
|
</div></div></div>`;
|
||||||
const close = () => { root.innerHTML = ''; };
|
const close = () => { root.innerHTML = ''; };
|
||||||
root.querySelector('.modal-close').onclick = close;
|
root.querySelector('.modal-close').onclick = close;
|
||||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||||
const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; };
|
||||||
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
const passphraseField = () => selectPgpKeyUi('#pgp-passphrase');
|
||||||
let keyServers = [];
|
let keyServers = [];
|
||||||
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled);
|
||||||
const updatePublishButtons = () => {
|
const updatePublishButtons = () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
selectAllPgpKeyUi('.pgp-publish').forEach(button => {
|
||||||
button.disabled = !server;
|
button.disabled = !server;
|
||||||
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
const needPassphrase = () => {
|
const needPassphrase = () => {
|
||||||
const value = passphraseField().value;
|
const value = passphraseField().value;
|
||||||
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
||||||
return value;
|
return value;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function render() {
|
async function render() {
|
||||||
const list = selectPgpKeyUi('#pgp-key-list');
|
const list = selectPgpKeyUi('#pgp-key-list');
|
||||||
let keys = [];
|
let keys = [];
|
||||||
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
||||||
keys.forEach(key => {
|
keys.forEach(key => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = key.email || 'OpenPGP key';
|
title.textContent = key.email || 'OpenPGP key';
|
||||||
const meta = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
||||||
const fingerprint = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
info.append(title, meta, fingerprint);
|
info.append(title, meta, fingerprint);
|
||||||
row.append(info);
|
row.append(info);
|
||||||
const actions = [
|
const actions = [
|
||||||
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
||||||
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
||||||
];
|
];
|
||||||
const changePassphrase = document.createElement('button');
|
const changePassphrase = document.createElement('button');
|
||||||
changePassphrase.className = 'discard';
|
changePassphrase.className = 'discard';
|
||||||
changePassphrase.textContent = 'Change passphrase…';
|
changePassphrase.textContent = 'Change passphrase…';
|
||||||
changePassphrase.onclick = async () => {
|
changePassphrase.onclick = async () => {
|
||||||
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value;
|
||||||
if (!currentPassphrase) {
|
if (!currentPassphrase) {
|
||||||
status('Enter the current passphrase for this key.');
|
status('Enter the current passphrase for this key.');
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
selectPgpKeyUi('#pgp-change-current-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value;
|
||||||
if (newPassphrase.length < 8) {
|
if (newPassphrase.length < 8) {
|
||||||
status('Use a new passphrase of at least 8 characters.');
|
status('Use a new passphrase of at least 8 characters.');
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
selectPgpKeyUi('#pgp-new-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) {
|
||||||
status('The new passphrases do not match.');
|
status('The new passphrases do not match.');
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
selectPgpKeyUi('#pgp-confirm-passphrase').focus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
changePassphrase.disabled = true;
|
changePassphrase.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.changePassphrase({
|
await window.daybreakMail.pgp.changePassphrase({
|
||||||
fingerprint: key.fingerprint,
|
fingerprint: key.fingerprint,
|
||||||
currentPassphrase,
|
currentPassphrase,
|
||||||
newPassphrase
|
newPassphrase
|
||||||
});
|
});
|
||||||
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
selectPgpKeyUi('#pgp-change-current-passphrase').value = '';
|
||||||
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
||||||
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
||||||
finally {
|
finally {
|
||||||
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
selectPgpKeyUi('#pgp-new-passphrase').value = '';
|
||||||
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
selectPgpKeyUi('#pgp-confirm-passphrase').value = '';
|
||||||
changePassphrase.disabled = false;
|
changePassphrase.disabled = false;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
row.append(changePassphrase);
|
row.append(changePassphrase);
|
||||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
if (androidPgp) {
|
||||||
actions.push(['Delete', async () => {
|
const biometric = document.createElement('button');
|
||||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
biometric.className = 'discard';
|
||||||
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
biometric.textContent = 'Checking biometric unlock…';
|
||||||
await render();
|
biometric.disabled = true;
|
||||||
return { deleted: true };
|
row.append(biometric);
|
||||||
}, true]);
|
window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => {
|
||||||
actions.forEach(([label, run, secret]) => {
|
if (!biometric.isConnected) return;
|
||||||
const button = document.createElement('button');
|
biometric.dataset.enabled = String(enabled);
|
||||||
button.className = 'discard';
|
biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…';
|
||||||
button.textContent = label;
|
biometric.disabled = false;
|
||||||
button.onclick = async () => {
|
}).catch(error => {
|
||||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.');
|
||||||
try {
|
});
|
||||||
|
biometric.onclick = async () => {
|
||||||
|
biometric.disabled = true;
|
||||||
|
try {
|
||||||
|
if (biometric.dataset.enabled === 'true') {
|
||||||
|
if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return;
|
||||||
|
await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint);
|
||||||
|
status('Biometric unlock disabled.');
|
||||||
|
} else {
|
||||||
|
const passphrase = needPassphrase();
|
||||||
|
if (!passphrase) return;
|
||||||
|
await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase });
|
||||||
|
passphraseField().value = '';
|
||||||
|
status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.');
|
||||||
|
}
|
||||||
|
await render();
|
||||||
|
} catch (error) {
|
||||||
|
status(error.message || 'Could not update biometric key unlock.');
|
||||||
|
} finally {
|
||||||
|
biometric.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||||
|
actions.push(['Delete', async () => {
|
||||||
|
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||||
|
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
||||||
|
await render();
|
||||||
|
return { deleted: true };
|
||||||
|
}, true]);
|
||||||
|
actions.forEach(([label, run, secret]) => {
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.className = 'discard';
|
||||||
|
button.textContent = label;
|
||||||
|
button.onclick = async () => {
|
||||||
|
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||||
|
try {
|
||||||
const result = await saveAndroidPgpExport(label, await run());
|
const result = await saveAndroidPgpExport(label, await run());
|
||||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||||
} catch (error) { status(error.message || 'That action failed.'); }
|
} catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
const publish = document.createElement('button');
|
const publish = document.createElement('button');
|
||||||
publish.className = 'discard pgp-publish';
|
publish.className = 'discard pgp-publish';
|
||||||
publish.onclick = async () => {
|
publish.onclick = async () => {
|
||||||
const server = selectedPublishServer();
|
const server = selectedPublishServer();
|
||||||
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
||||||
publish.disabled = true;
|
publish.disabled = true;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
||||||
if (result.canceled) return;
|
if (result.canceled) return;
|
||||||
if (result.warning) status(result.warning);
|
if (result.warning) status(result.warning);
|
||||||
else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${server.name}. Check ${key.email || 'your email'} for a verification message before the key becomes searchable.`);
|
else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${server.name}. Check ${key.email || 'your email'} for a verification message before the key becomes searchable.`);
|
||||||
else if (result.verification === 'published') status(`The key is already published and searchable on ${server.name}.`);
|
else if (result.verification === 'published') status(`The key is already published and searchable on ${server.name}.`);
|
||||||
else if (result.verification === 'request-failed') status('The key was uploaded, but the server could not request email verification.');
|
else if (result.verification === 'request-failed') status('The key was uploaded, but the server could not request email verification.');
|
||||||
else if (result.verification === 'check-email') status(`${server.name} accepted the key. Check ${key.email || 'your email'} for its verification message. ${result.message || ''}`.trim());
|
else if (result.verification === 'check-email') status(`${server.name} accepted the key. Check ${key.email || 'your email'} for its verification message. ${result.message || ''}`.trim());
|
||||||
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
||||||
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
||||||
finally { updatePublishButtons(); }
|
finally { updatePublishButtons(); }
|
||||||
};
|
};
|
||||||
row.append(publish);
|
row.append(publish);
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
updatePublishButtons();
|
updatePublishButtons();
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
selectPgpKeyUi('#pgp-generate').onclick = async () => {
|
||||||
const button = selectPgpKeyUi('#pgp-generate');
|
const button = selectPgpKeyUi('#pgp-generate');
|
||||||
button.disabled = true;
|
button.disabled = true;
|
||||||
status('Creating key…');
|
status('Creating key…');
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.generate({
|
await window.daybreakMail.pgp.generate({
|
||||||
name: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
name: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
||||||
});
|
});
|
||||||
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
||||||
await render();
|
await render();
|
||||||
} catch (error) { status(error.message || 'Could not create the key.'); }
|
} catch (error) { status(error.message || 'Could not create the key.'); }
|
||||||
button.disabled = false;
|
button.disabled = false;
|
||||||
};
|
};
|
||||||
selectPgpKeyUi('#pgp-import').onclick = async () => {
|
const importPrivateKey = async source => {
|
||||||
const passphrase = needPassphrase();
|
const passphrase = needPassphrase();
|
||||||
if (!passphrase) return;
|
if (!passphrase) return;
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null, ...(androidPgp ? { source } : {}) });
|
||||||
status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.');
|
status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.');
|
||||||
await render();
|
if (!result.canceled) await render();
|
||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
async function renderContacts() {
|
selectPgpKeyUi('#pgp-import').onclick = () => importPrivateKey(androidPgp ? 'file' : undefined);
|
||||||
const list = selectPgpKeyUi('#pgp-contact-list');
|
if (androidPgp) selectPgpKeyUi('#pgp-import-paste').onclick = () => importPrivateKey('paste');
|
||||||
let contacts = [];
|
async function renderContacts() {
|
||||||
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
const list = selectPgpKeyUi('#pgp-contact-list');
|
||||||
list.replaceChildren();
|
let contacts = [];
|
||||||
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
||||||
contacts.forEach(contact => {
|
list.replaceChildren();
|
||||||
const row = document.createElement('div');
|
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
||||||
row.className = 'attachment-row';
|
contacts.forEach(contact => {
|
||||||
const info = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
row.className = 'attachment-row';
|
||||||
const title = document.createElement('strong');
|
const info = document.createElement('div');
|
||||||
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
info.className = 'attachment-row-info';
|
||||||
const meta = document.createElement('small');
|
const title = document.createElement('strong');
|
||||||
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
title.textContent = contact.emails.join(', ') || contact.name || 'Public key';
|
||||||
const fingerprint = document.createElement('small');
|
const meta = document.createElement('small');
|
||||||
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
||||||
info.append(title, meta, fingerprint);
|
const fingerprint = document.createElement('small');
|
||||||
const trust = document.createElement('select');
|
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
trust.className = 'pgp-trust';
|
info.append(title, meta, fingerprint);
|
||||||
trust.setAttribute('aria-label', 'Key trust');
|
const trust = document.createElement('select');
|
||||||
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
trust.className = 'pgp-trust';
|
||||||
const option = document.createElement('option');
|
trust.setAttribute('aria-label', 'Key trust');
|
||||||
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
||||||
trust.append(option);
|
const option = document.createElement('option');
|
||||||
});
|
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
||||||
trust.onchange = async () => {
|
trust.append(option);
|
||||||
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
});
|
||||||
trust.value = contact.trust;
|
trust.onchange = async () => {
|
||||||
return;
|
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
||||||
}
|
trust.value = contact.trust;
|
||||||
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
return;
|
||||||
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
}
|
||||||
};
|
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
||||||
const actions = [
|
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
||||||
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
};
|
||||||
['Remove', async () => {
|
const actions = [
|
||||||
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
||||||
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
['Remove', async () => {
|
||||||
await renderContacts();
|
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
||||||
return { deleted: true };
|
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
||||||
}]
|
await renderContacts();
|
||||||
];
|
return { deleted: true };
|
||||||
row.append(info, trust);
|
}]
|
||||||
actions.forEach(([label, run]) => {
|
];
|
||||||
const button = document.createElement('button');
|
row.append(info, trust);
|
||||||
button.className = 'discard';
|
actions.forEach(([label, run]) => {
|
||||||
button.textContent = label;
|
const button = document.createElement('button');
|
||||||
button.onclick = async () => {
|
button.className = 'discard';
|
||||||
|
button.textContent = label;
|
||||||
|
button.onclick = async () => {
|
||||||
try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); }
|
try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||||
catch (error) { status(error.message || 'That action failed.'); }
|
catch (error) { status(error.message || 'That action failed.'); }
|
||||||
};
|
};
|
||||||
row.append(button);
|
row.append(button);
|
||||||
});
|
});
|
||||||
list.append(row);
|
list.append(row);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
selectPgpKeyUi('#pgp-add-contact').onclick = async () => {
|
selectPgpKeyUi('#pgp-add-contact').onclick = async () => {
|
||||||
try {
|
try {
|
||||||
const result = await window.daybreakMail.pgp.addContact({});
|
const result = await window.daybreakMail.pgp.addContact({});
|
||||||
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
||||||
await renderContacts();
|
await renderContacts();
|
||||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||||
};
|
};
|
||||||
async function renderKeyServers() {
|
async function renderKeyServers() {
|
||||||
const list = selectPgpKeyUi('#pgp-server-list');
|
const list = selectPgpKeyUi('#pgp-server-list');
|
||||||
const selector = selectPgpKeyUi('#pgp-publish-server');
|
const selector = selectPgpKeyUi('#pgp-publish-server');
|
||||||
const selectedId = selector.value;
|
const selectedId = selector.value;
|
||||||
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
||||||
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
||||||
selector.replaceChildren();
|
selector.replaceChildren();
|
||||||
const enabledServers = keyServers.filter(server => server.enabled);
|
const enabledServers = keyServers.filter(server => server.enabled);
|
||||||
if (!enabledServers.length) {
|
if (!enabledServers.length) {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = '';
|
option.value = '';
|
||||||
option.textContent = 'No enabled servers';
|
option.textContent = 'No enabled servers';
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
} else enabledServers.forEach(server => {
|
} else enabledServers.forEach(server => {
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = server.id;
|
option.value = server.id;
|
||||||
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
||||||
option.selected = server.id === selectedId;
|
option.selected = server.id === selectedId;
|
||||||
selector.append(option);
|
selector.append(option);
|
||||||
});
|
});
|
||||||
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
||||||
selector.onchange = updatePublishButtons;
|
selector.onchange = updatePublishButtons;
|
||||||
list.replaceChildren();
|
list.replaceChildren();
|
||||||
keyServers.forEach(server => {
|
keyServers.forEach(server => {
|
||||||
const row = document.createElement('div');
|
const row = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
row.className = 'attachment-row';
|
||||||
const info = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
info.className = 'attachment-row-info';
|
info.className = 'attachment-row-info';
|
||||||
const title = document.createElement('strong');
|
const title = document.createElement('strong');
|
||||||
title.textContent = server.name;
|
title.textContent = server.name;
|
||||||
const details = document.createElement('small');
|
const details = document.createElement('small');
|
||||||
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
||||||
info.append(title, details);
|
info.append(title, details);
|
||||||
const enabledLabel = document.createElement('label');
|
const enabledLabel = document.createElement('label');
|
||||||
enabledLabel.className = 'compose-line';
|
enabledLabel.className = 'compose-line';
|
||||||
const enabledText = document.createElement('span');
|
const enabledText = document.createElement('span');
|
||||||
enabledText.textContent = 'Use for lookup and publishing';
|
enabledText.textContent = 'Use for lookup and publishing';
|
||||||
const enabled = document.createElement('input');
|
const enabled = document.createElement('input');
|
||||||
enabled.type = 'checkbox';
|
enabled.type = 'checkbox';
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
||||||
enabled.onchange = async () => {
|
enabled.onchange = async () => {
|
||||||
enabled.disabled = true;
|
enabled.disabled = true;
|
||||||
try {
|
try {
|
||||||
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
||||||
await renderKeyServers();
|
await renderKeyServers();
|
||||||
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
enabled.checked = server.enabled;
|
enabled.checked = server.enabled;
|
||||||
status(error.message || `Could not update ${server.name}.`);
|
status(error.message || `Could not update ${server.name}.`);
|
||||||
} finally { enabled.disabled = false; }
|
} finally { enabled.disabled = false; }
|
||||||
};
|
};
|
||||||
enabledLabel.append(enabledText, enabled);
|
enabledLabel.append(enabledText, enabled);
|
||||||
row.append(info, enabledLabel);
|
row.append(info, enabledLabel);
|
||||||
if (!server.builtin) {
|
const remove = document.createElement('button');
|
||||||
const remove = document.createElement('button');
|
remove.className = 'discard';
|
||||||
remove.className = 'discard';
|
remove.textContent = 'Remove';
|
||||||
remove.textContent = 'Remove';
|
remove.onclick = async () => {
|
||||||
remove.onclick = async () => {
|
try {
|
||||||
try {
|
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
||||||
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
await renderKeyServers();
|
||||||
await renderKeyServers();
|
status(`${server.name} removed.`);
|
||||||
status('Custom key server removed.');
|
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
||||||
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
};
|
||||||
};
|
row.append(remove);
|
||||||
row.append(remove);
|
list.append(row);
|
||||||
}
|
});
|
||||||
list.append(row);
|
}
|
||||||
});
|
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
||||||
}
|
const button = selectPgpKeyUi('#pgp-find-key');
|
||||||
selectPgpKeyUi('#pgp-find-key').onclick = async () => {
|
const results = selectPgpKeyUi('#pgp-found-keys');
|
||||||
const button = selectPgpKeyUi('#pgp-find-key');
|
button.disabled = true;
|
||||||
const results = selectPgpKeyUi('#pgp-found-keys');
|
results.textContent = 'Searching…';
|
||||||
button.disabled = true;
|
try {
|
||||||
results.textContent = 'Searching…';
|
const found = await window.daybreakMail.pgp.findKey({
|
||||||
try {
|
email: selectPgpKeyUi('#pgp-search-email').value
|
||||||
const found = await window.daybreakMail.pgp.findKey({
|
});
|
||||||
email: selectPgpKeyUi('#pgp-search-email').value
|
results.replaceChildren();
|
||||||
});
|
found.keys.forEach(key => {
|
||||||
results.replaceChildren();
|
const row = document.createElement('div');
|
||||||
found.keys.forEach(key => {
|
row.className = 'attachment-row';
|
||||||
const row = document.createElement('div');
|
const info = document.createElement('div');
|
||||||
row.className = 'attachment-row';
|
info.className = 'attachment-row-info';
|
||||||
const info = document.createElement('div');
|
const title = document.createElement('strong');
|
||||||
info.className = 'attachment-row-info';
|
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
||||||
const title = document.createElement('strong');
|
const meta = document.createElement('small');
|
||||||
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
||||||
const meta = document.createElement('small');
|
const fingerprint = document.createElement('small');
|
||||||
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||||
const fingerprint = document.createElement('small');
|
info.append(title, meta, fingerprint);
|
||||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
const add = document.createElement('button');
|
||||||
info.append(title, meta, fingerprint);
|
add.className = 'discard';
|
||||||
const add = document.createElement('button');
|
add.textContent = 'Add to contacts…';
|
||||||
add.className = 'discard';
|
add.onclick = async () => {
|
||||||
add.textContent = 'Add to contacts…';
|
add.disabled = true;
|
||||||
add.onclick = async () => {
|
try {
|
||||||
add.disabled = true;
|
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||||
try {
|
if (result.canceled) return;
|
||||||
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
status(result.keyChangedFrom?.length ? 'Key added. You already had another key for this address; compare fingerprints before trusting either key.' : 'Key added as unverified. Compare its fingerprint with the owner before trusting it.');
|
||||||
if (result.canceled) return;
|
await renderContacts();
|
||||||
status(result.keyChangedFrom?.length ? 'Key added. You already had another key for this address; compare fingerprints before trusting either key.' : 'Key added as unverified. Compare its fingerprint with the owner before trusting it.');
|
row.remove();
|
||||||
await renderContacts();
|
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
||||||
row.remove();
|
finally { add.disabled = false; }
|
||||||
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
};
|
||||||
finally { add.disabled = false; }
|
row.append(info, add);
|
||||||
};
|
results.append(row);
|
||||||
row.append(info, add);
|
});
|
||||||
results.append(row);
|
found.errors.forEach(error => {
|
||||||
});
|
const warning = document.createElement('small');
|
||||||
found.errors.forEach(error => {
|
warning.textContent = `${error.name}: ${error.message}`;
|
||||||
const warning = document.createElement('small');
|
results.append(warning);
|
||||||
warning.textContent = `${error.name}: ${error.message}`;
|
});
|
||||||
results.append(warning);
|
if (!found.keys.length && !found.errors.length) results.textContent = 'No matching public key was found on the enabled servers.';
|
||||||
});
|
if (found.keys.length) status(`Found ${found.keys.length} public key(s) on ${found.searchedServers.map(server => server.name).join(', ')}. They remain unverified until you check their fingerprints independently.${found.errors.length ? ` ${found.errors.length} server(s) could not be searched; see details above.` : ''}`);
|
||||||
if (!found.keys.length && !found.errors.length) results.textContent = 'No matching public key was found on the enabled servers.';
|
else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`);
|
||||||
if (found.keys.length) status(`Found ${found.keys.length} public key(s) on ${found.searchedServers.map(server => server.name).join(', ')}. They remain unverified until you check their fingerprints independently.${found.errors.length ? ` ${found.errors.length} server(s) could not be searched; see details above.` : ''}`);
|
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
||||||
else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`);
|
} catch (error) {
|
||||||
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
results.textContent = '';
|
||||||
} catch (error) {
|
status(error.message || 'Could not search the key server.');
|
||||||
results.textContent = '';
|
} finally { button.disabled = false; }
|
||||||
status(error.message || 'Could not search the key server.');
|
};
|
||||||
} finally { button.disabled = false; }
|
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
||||||
};
|
const button = selectPgpKeyUi('#pgp-add-server');
|
||||||
selectPgpKeyUi('#pgp-add-server').onclick = async () => {
|
button.disabled = true;
|
||||||
const button = selectPgpKeyUi('#pgp-add-server');
|
try {
|
||||||
button.disabled = true;
|
const result = await window.daybreakMail.pgp.addKeyServer({
|
||||||
try {
|
name: selectPgpKeyUi('#pgp-server-name').value,
|
||||||
const result = await window.daybreakMail.pgp.addKeyServer({
|
url: selectPgpKeyUi('#pgp-server-url').value,
|
||||||
name: selectPgpKeyUi('#pgp-server-name').value,
|
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
||||||
url: selectPgpKeyUi('#pgp-server-url').value,
|
});
|
||||||
protocol: selectPgpKeyUi('#pgp-server-protocol').value
|
if (result.canceled) return;
|
||||||
});
|
selectPgpKeyUi('#pgp-server-name').value = '';
|
||||||
if (result.canceled) return;
|
selectPgpKeyUi('#pgp-server-url').value = '';
|
||||||
selectPgpKeyUi('#pgp-server-name').value = '';
|
await renderKeyServers();
|
||||||
selectPgpKeyUi('#pgp-server-url').value = '';
|
status('Custom key server added.');
|
||||||
await renderKeyServers();
|
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
||||||
status('Custom key server added.');
|
finally { button.disabled = false; }
|
||||||
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
};
|
||||||
finally { button.disabled = false; }
|
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||||
};
|
selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
|
||||||
window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number(selectPgpKeyUi('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
||||||
selectPgpKeyUi('#pgp-save-cache').onclick = async () => {
|
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||||
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number(selectPgpKeyUi('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
};
|
||||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||||
};
|
void renderKeyServers();
|
||||||
selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
void renderContacts();
|
||||||
if (!androidPgp) void renderKeyServers();
|
void render();
|
||||||
void renderContacts();
|
}
|
||||||
void render();
|
|
||||||
}
|
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => async function () {
|
||||||
|
await baseOpenPreferences();
|
||||||
window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () {
|
const fields = selectPgpKeyUi('#modal-root .compose-fields');
|
||||||
baseOpenPreferences();
|
if (!fields || !pgpAvailable()) return;
|
||||||
const fields = selectPgpKeyUi('#modal-root .compose-fields');
|
const button = document.createElement('button');
|
||||||
if (!fields || !pgpAvailable()) return;
|
button.type = 'button';
|
||||||
const button = document.createElement('button');
|
button.className = 'discard';
|
||||||
button.type = 'button';
|
button.id = 'open-encryption-keys';
|
||||||
button.className = 'discard';
|
button.textContent = 'Encryption keys…';
|
||||||
button.id = 'open-encryption-keys';
|
button.onclick = openEncryptionKeys;
|
||||||
button.textContent = 'Encryption keys…';
|
fields.append(button);
|
||||||
button.onclick = openEncryptionKeys;
|
|
||||||
fields.append(button);
|
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
|
|||||||
+5976
-5120
File diff suppressed because one or more lines are too long
+46
-43
@@ -6,58 +6,61 @@ const selectAllProductivityUi = productivityMailUi.selectAll;
|
|||||||
const toastProductivityUi = productivityMailUi.toast;
|
const toastProductivityUi = productivityMailUi.toast;
|
||||||
const escapeProductivityUi = productivityMailUi.escapeHtml;
|
const escapeProductivityUi = productivityMailUi.escapeHtml;
|
||||||
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
|
const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' };
|
||||||
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
|
const productRead = (key, fallback) => { try { const value = JSON.parse(localStorage.getItem(key)); return value ?? fallback; } catch { return fallback; } };
|
||||||
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
|
const productWrite = (key, value) => localStorage.setItem(key, JSON.stringify(value));
|
||||||
let profileSettings = productRead(productKeys.profile, { name: '' });
|
let profileSettings = productRead(productKeys.profile, { name: '' });
|
||||||
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
if (/^mira(\s+sol)?$/i.test(profileSettings.name || '')) { profileSettings = { name: '' }; localStorage.removeItem(productKeys.profile); }
|
||||||
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
let calendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
|
||||||
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
const generatedContactEmails = new Set(['amelia@northstar.design','jonah@fieldnotes.co','sofia@smallhours.works','mateo@roam.travel','eden@paperandpine.com','noah@common-thread.org','iris@littlefern.press']);
|
||||||
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
let savedContacts = productRead(productKeys.contacts, []).filter(contact => !generatedContactEmails.has(String(contact.email||'').toLowerCase()));
|
||||||
productWrite(productKeys.contacts, savedContacts);
|
productWrite(productKeys.contacts, savedContacts);
|
||||||
let savedEvents = productRead(productKeys.events, []);
|
let savedEvents = productRead(productKeys.events, []);
|
||||||
let customLabels = productRead(productKeys.labels, []);
|
let customLabels = productRead(productKeys.labels, []);
|
||||||
let snoozedIds = productRead(productKeys.snoozed, []);
|
let snoozedIds = productRead(productKeys.snoozed, []);
|
||||||
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=selectProductivityUi('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=selectProductivityUi('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (productivityMailUi.connectedAccount) productivityMailUi.updateAccountCard(productivityMailUi.connectedAccount); }
|
function setProfileName(name) { profileSettings.name = name.trim(); productWrite(productKeys.profile, profileSettings); const first = profileSettings.name.split(/\s+/)[0] || ''; const greeting=selectProductivityUi('#greeting-name'); greeting.textContent=first; greeting.hidden=!first; const heading=selectProductivityUi('#welcome-heading'); if(heading) heading.firstChild.textContent=first?'Good morning, ':'Good morning'; if (productivityMailUi.connectedAccount) productivityMailUi.updateAccountCard(productivityMailUi.connectedAccount); }
|
||||||
function openAccountSettings() {
|
function openAccountSettings() {
|
||||||
const root=selectProductivityUi('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Account Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Display name</span><input id="profile-name" maxlength="80" value="${escapeProductivityUi(profileSettings.name)}" placeholder="Your name"></label><p class="account-note">This name appears in your greeting. Set sender display names separately for each mailbox.</p></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-profile">Save account settings</button></div></div></div>`;
|
||||||
const close=()=>root.innerHTML='';
|
const close=()=>root.innerHTML='';
|
||||||
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-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
|
selectProductivityUi('#save-profile').onclick=()=>{const name=selectProductivityUi('#profile-name').value.trim();if(!name){toastProductivityUi('Enter your display name');return}setProfileName(name);close();toastProductivityUi('Account settings saved')};
|
||||||
selectProductivityUi('#profile-name').focus();
|
selectProductivityUi('#profile-name').focus();
|
||||||
}
|
}
|
||||||
async function openPreferences() {
|
async function openPreferences() {
|
||||||
const root=selectProductivityUi('#modal-root');
|
const root=selectProductivityUi('#modal-root');
|
||||||
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']];
|
||||||
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
|
||||||
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
|
||||||
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>`:'';
|
||||||
const close=()=>root.innerHTML='';
|
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>`;
|
||||||
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
|
const close=()=>root.innerHTML='';
|
||||||
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=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('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
|
||||||
selectProductivityUi('#theme-select').focus();
|
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.')}};
|
||||||
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(); }
|
selectProductivityUi('#theme-select').focus();
|
||||||
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
}
|
||||||
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
|
function 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 renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}}
|
function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`<div class="cal-cell ${d.getMonth()!==month?'outside':''} ${d.toDateString()===new Date().toDateString()?'today':''}" data-day="${key}"><span class="cal-number">${d.getDate()}</span>${items.slice(0,3).map(e=>`<div class="event-chip ${e.color||'green'}" data-event="${e.id}">${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}</div>`).join('')}${items.length>3?`<small>+${items.length-3} more</small>`:''}</div>`}const upcoming=savedEvents.filter(e=>e.date>=new Date().toISOString().slice(0,10)).sort((a,b)=>a.date.localeCompare(b.date)||a.time.localeCompare(b.time)).slice(0,5);selectProductivityUi('#calendar-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">YOUR TIME, WITH ROOM TO BREATHE</p><h2>${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}</h2><p class="page-subtitle">${savedEvents.length} saved events</p></div><div class="cal-actions"><button class="outline-button" id="today-btn">Today</button><button class="outline-button" id="prev-month" aria-label="Previous month">‹</button><button class="outline-button" id="next-month" aria-label="Next month">›</button><button class="outline-button" id="caldav-sync">Sync</button><button class="compose-button" id="new-event">+ New event</button></div></div><div class="calendar-card"><div class="calendar-week">${days.map(d=>`<span>${d}</span>`).join('')}</div><div class="calendar-grid">${cells}</div></div><div class="upcoming"><h3>Coming up</h3>${upcoming.length?upcoming.map(e=>`<button class="upcoming-row" data-event="${e.id}"><span class="event-date">${new Intl.DateTimeFormat('en-US',{month:'short'}).format(new Date(`${e.date}T12:00:00`)).toUpperCase()}<br><strong>${e.date.slice(8)}</strong></span><div><strong>${escapeProductivityUi(e.title)}</strong><small>${escapeProductivityUi(e.time||'All day')}${e.with?` · with ${escapeProductivityUi(e.with)}`:''}${e.place?` · ${escapeProductivityUi(e.place)}`:''}</small></div></button>`).join(''):'<p class="page-subtitle">No upcoming events yet.</p>'}</div>`;selectProductivityUi('#new-event').onclick=()=>showEvent(new Date(year,month,new Date().getDate()).toISOString().slice(0,10));selectProductivityUi('#today-btn').onclick=()=>{calendarMonth=new Date(new Date().getFullYear(),new Date().getMonth(),1);renderCalendar()};selectProductivityUi('#prev-month').onclick=()=>{calendarMonth=new Date(year,month-1,1);renderCalendar()};selectProductivityUi('#next-month').onclick=()=>{calendarMonth=new Date(year,month+1,1);renderCalendar()};selectProductivityUi('#calendar-view').onclick=e=>{const event=e.target.closest('[data-event]');if(event){showEvent(event.dataset.event);return}const cell=e.target.closest('.cal-cell');if(cell)showEvent(cell.dataset.day)}}
|
||||||
function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
|
function showContact(index){const existing=Number.isInteger(index)?savedContacts[index]:null,root=selectProductivityUi('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${existing?'Edit contact':'Add contact'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Name</span><input id="contact-name" maxlength="100" value="${escapeProductivityUi(existing?.name||'')}" placeholder="Their name"></label><label class="compose-line"><span>Email</span><input id="contact-email" type="email" value="${escapeProductivityUi(existing?.email||'')}" placeholder="name@example.com"></label><label class="compose-line"><span>Note</span><input id="contact-note" value="${escapeProductivityUi(existing?.note||'')}" placeholder="How you know them"></label></div><div class="compose-footer">${existing?'<button class="discard" id="delete-contact">Remove contact</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-contact">${existing?'Save changes':'Save contact'}</button></div></div></div>`;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()}
|
||||||
function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})}
|
function renderContacts(){const cards=savedContacts.map((c,i)=>`<article class="contact-card" data-contact="${i}"><div class="contact-avatar" style="background:${escapeProductivityUi(c.color)}">${escapeProductivityUi(c.initials)}</div><div><strong>${escapeProductivityUi(c.name)}</strong><span>${escapeProductivityUi(c.email)}</span><small>${escapeProductivityUi(c.note)}</small></div><button class="icon-button contact-more" data-edit-contact="${i}" aria-label="Edit ${escapeProductivityUi(c.name)}">···</button><button class="contact-email" data-email="${escapeProductivityUi(c.email)}" aria-label="Email ${escapeProductivityUi(c.name)}">↗</button></article>`).join('');selectProductivityUi('#contacts-view').innerHTML=`<div class="page-heading"><div><p class="eyebrow">THE PEOPLE WHO MAKE LIFE FULLER</p><h2>Your people</h2><p class="page-subtitle">${savedContacts.length} contacts, all in one place.</p></div><div class="cal-actions"><button class="outline-button" id="carddav-sync">Sync</button><button class="compose-button" id="add-contact">+ Add contact</button></div></div><div class="contact-search"><span>⌕</span><input id="contact-search" placeholder="Find someone by name or email"></div><div class="contacts-grid">${cards||'<p class="page-subtitle">No contacts yet. Add someone to get started.</p>'}</div>`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}}
|
||||||
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
|
function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]}
|
||||||
function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
|
function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>`<button class="label-link" data-label="${escapeProductivityUi(label)}"><i class="label-dot dot-blue"></i>${escapeProductivityUi(label)}</button>`).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})}
|
||||||
async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
|
function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')}
|
||||||
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh†to sync, or “account†to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
|
function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()}
|
||||||
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
|
async function actOnSelected(action){const selected=productivityMailUi.state.messages.filter(m=>productivityMailUi.state.selectedIds.has(m.id));if(!selected.length){toastProductivityUi('Select one or more messages first');return}try{for(const m of selected)await messageAction(m,action);if(action==='archive'||action==='delete')selected.forEach(m=>{m[action==='archive'?'archived':'deleted']=true});if(action==='unread')selected.forEach(m=>m.unread=true);productivityMailUi.state.selectedIds.clear();productivityMailUi.renderList();if(action==='archive'||action==='delete')selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Messages archived':action==='delete'?'Messages moved to Trash':'Messages marked unread')}catch(e){toastProductivityUi(e.message||'Could not update messages')}}
|
||||||
|
document.addEventListener('DOMContentLoaded',()=>{setProfileName(profileSettings.name);renderLabels();selectAllProductivityUi('.profile-button').forEach(b=>b.onclick=openAccountSettings);selectProductivityUi('#settings-button').onclick=openPreferences;selectProductivityUi('#add-label').onclick=addCustomLabel;selectProductivityUi('#sidebar-menu').onclick=()=>{const choice=prompt('Mailbox options: enter “refresh†to sync, or “account†to manage your mailbox.');if(choice?.toLowerCase()==='account')productivityMailUi.openMailAccount();else if(choice?.toLowerCase()==='refresh')productivityMailUi.syncMailbox(true)};selectProductivityUi('.help-button').onclick=()=>{const root=selectProductivityUi('#modal-root');root.innerHTML='<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>ep-mail help</span><button class="modal-close">×</button></div><div class="compose-fields"><p>Use the left rail to switch between Mail, Calendar, and Contacts. Select mail with the checkboxes for bulk actions. Calendar events and contacts are saved on this device.</p></div><div class="compose-footer"><span></span><button class="send-button modal-close">Got it</button></div></div></div>';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=()=>root.innerHTML='')};selectProductivityUi('#select-all').onclick=()=>{const rows=selectAllProductivityUi('.message');const ids=rows.map(r=>Number(r.dataset.id));const all=ids.length&&ids.every(id=>productivityMailUi.state.selectedIds.has(id));ids.forEach(id=>all?productivityMailUi.state.selectedIds.delete(id):productivityMailUi.state.selectedIds.add(id));productivityMailUi.renderList()};selectProductivityUi('#archive-selected').onclick=()=>actOnSelected('archive');selectProductivityUi('#delete-selected').onclick=()=>actOnSelected('delete');selectProductivityUi('#mark-unread').onclick=()=>actOnSelected('unread');document.addEventListener('click',e=>{const more=e.target.closest('.reader-tools button[title="More"]');if(more){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;const choice=prompt('Message actions: unread, snooze, label, inbox');if(choice==='unread')messageAction(m,'unread').then(()=>{m.unread=true;productivityMailUi.renderList();toastProductivityUi('Marked unread')});else if(choice==='snooze'){snoozedIds=[...new Set([...snoozedIds,m.id])];productWrite(productKeys.snoozed,snoozedIds);toastProductivityUi('Message snoozed')}else if(choice==='label')addMessageLabel(m);else if(choice==='inbox'){m.archived=false;productivityMailUi.renderList();toastProductivityUi('Moved to Inbox')}e.stopImmediatePropagation();return}const readerAction=e.target.closest('#reader-archive,#reader-delete,#reader-star');if(readerAction){const m=productivityMailUi.state.messages.find(x=>x.id===productivityMailUi.state.activeMessage);if(!m)return;e.stopImmediatePropagation();const action=readerAction.id==='reader-archive'?'archive':readerAction.id==='reader-delete'?'delete':'star';messageAction(m,action).then(()=>{if(action==='star')m.star=!m.star;else m[action==='archive'?'archived':'deleted']=true;if(action==='star'){productivityMailUi.renderList();openMessage(m.id)}else{productivityMailUi.renderList();selectProductivityUi('#reader-pane').innerHTML=productivityMailUi.emptyReader();toastProductivityUi(action==='archive'?'Moved to Archive':'Moved to Trash')}}).catch(x=>toastProductivityUi(x.message));return}const star=e.target.closest('.star');if(star){const m=productivityMailUi.state.messages.find(x=>x.id===Number(star.closest('.message').dataset.id));if(m){e.stopImmediatePropagation();messageAction(m,'star').then(()=>{m.star=!m.star;productivityMailUi.renderList()}).catch(x=>toastProductivityUi(x.message))}}const row=e.target.closest('.message');if(row&&!e.target.closest('button,input')){const m=productivityMailUi.state.messages.find(x=>x.id===Number(row.dataset.id));if(m&&productivityMailUi.connectedAccount&&m.uid)window.daybreakMail.updateMessage({uid:m.uid,folder:productivityMailUi.state.activeFolder,action:'unread',enabled:false}).catch(()=>{})}},{capture:true});selectProductivityUi('#load-more').textContent='Load more ↓';});
|
||||||
|
function addMessageLabel(m){const options=['Design','Travel','Personal',...customLabels];const label=prompt(`Add a label (${options.join(', ')})`);if(!label)return;m.tags=[...new Set([...(m.tags||[]),label])];productWrite(`daybreak-message-labels-${m.id}`,m.tags);toastProductivityUi(`Labeled ${label}`);productivityMailUi.renderList()}
|
||||||
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
||||||
const state = productivityMailUi.state;
|
const state = productivityMailUi.state;
|
||||||
if (state.activeFolder === 'Drafts') {
|
if (state.activeFolder === 'Drafts') {
|
||||||
@@ -79,7 +82,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
return baseMessageRenderer();
|
return baseMessageRenderer();
|
||||||
});
|
});
|
||||||
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}const decrypted=message?.attachments?.find(file=>file.filename===filename&&file.contentBase64);const saving=decrypted&&window.daybreakMail?.savePgpAttachment?window.daybreakMail.savePgpAttachment(decrypted):message?.uid&&window.daybreakMail?.saveAttachment?window.daybreakMail.saveAttachment({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,filename}):null;if(!saving){toastProductivityUi('Attachment download is available for connected mailbox messages');return}saving.then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
|
document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}const decrypted=message?.attachments?.find(file=>file.filename===filename&&file.contentBase64);const saving=decrypted&&window.daybreakMail?.savePgpAttachment?window.daybreakMail.savePgpAttachment(decrypted):message?.uid&&window.daybreakMail?.saveAttachment?window.daybreakMail.saveAttachment({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,filename}):null;if(!saving){toastProductivityUi('Attachment download is available for connected mailbox messages');return}saving.then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true);
|
||||||
|
|
||||||
window.epMailFeatures.productivity = Object.freeze({
|
window.epMailFeatures.productivity = Object.freeze({
|
||||||
|
|||||||
+25
-2
@@ -1,5 +1,28 @@
|
|||||||
const CACHE='ep-mail-v18';
|
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;
|
||||||
|
})());
|
||||||
|
});
|
||||||
|
|||||||
+49
-39
@@ -65,43 +65,53 @@ document.addEventListener('keydown', event => {
|
|||||||
action.run();
|
action.run();
|
||||||
});
|
});
|
||||||
|
|
||||||
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => function () {
|
function openShortcutSettings() {
|
||||||
baseOpenPreferences();
|
const root = selectShortcutUi('#modal-root');
|
||||||
const fields = selectShortcutUi('#modal-root .compose-fields');
|
const shortcuts = loadShortcuts();
|
||||||
const save = selectShortcutUi('#save-appearance');
|
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Keyboard shortcuts</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
||||||
if (!fields || !save) return;
|
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button></div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-shortcuts">Save shortcuts</button></div></div></div>`;
|
||||||
const shortcuts = loadShortcuts();
|
const close = () => { root.innerHTML = ''; };
|
||||||
const section = document.createElement('div');
|
root.querySelectorAll('.modal-close').forEach(button => { button.onclick = close; });
|
||||||
section.className = 'shortcut-settings';
|
selectShortcutUi('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||||
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${escapeShortcutUi(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
fields.addEventListener('keydown', event => {
|
||||||
fields.append(section);
|
const input = event.target.closest('.shortcut-input');
|
||||||
section.addEventListener('keydown', event => {
|
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
||||||
const input = event.target.closest('.shortcut-input');
|
event.preventDefault();
|
||||||
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
||||||
event.preventDefault();
|
const combo = eventShortcut(event);
|
||||||
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
if (combo) input.value = combo;
|
||||||
const combo = eventShortcut(event);
|
});
|
||||||
if (combo) input.value = combo;
|
selectShortcutUi('#reset-shortcuts').onclick = () => {
|
||||||
|
fields.querySelectorAll('.shortcut-input').forEach(input => {
|
||||||
|
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
||||||
});
|
});
|
||||||
selectShortcutUi('#reset-shortcuts').onclick = () => {
|
};
|
||||||
section.querySelectorAll('.shortcut-input').forEach(input => {
|
selectShortcutUi('#save-shortcuts').onclick = () => {
|
||||||
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
const values = {};
|
||||||
});
|
const used = new Map();
|
||||||
};
|
for (const input of fields.querySelectorAll('.shortcut-input')) {
|
||||||
const baseSave = save.onclick;
|
const value = normalizeShortcut(input.value);
|
||||||
save.onclick = event => {
|
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
||||||
const values = {};
|
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||||
const used = new Map();
|
if (value) used.set(value, label);
|
||||||
for (const input of section.querySelectorAll('.shortcut-input')) {
|
values[input.dataset.action] = value;
|
||||||
const value = normalizeShortcut(input.value);
|
}
|
||||||
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
||||||
if (value && used.has(value)) { toastShortcutUi(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
close();
|
||||||
if (value) used.set(value, label);
|
toastShortcutUi('Keyboard shortcuts saved');
|
||||||
values[input.dataset.action] = value;
|
};
|
||||||
}
|
}
|
||||||
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
|
||||||
baseSave?.call(save, event);
|
shortcutProductivityUi.wrapOpenPreferences(baseOpenPreferences => async function () {
|
||||||
};
|
await baseOpenPreferences();
|
||||||
});
|
const fields = selectShortcutUi('#modal-root .compose-fields');
|
||||||
})();
|
if (!fields || !selectShortcutUi('#save-appearance')) return;
|
||||||
|
const button = document.createElement('button');
|
||||||
|
button.type = 'button';
|
||||||
|
button.className = 'discard';
|
||||||
|
button.id = 'open-keyboard-shortcuts';
|
||||||
|
button.textContent = 'Keyboard shortcuts…';
|
||||||
|
button.onclick = openShortcutSettings;
|
||||||
|
fields.append(button);
|
||||||
|
});})();
|
||||||
|
|||||||
+7
-4
@@ -114,7 +114,7 @@ body.ep-daylight .compose-line input::placeholder,body.ep-daylight .compose-body
|
|||||||
body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b}
|
body.ep-daylight .modal-close,body.ep-daylight .discard{color:#59706b}
|
||||||
body.ep-daylight .toast{background:#11212b;color:#f1f1e9}
|
body.ep-daylight .toast{background:#11212b;color:#f1f1e9}
|
||||||
body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||||
.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-fields{min-height:0;flex:1 1 auto;overflow-y:auto}
|
.compose-modal{max-height:90vh;display:flex;flex-direction:column}.compose-modal>.modal-head,.compose-modal>.compose-footer{flex:none}.compose-fields{min-height:0;flex:0 1 auto;overflow-y:auto}.compose-modal>.compose-body{flex:1 1 120px;min-height:90px;height:auto}
|
||||||
.snooze-options .outline-button{width:100%;text-align:left}
|
.snooze-options .outline-button{width:100%;text-align:left}
|
||||||
.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap}
|
.mail-rules{padding:10px 0;border-bottom:1px solid var(--line)}.mail-rule-row{display:grid;grid-template-columns:1fr 1fr 120px 1fr auto;gap:6px;align-items:center;padding:5px 0}.mail-rule-row input,.mail-rule-row select{box-sizing:border-box;min-width:0;width:100%;padding:7px;border:1px solid var(--line);border-radius:5px;background:var(--panel);color:var(--text);font-size:10px}.mail-rule-row input:disabled{opacity:.55}.mail-rule-row .discard{white-space:nowrap}
|
||||||
@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}}
|
@media(max-width:650px){.mail-rule-row{grid-template-columns:1fr 1fr}.mail-rule-row .mail-rule-action,.mail-rule-row .mail-rule-value{grid-column:auto}}
|
||||||
@@ -126,9 +126,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
|||||||
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
|
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
|
||||||
|
|
||||||
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
|
.compose-fields code{font-family:monospace}.shortcut-input{text-transform:none}#reset-shortcuts{margin-top:8px}
|
||||||
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
||||||
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
|
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
|
||||||
|
.pgp-keys-modal .attachment-list{grid-template-columns:minmax(0,1fr)}.pgp-keys-modal .attachment-row{min-width:0}.pgp-keys-modal .attachment-row-info{flex:1 0 100%}.pgp-keys-modal .attachment-row-info strong,.pgp-keys-modal .attachment-row-info small{overflow:visible;text-overflow:clip;white-space:normal;overflow-wrap:anywhere}.pgp-keys-modal .attachment-row>button{max-width:100%;padding:8px;font-size:12px}.pgp-keys-modal .attachment-row>.compose-line{flex:1 1 180px;min-width:0}.pgp-keys-modal .pgp-trust{margin-left:0;max-width:100%}.pgp-keys-modal .pgp-actions{flex-wrap:wrap}
|
||||||
|
|
||||||
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
|
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
|
||||||
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
|
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
|
||||||
@@ -199,8 +200,10 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
|||||||
.compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px}
|
.compose-line input[type=checkbox]{flex:0 0 auto;width:20px;height:20px}
|
||||||
.compose-line span{flex:0 1 54%;line-height:1.25}
|
.compose-line span{flex:0 1 54%;line-height:1.25}
|
||||||
.compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0}
|
.compose-line input:not([type=checkbox]){flex:1;max-width:100%;min-width:0}
|
||||||
.compose-footer{gap:8px;padding:10px 12px}
|
.compose-footer{gap:8px;padding:10px 12px;flex-wrap:wrap;justify-content:flex-end}
|
||||||
.compose-body{height:30vh;padding:12px}
|
.compose-footer .pgp-compose{flex:1 0 100%;flex-wrap:wrap;margin-right:0;gap:4px 12px}
|
||||||
|
.compose-footer .send-button{order:99;padding:10px 18px;font-size:12px}
|
||||||
|
.compose-body{padding:12px}
|
||||||
.account-note,.account-status{font-size:12px}
|
.account-note,.account-status{font-size:12px}
|
||||||
.mail-rule-row{grid-template-columns:1fr;gap:6px}
|
.mail-rule-row{grid-template-columns:1fr;gap:6px}
|
||||||
.mail-rule-row>*{grid-column:1}
|
.mail-rule-row>*{grid-column:1}
|
||||||
|
|||||||
Reference in New Issue
Block a user