From 5f456e64d08e3da55646e6cc4856c620091534dd Mon Sep 17 00:00:00 2001 From: Tero Date: Tue, 3 Nov 2026 23:45:20 +0200 Subject: [PATCH] Android security implementation Phase 0-3 finalization part 1 --- ANDROID_SECURITY_PLAN.md | 25 +- android/app/build.gradle | 69 +- .../daybreak/mail/AndroidAccountVault.kt | 247 ++++-- .../daybreak/mail/AndroidAppLockPolicy.kt | 11 + .../daybreak/mail/AndroidDownloadPolicy.kt | 7 + .../daybreak/mail/AndroidMailService.kt | 419 +++++---- .../mail/AndroidPgpBiometricUnlock.kt | 166 ++++ .../daybreak/mail/BoundedInputReader.kt | 19 + .../java/studio/daybreak/mail/EpMailPlugin.kt | 674 +++++++++------ .../studio/daybreak/mail/MainActivity.java | 121 ++- .../daybreak/mail/AndroidAppLockPolicyTest.kt | 14 + .../mail/AndroidDownloadPolicyTest.kt | 15 + .../daybreak/mail/BoundedInputReaderTest.kt | 23 + package-lock.json | 4 +- package.json | 2 +- pgp-mail-ui.js | 305 +++---- pgp-ui.js | 818 +++++++++--------- platform-bridge.js | 46 +- productivity.js | 89 +- scripts/android-bridge.js | 64 +- scripts/android-pgp.js | 39 +- tests/android-pgp.test.cjs | 52 ++ tests/android-ui-support.test.cjs | 62 ++ www/pgp-mail-ui.js | 305 +++---- www/pgp-ui.js | 818 +++++++++--------- www/platform-bridge.js | 46 +- www/productivity.js | 89 +- 27 files changed, 2774 insertions(+), 1775 deletions(-) create mode 100644 android/app/src/main/java/studio/daybreak/mail/AndroidAppLockPolicy.kt create mode 100644 android/app/src/main/java/studio/daybreak/mail/AndroidDownloadPolicy.kt create mode 100644 android/app/src/main/java/studio/daybreak/mail/AndroidPgpBiometricUnlock.kt create mode 100644 android/app/src/main/java/studio/daybreak/mail/BoundedInputReader.kt create mode 100644 android/app/src/test/java/studio/daybreak/mail/AndroidAppLockPolicyTest.kt create mode 100644 android/app/src/test/java/studio/daybreak/mail/AndroidDownloadPolicyTest.kt create mode 100644 android/app/src/test/java/studio/daybreak/mail/BoundedInputReaderTest.kt diff --git a/ANDROID_SECURITY_PLAN.md b/ANDROID_SECURITY_PLAN.md index db3ff3f..8153bc4 100644 --- a/ANDROID_SECURITY_PLAN.md +++ b/ANDROID_SECURITY_PLAN.md @@ -7,18 +7,18 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU ## Implementation progress (2026-11-03) - **Phase 0 — Baseline:** The merged release manifest and core WebView/network settings have now been reviewed and hardened. TLS certificate integration tests, the complete plugin audit, and a production-signed APK review remain open, so the Phase 0 release gate is not closed. -- **Phase 1 — Local data/privacy:** Notification privacy, immediate background app locking, `FLAG_SECURE` while locked, account-removal disclosure, and a fail-closed missing-key recovery screen are implemented. Vault lifecycle, complete deletion semantics, and app-lock lifecycle/biometric follow-up remain open. -- **Phase 2 — Android OpenPGP:** Experimental test implementation is present. It is not security-reviewed or release-complete. -- **Phase 3 — WebView/bridge:** Important protections are implemented; complete bridge review and device/content testing remain open. +- **Phase 1 — Local data/privacy:** Notification privacy, configurable app locking, `FLAG_SECURE` from backgrounding, account-removal disclosure, explicit full local-data deletion, and fail-closed missing-key recovery are implemented. Vault lifecycle and automated device/lifecycle tests remain open. +- **Phase 2 — Android OpenPGP:** The experimental implementation now includes optional authentication-bound biometric/device-credential release of PGP passphrases, with passphrase fallback and invalidation recovery. It is not security-reviewed or release-complete. +- **Phase 3 — WebView/bridge:** CSP, navigation, sanitizer, and plugin-surface regression checks are automated; complete bridge review and device/content testing remain open. - **Phase 4 — Assurance:** Open; independent review, release assurance, and vulnerability/maintenance work remain. Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed. OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, on-demand PGP/MIME or inline-encrypted-message decryption, and verification of signed-only PGP/MIME and clear-signed messages. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**. -**Validation evidence:** DAV URL, attachment-name, notification privacy, Android OpenPGP policy decisions, one-shot confirmation callbacks, and the missing-vault-key policy have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock/unlock; with the lock active, emulator screenshots were fully obscured, and unlocking/turning the setting off restored the app. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. The Android OpenPGP module also has automated GnuPG interoperability tests in a Node harness, but those are not device-level mail tests. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Current validation: 157 Node tests and 21 Android unit tests pass; the Android debug build and release-manifest task succeed. Device testing of vault-corruption/key-loss recovery, invalid-certificate integration tests, production-signed APK review, and automated instrumentation of the actual confirmation dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android. +**Validation evidence:** DAV URL, attachment-name, notification privacy, app-lock delay policy, app-owned Downloads selection, Android OpenPGP policy decisions, one-shot confirmation callbacks, bounded preview reads, and the missing-vault-key policy have Android unit tests. The latest run passed all 161 Node tests and all 25 Android unit tests; debug APK assembly and the release-manifest processing task also succeeded. The Android PGP module's Node-harness tests cover encrypted-message flows, passphrase-verified biometric unlock, invalidation error propagation, and manual passphrase recovery; they do not exercise Android Keystore prompts or OS-level invalidation. The app lock was previously exercised on an emulator with a device PIN, including background lock/unlock and screenshot obscuring; the new delay choices still need device lifecycle testing. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were previously exercised on an emulator; actual dialog automation remains open. The Android OpenPGP module also has automated GnuPG interoperability tests in a Node harness, but those are not device-level mail tests. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Device testing of vault-corruption/key-loss recovery, biometric enrollment invalidation, invalid-certificate integration, production-signed APK review, and automated instrumentation of native dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android. -**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric design; invalid-certificate integration tests; production-signed APK/manifest review; app-lock recovery polish; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain. +**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation/biometric dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric invalidation tests; invalid-certificate integration tests; production-signed APK/manifest review; app-lock process-recreation testing; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain. ## Goals and limits @@ -51,9 +51,10 @@ These are implementation observations, not proof that all paths are safe. In par ### Phase 1 — Local data and privacy controls (P0) - [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. If the key alias is missing while encrypted data remains, the app now refuses to generate a replacement key and shows a recovery screen; it does not reset or expose the data. Add device tests for missing/invalidated keys, corrupted ciphertext, reinstall/migration handling, and the recovery instructions; verify no plaintext fallback for all stored data. -- [~] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation now says downloaded attachment files and global OpenPGP keys are retained. Decide/test whether a separate app-data wipe should remove app-created Downloads and PGP keys; account removal intentionally leaves those user data intact. +- [x] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation says downloaded attachment files and global OpenPGP keys are retained. +- [~] A separate native-confirmed full-data wipe removes vault contents, account and PGP Keystore keys, app-owned Downloads attachments, WebView data, service-worker registrations/caches, and renderer local settings. It is distinct from account removal; Android storage-failure and end-to-end deletion tests remain open. - [x] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting. -- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` while locked to hide task-switcher content and block screenshots; emulator smoke testing confirmed screenshots are obscured. Background sync continues and the setting is off unless enabled. Delayed lock, automated lifecycle/process-recreation tests, biometric UX, and recovery polish remain open. +- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` as soon as the app leaves the foreground. Users may choose immediate, 30-second, 1-minute, or 5-minute locking; the default is immediate. Background sync continues and the setting is off unless enabled. Emulator testing of the new delays, automated lifecycle/process-recreation tests, and recovery polish remain open. - [x] Background sync is separate from the UI lock. Further verification of which credentials/key material are available to background workers remains part of the vault lifecycle review. **Exit criteria:** storage migration and failure tests; no plaintext fallback; app-lock/session tests across lifecycle events; notification privacy tests on supported Android versions; data removal tests. @@ -61,8 +62,8 @@ These are implementation observations, not proof that all paths are safe. In par ### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity) - [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Automated Node-harness tests exercise the Android module against GnuPG; independent review and on-device GnuPG/Thunderbird interoperability remain release blockers. -- [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized. Biometric wrapping-key release, lifecycle/recovery handling, and automated checks against unprotected-key persistence remain open. -- [ ] Add optional biometric/device-credential release of PGP key access and test Keystore invalidation/recovery. Background sync does not use PGP private keys. +- [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized in that store. Optional PGP passphrase release is separately encrypted by an authentication-bound Android Keystore key; biometric/device-credential invalidation clears the wrapper and falls back to the original passphrase. Device-level invalidation/recovery tests and automated at-rest checks remain open. +- [x] Optional biometric/device-credential release of PGP key access is available per key; the default remains passphrase-only, and background sync does not use PGP private keys. - [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, trust, and public keys offered as message attachments (never imported silently). Native prompts guard trust elevation and replacement; automated cancel/confirm regression tests remain open. - [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open. - [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open. @@ -72,10 +73,10 @@ These are implementation observations, not proof that all paths are safe. In par ### 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. -- [~] Broad unused filesystem/navigation capabilities have been removed, but a complete review of every Capacitor plugin/method and permission remains open. -- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open. +- [~] Broad unused filesystem/navigation capabilities have been removed. Automated checks cover CSP, manifest permissions, external URL constraints, DAV redirects, and selected bridge methods; a complete method-by-method plugin review remains open. +- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. Text/image previews use bounded stream reads, while attachment downloads stream to app storage. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open. **Exit criteria:** automated CSP/navigation/bridge tests, sanitizer regressions, and a manual WebView inspection on the minimum and target Android versions. diff --git a/android/app/build.gradle b/android/app/build.gradle index 7d5c5f7..b45a9a9 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,39 +1,39 @@ apply plugin: 'com.android.application' apply plugin: 'org.jetbrains.kotlin.android' -def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version -def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() } -def releaseStoreFile = System.getenv('EP_MAIL_ANDROID_STORE_FILE') -def releaseStorePassword = System.getenv('EP_MAIL_ANDROID_STORE_PASSWORD') -def releaseKeyAlias = System.getenv('EP_MAIL_ANDROID_KEY_ALIAS') -def releaseKeyPassword = System.getenv('EP_MAIL_ANDROID_KEY_PASSWORD') -def releaseSigningValues = [releaseStoreFile, releaseStorePassword, releaseKeyAlias, releaseKeyPassword] -def hasAnyReleaseSigningValue = releaseSigningValues.any { it != null && !it.isBlank() } -def hasCompleteReleaseSigning = releaseSigningValues.every { it != null && !it.isBlank() } - -if (hasAnyReleaseSigningValue && !hasCompleteReleaseSigning) { - throw new GradleException('Android release signing requires EP_MAIL_ANDROID_STORE_FILE, EP_MAIL_ANDROID_STORE_PASSWORD, EP_MAIL_ANDROID_KEY_ALIAS, and EP_MAIL_ANDROID_KEY_PASSWORD.') -} -if (hasCompleteReleaseSigning && !new File(releaseStoreFile).isAbsolute()) { - throw new GradleException('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.') -} +def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version +def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() } +def releaseStoreFile = System.getenv('EP_MAIL_ANDROID_STORE_FILE') +def releaseStorePassword = System.getenv('EP_MAIL_ANDROID_STORE_PASSWORD') +def releaseKeyAlias = System.getenv('EP_MAIL_ANDROID_KEY_ALIAS') +def releaseKeyPassword = System.getenv('EP_MAIL_ANDROID_KEY_PASSWORD') +def releaseSigningValues = [releaseStoreFile, releaseStorePassword, releaseKeyAlias, releaseKeyPassword] +def hasAnyReleaseSigningValue = releaseSigningValues.any { it != null && !it.isBlank() } +def hasCompleteReleaseSigning = releaseSigningValues.every { it != null && !it.isBlank() } + +if (hasAnyReleaseSigningValue && !hasCompleteReleaseSigning) { + throw new GradleException('Android release signing requires EP_MAIL_ANDROID_STORE_FILE, EP_MAIL_ANDROID_STORE_PASSWORD, EP_MAIL_ANDROID_KEY_ALIAS, and EP_MAIL_ANDROID_KEY_PASSWORD.') +} +if (hasCompleteReleaseSigning && !new File(releaseStoreFile).isAbsolute()) { + throw new GradleException('EP_MAIL_ANDROID_STORE_FILE must be an absolute path.') +} android { namespace = "studio.daybreak.mail" compileSdk = rootProject.ext.compileSdkVersion - buildFeatures { - buildConfig true - } - if (hasCompleteReleaseSigning) { - signingConfigs { - release { - storeFile file(releaseStoreFile) - storePassword releaseStorePassword - keyAlias releaseKeyAlias - keyPassword releaseKeyPassword - } - } - } + buildFeatures { + buildConfig true + } + if (hasCompleteReleaseSigning) { + signingConfigs { + release { + storeFile file(releaseStoreFile) + storePassword releaseStorePassword + keyAlias releaseKeyAlias + keyPassword releaseKeyPassword + } + } + } packaging { resources { pickFirsts += "META-INF/NOTICE.md" @@ -54,11 +54,11 @@ android { } } buildTypes { - release { - minifyEnabled false - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' - if (hasCompleteReleaseSigning) signingConfig signingConfigs.release - } + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + if (hasCompleteReleaseSigning) signingConfig signingConfigs.release + } } compileOptions { sourceCompatibility JavaVersion.VERSION_21 @@ -80,6 +80,7 @@ dependencies { implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion" implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion" implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" + implementation 'androidx.biometric:biometric:1.1.0' implementation project(':capacitor-android') implementation 'com.sun.mail:android-mail:1.6.7' implementation 'com.sun.mail:android-activation:1.6.7' diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt index 0e89b8e..93f33c7 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidAccountVault.kt @@ -21,11 +21,11 @@ internal object AndroidAccountVault { private const val ENCRYPTED_VALUE = "encrypted-data" private const val GCM_TAG_BITS = 128 - @Volatile private var appContext: Context? = null - - fun initialize(context: Context) { - appContext = context.applicationContext - } + @Volatile private var appContext: Context? = null + + fun initialize(context: Context) { + appContext = context.applicationContext + } @Synchronized fun read(): JSONObject { @@ -55,80 +55,137 @@ internal object AndroidAccountVault { } fun accounts(): JSONArray = read().optJSONArray("accounts") ?: JSONArray() - - fun notificationDetailsEnabled(): Boolean = - read().optBoolean("showNotificationDetails", NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS) - - @Synchronized - fun setNotificationDetailsEnabled(enabled: Boolean): Boolean { - val store = read().put("showNotificationDetails", enabled) - write(store) - return enabled - } - - fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false) - - @Synchronized - fun setAppLockEnabled(enabled: Boolean): Boolean { - val store = read().put("appLockEnabled", enabled) - write(store) - return enabled - } - - fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) } - ?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject()) - - @Synchronized - fun savePgpStore(candidate: JSONObject) { - validatePgpStore(candidate) - val store = read().put("pgpStore", JSONObject(candidate.toString())) - write(store) - } - - private fun validatePgpStore(candidate: JSONObject) { - require(candidate.toString().length <= 3_000_000) { "The OpenPGP key store is too large." } - require(!hasPassphraseField(candidate)) { "Passphrases must never be stored." } - val keys = candidate.optJSONArray("keys") ?: JSONArray() - val contacts = candidate.optJSONArray("contacts") ?: JSONArray() - require(keys.length() <= 20 && contacts.length() <= 500) { "The OpenPGP key store has too many entries." } - val fingerprint = Regex("^[0-9A-Fa-f]{40,64}$") - for (index in 0 until keys.length()) { - val entry = keys.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP key entry is invalid.") - val privateKey = entry.optString("privateKey") - val publicKey = entry.optString("publicKey") - require(fingerprint.matches(entry.optString("fingerprint")) && - privateKey.length in 1..200_000 && privateKey.contains("BEGIN PGP PRIVATE KEY BLOCK") && - publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK")) { - "An OpenPGP key entry is invalid." - } - } - for (index in 0 until contacts.length()) { - val entry = contacts.optJSONObject(index) ?: throw IllegalArgumentException("An OpenPGP contact entry is invalid.") - val publicKey = entry.optString("publicKey") - require(fingerprint.matches(entry.optString("fingerprint")) && - publicKey.length in 1..200_000 && publicKey.contains("BEGIN PGP PUBLIC KEY BLOCK") && - !publicKey.contains("BEGIN PGP PRIVATE KEY BLOCK")) { - "An OpenPGP contact entry is invalid." - } - require(entry.optString("trust") in setOf("unknown", "trusted", "verified")) { - "An OpenPGP contact trust value is invalid." - } - } - } - - private fun hasPassphraseField(value: Any?): Boolean = when (value) { - is JSONObject -> { - val keys = value.keys() - var found = false - while (keys.hasNext() && !found) { - val key = keys.next() - found = key.contains("passphrase", ignoreCase = true) || hasPassphraseField(value.opt(key)) - } - found - } - is JSONArray -> (0 until value.length()).any { hasPassphraseField(value.opt(it)) } - else -> false - } + + fun notificationDetailsEnabled(): Boolean = + read().optBoolean("showNotificationDetails", NotificationPrivacyPolicy.DEFAULT_SHOW_DETAILS) + + @Synchronized + fun setNotificationDetailsEnabled(enabled: Boolean): Boolean { + val store = read().put("showNotificationDetails", enabled) + write(store) + return enabled + } + + fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false) + + fun appLockDelaySeconds(): Int = read().optInt("appLockDelaySeconds", 0) + + @Synchronized + fun setAppLockEnabled(enabled: Boolean): Boolean { + val store = read().put("appLockEnabled", enabled) + write(store) + return enabled + } + + @Synchronized + fun setAppLockDelaySeconds(seconds: Int): Int { + AndroidAppLockPolicy.requireValidDelay(seconds) + val store = read().put("appLockDelaySeconds", seconds) + write(store) + return seconds + } + + fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) } + ?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject()) + + @Synchronized + fun savePgpStore(candidate: JSONObject) { + validatePgpStore(candidate) + val store = read() + val previousKeys = store.optJSONObject("pgpStore")?.optJSONArray("keys") ?: JSONArray() + val nextFingerprints = (0 until (candidate.optJSONArray("keys")?.length() ?: 0)) + .mapNotNull { candidate.optJSONArray("keys")?.optJSONObject(it)?.optString("fingerprint") } + .map { it.uppercase(Locale.ROOT) } + .toSet() + val removedFingerprints = (0 until previousKeys.length()) + .mapNotNull { previousKeys.optJSONObject(it)?.optString("fingerprint") } + .filter { it.uppercase(Locale.ROOT) !in nextFingerprints } + val biometricUnlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject() + removedFingerprints.forEach { biometricUnlocks.remove(it.uppercase(Locale.ROOT)) } + store.put("pgpBiometricUnlocks", biometricUnlocks) + store.put("pgpStore", JSONObject(candidate.toString())) + write(store) + removedFingerprints.forEach(AndroidPgpBiometricUnlock::deleteKey) + } + + @Synchronized + fun pgpBiometricUnlock(fingerprint: String): String? = + read().optJSONObject("pgpBiometricUnlocks")?.optString(fingerprint.uppercase(Locale.ROOT)) + ?.takeIf(String::isNotBlank) + + fun hasPgpBiometricUnlock(fingerprint: String): Boolean = + pgpBiometricUnlock(fingerprint) != null + + @Synchronized + fun setPgpBiometricUnlock(fingerprint: String, ciphertext: String?) { + require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) { + "The OpenPGP fingerprint is invalid." + } + val store = read() + val unlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject() + val key = fingerprint.uppercase(Locale.ROOT) + if (ciphertext.isNullOrBlank()) unlocks.remove(key) + else { + require(ciphertext.length <= 16_384) { "Biometric key unlock data is too large." } + unlocks.put(key, ciphertext) + } + store.put("pgpBiometricUnlocks", unlocks) + write(store) + } + + @Synchronized + fun wipe() { + val prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + check(prefs.edit().clear().commit()) { "Could not delete encrypted local data." } + val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + if (keyStore.containsAlias(KEY_ALIAS)) keyStore.deleteEntry(KEY_ALIAS) + AndroidPgpBiometricUnlock.deleteAllKeys() + } + + private fun validatePgpStore(candidate: JSONObject) { + 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? { val store = read() @@ -503,13 +560,13 @@ internal object AndroidAccountVault { .put("id", account.optString("id")) .put("email", account.optString("email")) .put("displayName", account.optString("displayName")) - .put("imapHost", account.optString("imapHost")) - .put("smtpHost", account.optString("smtpHost")) - .put("imapPort", account.optInt("imapPort", 143)) - .put("smtpPort", account.optInt("smtpPort", 587)) - .put("imapSecure", account.optBoolean("imapSecure", false)) - .put("smtpSecure", account.optBoolean("smtpSecure", false)) - .put("signature", account.optString("signature")) + .put("imapHost", account.optString("imapHost")) + .put("smtpHost", account.optString("smtpHost")) + .put("imapPort", account.optInt("imapPort", 143)) + .put("smtpPort", account.optInt("smtpPort", 587)) + .put("imapSecure", account.optBoolean("imapSecure", false)) + .put("smtpSecure", account.optBoolean("smtpSecure", false)) + .put("signature", account.optString("signature")) .put("notificationsEnabled", account.optBoolean("notificationsEnabled", true)) .put("syncIntervalMinutes", account.optInt("syncIntervalMinutes", 2)) .put("rules", account.optJSONArray("rules") ?: JSONArray()) @@ -597,15 +654,15 @@ internal object AndroidAccountVault { appContext ?: throw IllegalStateException("Encrypted account storage is not initialized.") @Synchronized - private fun secretKey(): SecretKey { - val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } - (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") + private fun secretKey(): SecretKey { + val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (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") generator.init( KeyGenParameterSpec.Builder( KEY_ALIAS, diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidAppLockPolicy.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidAppLockPolicy.kt new file mode 100644 index 0000000..eb80018 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidAppLockPolicy.kt @@ -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." + } + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidDownloadPolicy.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidDownloadPolicy.kt new file mode 100644 index 0000000..15a24f6 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidDownloadPolicy.kt @@ -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" +} diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt index 73bd6d1..055be78 100644 --- a/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidMailService.kt @@ -2,6 +2,7 @@ package studio.daybreak.mail import android.content.ContentValues import android.content.Context +import android.content.ContentUris import android.os.Build import android.os.Environment import android.provider.MediaStore @@ -10,9 +11,10 @@ import android.webkit.MimeTypeMap import com.sun.mail.imap.IMAPFolder import org.json.JSONArray import org.json.JSONObject -import java.io.File -import java.io.ByteArrayInputStream -import java.io.ByteArrayOutputStream +import java.io.File +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.InputStream import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Calendar @@ -43,6 +45,52 @@ import javax.mail.internet.MimeUtility internal object AndroidMailService { 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 -> val inbox = store.getFolder("INBOX") check(inbox.exists()) { "The inbox could not be found." } @@ -264,25 +312,25 @@ internal object AndroidMailService { JSONObject().put("ok", true) } - fun send(account: JSONObject, input: JSONObject): JSONObject { - val rawBase64 = input.optString("rawBase64") - val session = Session.getInstance(smtpProperties(account), credentials(account)) - val message: MimeMessage - if (rawBase64.isNotBlank()) { - require(rawBase64.length <= 36_000_000 && rawBase64.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) { - "The encrypted message is too large or invalid." - } - val bytes = Base64.decode(rawBase64, Base64.DEFAULT) - require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." } - message = MimeMessage(session, ByteArrayInputStream(bytes)) - validateOpenPgpMime(message) - require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) { - "The encrypted message needs a sender and at least one recipient." - } - } else { - val recipient = input.optString("to").trim() - require(recipient.isNotEmpty()) { "Add at least one recipient." } - message = MimeMessage(session) + fun send(account: JSONObject, input: JSONObject): JSONObject { + val rawBase64 = input.optString("rawBase64") + val session = Session.getInstance(smtpProperties(account), credentials(account)) + val message: MimeMessage + if (rawBase64.isNotBlank()) { + require(rawBase64.length <= 36_000_000 && rawBase64.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) { + "The encrypted message is too large or invalid." + } + val bytes = Base64.decode(rawBase64, Base64.DEFAULT) + require(bytes.size <= 25 * 1024 * 1024) { "The encrypted message is too large to send on Android testing builds." } + message = MimeMessage(session, ByteArrayInputStream(bytes)) + validateOpenPgpMime(message) + require(message.from?.isNotEmpty() == true && message.allRecipients?.isNotEmpty() == true) { + "The encrypted message needs a sender and at least one recipient." + } + } else { + val recipient = input.optString("to").trim() + require(recipient.isNotEmpty()) { "Add at least one recipient." } + message = MimeMessage(session) message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8")) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true)) val cc = input.optString("cc").trim() @@ -321,10 +369,10 @@ internal object AndroidMailService { } message.setContent(multipart) } - message.sentDate = Date() - message.saveChanges() - input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } - } + message.sentDate = Date() + message.saveChanges() + input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } + } val transport = session.getTransport("smtp") try { @@ -350,63 +398,63 @@ internal object AndroidMailService { } catch (_: Exception) { savedToSent = false } - 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)) - } + return JSONObject().put("ok", true).put("savedToSent", savedToSent) + } + + fun pgpMessageSource(account: JSONObject, folderName: String, uid: Long): JSONObject = withStore(account) { _, store -> + require(uid > 0) { "That message could not be identified." } + val folder = resolveFolder(store, folderName) ?: throw IllegalStateException("That mail folder could not be found.") + folder.open(Folder.READ_ONLY) + try { + val message = (folder as? UIDFolder)?.getMessageByUID(uid) + ?: throw IllegalStateException("The message is no longer available.") + val output = ByteArrayOutputStream() + message.writeTo(output) + val bytes = output.toByteArray() + require(bytes.size <= 25 * 1024 * 1024) { "This encrypted message is too large to open on Android testing builds." } + JSONObject().put("rawBase64", Base64.encodeToString(bytes, Base64.NO_WRAP)) + } finally { + folder.close(false) + } + } + + private fun validateOpenPgpMime(message: MimeMessage) { + val contentType = message.contentType.lowercase(Locale.ROOT) + val multipart = message.content as? Multipart + ?: throw IllegalArgumentException("The OpenPGP MIME message is malformed.") + require(multipart.count == 2) { "The OpenPGP MIME message has an unexpected structure." } + if (contentType.startsWith("multipart/encrypted")) { + val versionPart = multipart.getBodyPart(0) + val encryptedPart = multipart.getBodyPart(1) + val version = runCatching { versionPart.content.toString().trim() }.getOrDefault("") + val armor = runCatching { String(encryptedPart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("") + require(versionPart.isMimeType("application/pgp-encrypted") && version == "Version: 1" && + encryptedPart.isMimeType("application/octet-stream") && + armor.contains("-----BEGIN PGP MESSAGE-----") && armor.contains("-----END PGP MESSAGE-----")) { + "The encrypted OpenPGP payload is missing or malformed." + } + } else if (contentType.startsWith("multipart/signed")) { + val signaturePart = multipart.getBodyPart(1) + val armor = runCatching { String(signaturePart.inputStream.readBytes(), Charsets.US_ASCII) }.getOrDefault("") + require(signaturePart.isMimeType("application/pgp-signature") && + armor.contains("-----BEGIN PGP SIGNATURE-----") && armor.contains("-----END PGP SIGNATURE-----")) { + "The OpenPGP signature is missing or malformed." + } + } else { + throw IllegalArgumentException("Only an OpenPGP MIME message can use the protected send path.") + } + } + + fun savePgpAttachment(context: Context, input: JSONObject): JSONObject { + val filename = input.optString("filename").replace(Regex("[\\\\/\\r\\n\\u0000]"), "").take(255).ifBlank { "attachment" } + val contentType = input.optString("contentType", "application/octet-stream").lowercase(Locale.ROOT) + require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) { "The attachment content type is invalid." } + val encoded = input.optString("contentBase64") + require(encoded.length <= 36_000_000 && encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) { + "The attachment is too large or invalid." + } + return saveAttachmentBytes(context, filename, contentType, Base64.decode(encoded, Base64.DEFAULT)) + } fun flushOutbox(account: JSONObject) { val accountId = account.optString("id") @@ -422,7 +470,7 @@ internal object AndroidMailService { } AndroidAccountVault.removeMailOperation(accountId, operation.optString("id")) } 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 } } @@ -440,7 +488,7 @@ internal object AndroidMailService { val filename = input.optString("filename") val part = findAttachment(message, filename) ?: 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 { folder.close(false) } @@ -461,7 +509,7 @@ internal object AndroidMailService { val none = JSONObject().put("kind", "none") .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)) { - val bytes = part.inputStream.use { it.readBytes() } + val bytes = part.inputStream.use { BoundedInputReader.read(it, 5 * 1048576 + 1) } if (bytes.size > 5 * 1048576) { none.put("reason", "This image is too large to preview. Download it instead.") } else { @@ -470,7 +518,7 @@ internal object AndroidMailService { ) } } 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") .put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8)) .put("truncated", bytes.size > 100000) @@ -550,7 +598,7 @@ internal object AndroidMailService { inbox.close(true) } } 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 +606,19 @@ internal object AndroidMailService { fun watchInbox( account: JSONObject, - onNewMail: (Int) -> Unit, - shouldStop: () -> Boolean, - onConnection: (Store?, Folder?) -> Unit - ) { - val protocol = imapProtocol(account) - val props = imapProperties(account).apply { - setProperty("mail.$protocol.timeout", "0") - setProperty("mail.$protocol.writetimeout", "60000") - } + onNewMail: (Int) -> Unit, + shouldStop: () -> Boolean, + onConnection: (Store?, Folder?) -> Unit + ) { + val protocol = imapProtocol(account) + val props = imapProperties(account).apply { + setProperty("mail.$protocol.timeout", "0") + setProperty("mail.$protocol.writetimeout", "60000") + } val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2) .coerceIn(2, 60) * 60_000L val session = Session.getInstance(props, credentials(account)) - val store = session.getStore(protocol) + val store = session.getStore(protocol) try { store.connect( account.optString("imapHost"), @@ -665,13 +713,13 @@ internal object AndroidMailService { val body = ArrayList() val htmlBodies = ArrayList() val attachments = JSONArray() - val links = linkedSetOf() - collectParts(message, body, htmlBodies, attachments, links) - val bodyText = body.joinToString("\n\n").trim().take(8000) - val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----") - val signed = isSignedMessage(message) || bodyText.contains("-----BEGIN PGP SIGNED MESSAGE-----") - val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText - val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) + val links = linkedSetOf() + collectParts(message, body, htmlBodies, attachments, links) + val bodyText = body.joinToString("\n\n").trim().take(8000) + val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----") + val signed = isSignedMessage(message) || bodyText.contains("-----BEGIN PGP SIGNED MESSAGE-----") + val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText + val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) val date = message.receivedDate ?: message.sentDate ?: Date() val tags = JSONArray().put(requestedFolder) val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid") @@ -692,10 +740,10 @@ internal object AndroidMailService { .put("color", "#dce6df") .put("sender", senderName) .put("email", senderEmail) - .put("subject", subject) - .put("snippet", snippet) - .put("encrypted", encrypted) - .put("signed", signed) + .put("subject", subject) + .put("snippet", snippet) + .put("encrypted", encrypted) + .put("signed", signed) .put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date)) .put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date)) .put("timestamp", date.time) @@ -708,46 +756,46 @@ internal object AndroidMailService { .put("sourceFolder", labelFolder) .put("html", htmlBodies.firstOrNull()?.take(100000) ?: "") .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) }) .put("links", JSONArray().apply { links.take(30).forEach(::put) }) .put("attachments", attachments) .put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL) - .put("size", files.firstOrNull()?.optString("size") ?: "") - } - - private fun isEncryptedMessage(part: javax.mail.Part): Boolean { - if (part.isMimeType("multipart/encrypted")) return true - val content = try { part.content } catch (_: Exception) { return false } - if (content is Multipart) { - for (index in 0 until content.count) if (isEncryptedMessage(content.getBodyPart(index))) return true - } else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true - return false - } - - private fun isSignedMessage(part: javax.mail.Part): Boolean { - if (part.isMimeType("multipart/signed")) return true - val content = try { part.content } catch (_: Exception) { return false } - if (content is Multipart) { - for (index in 0 until content.count) if (isSignedMessage(content.getBodyPart(index))) return true - } else if (content is String && content.contains("-----BEGIN PGP SIGNED MESSAGE-----")) return true - return false - } + .put("size", files.firstOrNull()?.optString("size") ?: "") + } + + private fun isEncryptedMessage(part: javax.mail.Part): Boolean { + if (part.isMimeType("multipart/encrypted")) return true + val content = try { part.content } catch (_: Exception) { return false } + if (content is Multipart) { + for (index in 0 until content.count) if (isEncryptedMessage(content.getBodyPart(index))) return true + } else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true + return false + } + + private fun isSignedMessage(part: javax.mail.Part): Boolean { + if (part.isMimeType("multipart/signed")) return true + val content = try { part.content } catch (_: Exception) { return false } + if (content is Multipart) { + for (index in 0 until content.count) if (isSignedMessage(content.getBodyPart(index))) return true + } else if (content is String && content.contains("-----BEGIN PGP SIGNED MESSAGE-----")) return true + return false + } private fun attachmentList(attachments: JSONArray): List = (0 until attachments.length()).map { attachments.getJSONObject(it) } - private fun collectParts( + private fun collectParts( part: javax.mail.Part, body: MutableList, htmlBodies: MutableList, attachments: JSONArray, links: MutableSet - ) { - if (part.isMimeType("application/pgp-signature") || part.isMimeType("application/pgp-encrypted")) return - val filename = decode(part.fileName) - if (part.isMimeType("application/octet-stream") && filename.equals("encrypted.asc", true)) return + ) { + if (part.isMimeType("application/pgp-signature") || part.isMimeType("application/pgp-encrypted")) return + 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)) { val name = filename.ifBlank { "attachment" } val size = part.size.coerceAtLeast(0) @@ -786,29 +834,60 @@ internal object AndroidMailService { return null } - private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject { - val safeFilename = AttachmentNamePolicy.sanitize(filename) - val mimeType = contentType.substringBefore(';').ifBlank { - MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream" - } - if (Build.VERSION.SDK_INT >= 29) { - val values = ContentValues().apply { - put(MediaStore.Downloads.DISPLAY_NAME, safeFilename) + private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject { + return saveAttachmentStream(context, filename, contentType, ByteArrayInputStream(bytes)) + } + + private fun saveAttachmentStream(context: Context, filename: String, contentType: String, input: InputStream): JSONObject { + val safeFilename = AttachmentNamePolicy.sanitize(filename) + val mimeType = contentType.substringBefore(';').ifBlank { + 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.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) } val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) ?: throw IllegalStateException("Could not create the attachment in Downloads.") - context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) } - ?: throw IllegalStateException("Could not write the attachment.") - return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", safeFilename) - } + try { + val output = context.contentResolver.openOutputStream(uri) + ?: 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) ?: throw IllegalStateException("Downloads storage is not available.") - val file = File(directory, safeFilename) - file.writeBytes(bytes) - return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename) - } + val file = File(directory, safeFilename) + try { + file.outputStream().use { output -> input.use { it.copyTo(output) } } + } catch (error: Exception) { + try { + input.close() + } catch (cleanupError: Exception) { + error.addSuppressed(cleanupError) + } + if (file.exists() && !file.delete()) error.addSuppressed( + IllegalStateException("Could not remove the incomplete attachment from Downloads.") + ) + throw error + } + return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename) + } private const val CUSTOM_FOLDER_PREFIX = "Folder:" private val reservedFolderNames = setOf( @@ -879,9 +958,9 @@ internal object AndroidMailService { } } - private fun withStore(account: JSONObject, block: (Session, Store) -> T): T { - val session = Session.getInstance(imapProperties(account), credentials(account)) - val store = session.getStore(imapProtocol(account)) + private fun withStore(account: JSONObject, block: (Session, Store) -> T): T { + val session = Session.getInstance(imapProperties(account), credentials(account)) + val store = session.getStore(imapProtocol(account)) try { store.connect( account.optString("imapHost"), @@ -895,28 +974,28 @@ internal object AndroidMailService { } } - private fun credentials(account: JSONObject) = object : Authenticator() { + private fun credentials(account: JSONObject) = object : Authenticator() { override fun getPasswordAuthentication() = PasswordAuthentication( account.optString("email"), account.optString("password") ) } - private fun imapProperties(account: JSONObject) = Properties().apply { - putAll(AndroidMailTransport.imapProperties(MailServerConnection( - account.optString("imapHost"), - account.optInt("imapPort", 143), - account.optBoolean("imapSecure", false) - ))) - } - - private fun imapProtocol(account: JSONObject) = if (account.optBoolean("imapSecure", false)) "imaps" else "imap" - - private fun smtpProperties(account: JSONObject) = AndroidMailTransport.smtpProperties(MailServerConnection( - account.optString("smtpHost"), - account.optInt("smtpPort", 587), - account.optBoolean("smtpSecure", false) - )) + private fun imapProperties(account: JSONObject) = Properties().apply { + putAll(AndroidMailTransport.imapProperties(MailServerConnection( + account.optString("imapHost"), + account.optInt("imapPort", 143), + account.optBoolean("imapSecure", false) + ))) + } + + private fun imapProtocol(account: JSONObject) = if (account.optBoolean("imapSecure", false)) "imaps" else "imap" + + private fun smtpProperties(account: JSONObject) = AndroidMailTransport.smtpProperties(MailServerConnection( + account.optString("smtpHost"), + account.optInt("smtpPort", 587), + account.optBoolean("smtpSecure", false) + )) private fun displayName(account: JSONObject) = account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80) diff --git a/android/app/src/main/java/studio/daybreak/mail/AndroidPgpBiometricUnlock.kt b/android/app/src/main/java/studio/daybreak/mail/AndroidPgpBiometricUnlock.kt new file mode 100644 index 0000000..9a6f3c2 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/AndroidPgpBiometricUnlock.kt @@ -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() + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/BoundedInputReader.kt b/android/app/src/main/java/studio/daybreak/mail/BoundedInputReader.kt new file mode 100644 index 0000000..0e89da0 --- /dev/null +++ b/android/app/src/main/java/studio/daybreak/mail/BoundedInputReader.kt @@ -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() + } +} diff --git a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt index 681bad1..174981b 100644 --- a/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt +++ b/android/app/src/main/java/studio/daybreak/mail/EpMailPlugin.kt @@ -7,6 +7,7 @@ import android.content.IntentFilter import android.net.Uri import android.os.Build import android.app.AlertDialog +import androidx.biometric.BiometricPrompt import com.getcapacitor.JSObject import com.getcapacitor.Plugin import com.getcapacitor.PluginCall @@ -14,16 +15,18 @@ import com.getcapacitor.PluginMethod import com.getcapacitor.annotation.CapacitorPlugin import java.util.Locale import java.util.UUID -import org.json.JSONArray -import org.json.JSONObject -import javax.mail.internet.InternetAddress +import org.json.JSONArray +import org.json.JSONObject +import javax.mail.internet.InternetAddress +import javax.crypto.Cipher @CapacitorPlugin(name = "EpMail") class EpMailPlugin : Plugin() { private var syncReceiver: BroadcastReceiver? = null + private var wipeDialogShowing = false - override fun load() { - AndroidAccountVault.initialize(context) + override fun load() { + AndroidAccountVault.initialize(context) val filter = IntentFilter(MailIdleService.ACTION_MAIL_SYNC) val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { @@ -38,21 +41,21 @@ class EpMailPlugin : Plugin() { @Suppress("DEPRECATION") context.registerReceiver(receiver, filter) } - ensureVaultAvailableAndStartSync() - } - - override fun handleOnResume() { - 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})") - } - } + ensureVaultAvailableAndStartSync() + } + + override fun handleOnResume() { + 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() { syncReceiver?.let { @@ -64,164 +67,300 @@ class EpMailPlugin : Plugin() { @PluginMethod fun getAppVersion(call: PluginCall) { call.resolve(JSObject().put("version", BuildConfig.VERSION_NAME)) - } - - @PluginMethod - fun getNotificationPrivacy(call: PluginCall) { - try { - call.resolve(JSObject().put("showDetails", AndroidAccountVault.notificationDetailsEnabled())) - } catch (error: Exception) { - call.reject(error.message ?: "Could not read notification privacy settings.") - } - } - - @PluginMethod - fun setNotificationDetails(call: PluginCall) { - try { - val enabled = call.getBoolean("enabled") - ?: throw IllegalArgumentException("Choose whether notifications may show details.") - AndroidAccountVault.setNotificationDetailsEnabled(enabled) - call.resolve(JSObject().put("showDetails", enabled)) - } catch (error: Exception) { - call.reject(error.message ?: "Could not save notification privacy settings.") - } - } - - @PluginMethod - fun getAppLockSettings(call: PluginCall) { - try { - val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager - call.resolve(JSObject() - .put("enabled", AndroidAccountVault.appLockEnabled()) - .put("deviceSecure", keyguard.isDeviceSecure)) - } catch (error: Exception) { - call.reject(error.message ?: "Could not read app-lock settings.") - } - } - - @PluginMethod - fun setAppLockEnabled(call: PluginCall) { - try { - val enabled = call.getBoolean("enabled") - ?: throw IllegalArgumentException("Choose whether to lock ep-mail when you leave it.") - val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager - require(!enabled || keyguard.isDeviceSecure) { - "Set a screen lock in Android Settings before enabling the app lock." - } - AndroidAccountVault.setAppLockEnabled(enabled) - (activity as? MainActivity)?.onAppLockSettingChanged(enabled) - call.resolve(JSObject().put("enabled", enabled).put("deviceSecure", keyguard.isDeviceSecure)) - } catch (error: Exception) { - call.reject(error.message ?: "Could not save app-lock settings.") - } - } - - @PluginMethod - fun pgpLoadStore(call: PluginCall) { - try { - call.resolve(AndroidAccountVault.pgpStore().toJSObject()) - } catch (error: Exception) { - call.reject(error.message ?: "Could not load the Android OpenPGP key store.") - } - } - - @PluginMethod - fun pgpSaveStore(call: PluginCall) { - try { - val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.") - val next = JSONObject(candidate.toString()) - val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next) - if (warning == null) { - AndroidAccountVault.savePgpStore(next) - call.resolve(JSObject().put("ok", true)) - } else { - showPgpConfirmation( - title = "Confirm OpenPGP key changes", - message = warning, - confirmLabel = "Confirm changes", - onConfirmed = { - try { - AndroidAccountVault.savePgpStore(next) - call.resolve(JSObject().put("ok", true)) - } catch (error: Exception) { - call.reject(error.message ?: "Could not save the Android OpenPGP key store.") - } - }, - onCancelled = { call.reject("OpenPGP key change cancelled.") } - ) - } - } catch (error: Exception) { - call.reject(error.message ?: "Could not save the Android OpenPGP key store.") - } - } - - private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? { - val oldContacts = previous.optJSONArray("contacts") ?: JSONArray() - val newContacts = candidate.optJSONArray("contacts") ?: JSONArray() - return AndroidPgpPolicy.storeChangeWarning(pgpContacts(oldContacts), pgpContacts(newContacts)) - } - - private fun pgpContacts(values: JSONArray): List = - (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 = - values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty() - - private fun showPgpConfirmation( - title: String, - message: String, - confirmLabel: String, - onConfirmed: () -> Unit, - onCancelled: () -> Unit - ) { - val gate = AndroidPgpConfirmationGate( - showPrompt = { prompt -> - val host = activity - host.runOnUiThread { - AlertDialog.Builder(host) - .setTitle(prompt.title) - .setMessage(prompt.message) - .setNegativeButton(prompt.cancelLabel) { _, _ -> prompt.cancel() } - .setPositiveButton(prompt.confirmLabel) { _, _ -> prompt.confirm() } - .setOnCancelListener { prompt.cancel() } - .show() - } - }, - dispatch = { action -> bridge.execute(action) } - ) - gate.request(title, message, confirmLabel, onConfirmed = onConfirmed, onCancelled = onCancelled) - } - - @PluginMethod - fun pgpGetMessageSource(call: PluginCall) { - try { - val account = AndroidAccountVault.account() - ?: throw IllegalStateException("Add a mail account before opening messages.") - val folder = call.getString("folder") ?: "Inbox" - val uid = call.getLong("uid") ?: 0L - call.resolve(AndroidMailService.pgpMessageSource(account, folder, uid).toJSObject()) - } catch (error: Exception) { - call.reject(error.message ?: "Could not load the encrypted message.") - } - } - - @PluginMethod - fun savePgpAttachment(call: PluginCall) { - try { - call.resolve(AndroidMailService.savePgpAttachment(context, JSONObject(call.data.toString())).toJSObject()) - } catch (error: Exception) { - call.reject(error.message ?: "Could not save the decrypted attachment.") - } - } - - @PluginMethod - fun getAccount(call: PluginCall) { + } + + @PluginMethod + fun getNotificationPrivacy(call: PluginCall) { + try { + call.resolve(JSObject().put("showDetails", AndroidAccountVault.notificationDetailsEnabled())) + } catch (error: Exception) { + call.reject(error.message ?: "Could not read notification privacy settings.") + } + } + + @PluginMethod + fun setNotificationDetails(call: PluginCall) { + try { + val enabled = call.getBoolean("enabled") + ?: throw IllegalArgumentException("Choose whether notifications may show details.") + AndroidAccountVault.setNotificationDetailsEnabled(enabled) + call.resolve(JSObject().put("showDetails", enabled)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save notification privacy settings.") + } + } + + @PluginMethod + fun getAppLockSettings(call: PluginCall) { + try { + val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager + call.resolve(JSObject() + .put("enabled", AndroidAccountVault.appLockEnabled()) + .put("lockDelaySeconds", AndroidAccountVault.appLockDelaySeconds()) + .put("deviceSecure", keyguard.isDeviceSecure)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not read app-lock settings.") + } + } + + @PluginMethod + fun setAppLockEnabled(call: PluginCall) { + try { + val enabled = call.getBoolean("enabled") + ?: throw IllegalArgumentException("Choose whether to lock ep-mail when you leave it.") + val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager + require(!enabled || keyguard.isDeviceSecure) { + "Set a screen lock in Android Settings before enabling the app lock." + } + AndroidAccountVault.setAppLockEnabled(enabled) + (activity as? MainActivity)?.onAppLockSettingChanged(enabled) + call.resolve(JSObject().put("enabled", enabled).put("deviceSecure", keyguard.isDeviceSecure)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save app-lock settings.") + } + } + + @PluginMethod + fun setAppLockDelay(call: PluginCall) { + try { + val seconds = call.getInt("seconds") + ?: throw IllegalArgumentException("Choose when ep-mail should lock after leaving it.") + call.resolve(JSObject().put("lockDelaySeconds", AndroidAccountVault.setAppLockDelaySeconds(seconds))) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save the app-lock delay.") + } + } + + @PluginMethod + fun pgpLoadStore(call: PluginCall) { + try { + call.resolve(AndroidAccountVault.pgpStore().toJSObject()) + } catch (error: Exception) { + call.reject(error.message ?: "Could not load the Android OpenPGP key store.") + } + } + + @PluginMethod + fun pgpSaveStore(call: PluginCall) { + try { + val candidate = call.getObject("store") ?: throw IllegalArgumentException("The OpenPGP key store is missing.") + val next = JSONObject(candidate.toString()) + val warning = pgpStoreChangeWarning(AndroidAccountVault.pgpStore(), next) + if (warning == null) { + AndroidAccountVault.savePgpStore(next) + call.resolve(JSObject().put("ok", true)) + } else { + showPgpConfirmation( + title = "Confirm OpenPGP key changes", + message = warning, + confirmLabel = "Confirm changes", + onConfirmed = { + try { + AndroidAccountVault.savePgpStore(next) + call.resolve(JSObject().put("ok", true)) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save the Android OpenPGP key store.") + } + }, + onCancelled = { call.reject("OpenPGP key change cancelled.") } + ) + } + } catch (error: Exception) { + call.reject(error.message ?: "Could not save the Android OpenPGP key store.") + } + } + + @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 = + (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 = + values?.let { array -> (0 until array.length()).mapNotNull { array.optString(it).takeIf(String::isNotBlank) } }.orEmpty() + + private fun showPgpConfirmation( + title: String, + message: String, + confirmLabel: String, + onConfirmed: () -> Unit, + onCancelled: () -> Unit + ) { + val gate = AndroidPgpConfirmationGate( + showPrompt = { prompt -> + val host = activity + host.runOnUiThread { + AlertDialog.Builder(host) + .setTitle(prompt.title) + .setMessage(prompt.message) + .setNegativeButton(prompt.cancelLabel) { _, _ -> prompt.cancel() } + .setPositiveButton(prompt.confirmLabel) { _, _ -> prompt.confirm() } + .setOnCancelListener { prompt.cancel() } + .show() + } + }, + dispatch = { action -> bridge.execute(action) } + ) + gate.request(title, message, confirmLabel, onConfirmed = onConfirmed, onCancelled = onCancelled) + } + + @PluginMethod + fun pgpGetMessageSource(call: PluginCall) { + try { + val account = AndroidAccountVault.account() + ?: throw IllegalStateException("Add a mail account before opening messages.") + val folder = call.getString("folder") ?: "Inbox" + val uid = call.getLong("uid") ?: 0L + call.resolve(AndroidMailService.pgpMessageSource(account, folder, uid).toJSObject()) + } catch (error: Exception) { + call.reject(error.message ?: "Could not load the encrypted message.") + } + } + + @PluginMethod + fun savePgpAttachment(call: PluginCall) { + try { + call.resolve(AndroidMailService.savePgpAttachment(context, JSONObject(call.data.toString())).toJSObject()) + } catch (error: Exception) { + call.reject(error.message ?: "Could not save the decrypted attachment.") + } + } + + @PluginMethod + fun getAccount(call: PluginCall) { val account = AndroidAccountVault.account() if (account == null) call.resolve() else call.resolve(AndroidAccountVault.publicAccount(account).toJSObject()) @@ -263,6 +402,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 fun connect(call: PluginCall) { try { @@ -452,33 +626,33 @@ class EpMailPlugin : Plugin() { } @PluginMethod - fun send(call: PluginCall) { - val input = JSONObject(call.data.toString()).apply { - if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>") - } - val warning = try { plaintextSendWarning(input) } catch (error: Exception) { - call.reject(error.message ?: "Could not check the OpenPGP send policy.") - return - } - if (warning == null) { - sendPrepared(call, input) - return - } - showPgpConfirmation( - title = "Send without OpenPGP encryption?", - message = warning, - confirmLabel = "Send plaintext", - onConfirmed = { sendPrepared(call, input) }, - onCancelled = { - call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled.")) - } - ) - } - - private fun sendPrepared(call: PluginCall, input: JSONObject) { - try { - val account = AndroidAccountVault.account() - ?: throw IllegalStateException("Add a mail account before sending.") + fun send(call: PluginCall) { + val input = JSONObject(call.data.toString()).apply { + if (optString("messageId").isBlank()) put("messageId", "<${UUID.randomUUID()}@ep-mail.local>") + } + val warning = try { plaintextSendWarning(input) } catch (error: Exception) { + call.reject(error.message ?: "Could not check the OpenPGP send policy.") + return + } + if (warning == null) { + sendPrepared(call, input) + return + } + showPgpConfirmation( + title = "Send without OpenPGP encryption?", + message = warning, + confirmLabel = "Send plaintext", + onConfirmed = { sendPrepared(call, input) }, + onCancelled = { + call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled.")) + } + ) + } + + private fun sendPrepared(call: PluginCall, input: JSONObject) { + try { + val account = AndroidAccountVault.account() + ?: throw IllegalStateException("Add a mail account before sending.") call.resolve(AndroidMailService.send(account, input).toJSObject()) } catch (error: Exception) { val account = AndroidAccountVault.account() @@ -488,36 +662,36 @@ class EpMailPlugin : Plugin() { .put("type", "send") .put("data", input)) call.resolve(JSObject().put("ok", true).put("queued", true)) - } else call.reject(error.message ?: "Could not send the message.") - } - } - - private fun plaintextSendWarning(input: JSONObject): String? { - if (input.optString("rawBase64").isNotBlank()) return null - val recipients = (listOf(input.optString("to"), input.optString("cc")) - .filter(String::isNotBlank) - .flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } }) - .distinct() - val data = AndroidAccountVault.pgpStore() - val contacts = data.optJSONArray("contacts") ?: JSONArray() - val keys = data.optJSONArray("keys") ?: JSONArray() - val available = ArrayList() - for (address in recipients) { - for (index in 0 until contacts.length()) { - val contact = contacts.optJSONObject(index) ?: continue - if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) { - available.add(AndroidPgpPolicy.RecipientKey(address, contact.optString("fingerprint"))) - } - } - for (index in 0 until keys.length()) { - val key = keys.optJSONObject(index) ?: continue - if (key.optString("email").equals(address, true)) { - available.add(AndroidPgpPolicy.RecipientKey(address, key.optString("fingerprint"))) - } - } - } - return AndroidPgpPolicy.plaintextSendWarning(recipients, available, input.optBoolean("pgpRequested")) - } + } else call.reject(error.message ?: "Could not send the message.") + } + } + + private fun plaintextSendWarning(input: JSONObject): String? { + if (input.optString("rawBase64").isNotBlank()) return null + val recipients = (listOf(input.optString("to"), input.optString("cc")) + .filter(String::isNotBlank) + .flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } }) + .distinct() + val data = AndroidAccountVault.pgpStore() + val contacts = data.optJSONArray("contacts") ?: JSONArray() + val keys = data.optJSONArray("keys") ?: JSONArray() + val available = ArrayList() + for (address in recipients) { + for (index in 0 until contacts.length()) { + val contact = contacts.optJSONObject(index) ?: continue + if (jsonStrings(contact.optJSONArray("emails")).any { it.equals(address, true) }) { + available.add(AndroidPgpPolicy.RecipientKey(address, contact.optString("fingerprint"))) + } + } + for (index in 0 until keys.length()) { + val key = keys.optJSONObject(index) ?: continue + if (key.optString("email").equals(address, true)) { + available.add(AndroidPgpPolicy.RecipientKey(address, key.optString("fingerprint"))) + } + } + } + return AndroidPgpPolicy.plaintextSendWarning(recipients, available, input.optBoolean("pgpRequested")) + } @PluginMethod fun listDrafts(call: PluginCall) { @@ -666,17 +840,17 @@ class EpMailPlugin : Plugin() { private fun normalizeAccount(input: JSONObject): JSONObject { val email = input.optString("email").trim() val password = input.optString("password") - val displayName = input.optString("displayName").trim().take(80) - val imapHost = input.optString("imapHost").trim() - val smtpHost = input.optString("smtpHost").trim() - val imapPort = input.optInt("imapPort", 143) - val smtpPort = input.optInt("smtpPort", 587) - require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) { - "Enter a valid email, account display name, password, and both mail server names." - } - require(imapPort in 1..65535 && smtpPort in 1..65535) { - "Enter valid IMAP and SMTP ports (1–65535)." - } + val displayName = input.optString("displayName").trim().take(80) + val imapHost = input.optString("imapHost").trim() + val smtpHost = input.optString("smtpHost").trim() + val imapPort = input.optInt("imapPort", 143) + val smtpPort = input.optInt("smtpPort", 587) + require(EMAIL.matches(email) && password.isNotBlank() && displayName.isNotBlank() && imapHost.isNotBlank() && smtpHost.isNotBlank()) { + "Enter a valid email, account display name, password, and both mail server names." + } + require(imapPort in 1..65535 && smtpPort in 1..65535) { + "Enter valid IMAP and SMTP ports (1–65535)." + } return JSONObject() .put("id", input.optString("id").ifBlank { UUID.randomUUID().toString() }) .put("email", email) @@ -690,10 +864,10 @@ class EpMailPlugin : Plugin() { require(it in setOf(2, 5, 15, 30, 60)) { "Choose a supported mailbox sync interval." } }) .put("rules", normalizeRules(input.optJSONArray("rules"))) - .put("imapPort", imapPort) - .put("smtpPort", smtpPort) - .put("imapSecure", input.optBoolean("imapSecure", false)) - .put("smtpSecure", input.optBoolean("smtpSecure", false)) + .put("imapPort", imapPort) + .put("smtpPort", smtpPort) + .put("imapSecure", input.optBoolean("imapSecure", false)) + .put("smtpSecure", input.optBoolean("smtpSecure", false)) } private fun normalizeRules(input: JSONArray?): JSONArray { diff --git a/android/app/src/main/java/studio/daybreak/mail/MainActivity.java b/android/app/src/main/java/studio/daybreak/mail/MainActivity.java index 9c1c643..afdb68b 100644 --- a/android/app/src/main/java/studio/daybreak/mail/MainActivity.java +++ b/android/app/src/main/java/studio/daybreak/mail/MainActivity.java @@ -1,5 +1,5 @@ -package studio.daybreak.mail; - +package studio.daybreak.mail; + import android.Manifest; import android.app.KeyguardManager; import android.content.Context; @@ -9,17 +9,25 @@ import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.SystemClock; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.WebView; +import android.webkit.WebStorage; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.biometric.BiometricManager; +import androidx.biometric.BiometricPrompt; import com.getcapacitor.BridgeActivity; +import javax.crypto.Cipher; public class MainActivity extends BridgeActivity { private static final int UNLOCK_REQUEST_CODE = 705; @@ -28,8 +36,18 @@ public class MainActivity extends BridgeActivity { private Button appLockButton; private boolean appLocked; private boolean awaitingUnlockResult; + private boolean pgpAuthInProgress; + private boolean pgpAuthPaused; + private long pgpAuthPauseAt; private boolean activityResumed; private boolean vaultRecoveryRequired; + private final Handler appLockHandler = new Handler(Looper.getMainLooper()); + private final Runnable delayedAppLock = () -> { + if (!activityResumed && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView(); + }; + private final Runnable lockAfterPgpAuth = () -> { + if (!activityResumed && pgpAuthPaused && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView(); + }; @Override public void onCreate(Bundle savedInstanceState) { @@ -56,6 +74,10 @@ public class MainActivity extends BridgeActivity { super.onResume(); if (vaultRecoveryRequired) return; activityResumed = true; + appLockHandler.removeCallbacks(delayedAppLock); + appLockHandler.removeCallbacks(lockAfterPgpAuth); + pgpAuthPaused = false; + if (!appLocked) getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE); if (isAppLockEnabled() && appLocked) { lockWebView(); configureUnlockButton(); @@ -65,7 +87,19 @@ public class MainActivity extends BridgeActivity { @Override public void onPause() { activityResumed = false; - if (!vaultRecoveryRequired && isAppLockEnabled()) lockWebView(); + if (!vaultRecoveryRequired && isAppLockEnabled() && !pgpAuthInProgress) { + int delaySeconds = appLockDelaySeconds(); + if (delaySeconds == 0) { + lockWebView(); + } else { + getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); + appLockHandler.postDelayed(delayedAppLock, delaySeconds * 1000L); + } + } else if (!vaultRecoveryRequired && isAppLockEnabled() && pgpAuthInProgress) { + pgpAuthPaused = true; + pgpAuthPauseAt = SystemClock.elapsedRealtime(); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE); + } super.onPause(); } @@ -78,8 +112,18 @@ public class MainActivity extends BridgeActivity { else updateAppLockMessage("Unlock with your Android screen lock to view mail."); } + @Override + public void onDestroy() { + appLockHandler.removeCallbacks(delayedAppLock); + appLockHandler.removeCallbacks(lockAfterPgpAuth); + super.onDestroy(); + } + public void onAppLockSettingChanged(boolean enabled) { runOnUiThread(() -> { + appLockHandler.removeCallbacks(delayedAppLock); + appLockHandler.removeCallbacks(lockAfterPgpAuth); + pgpAuthPaused = false; if (!enabled) { awaitingUnlockResult = false; unlockWebView(false); @@ -91,6 +135,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() { try { return AndroidAccountVault.INSTANCE.appLockEnabled(); diff --git a/android/app/src/test/java/studio/daybreak/mail/AndroidAppLockPolicyTest.kt b/android/app/src/test/java/studio/daybreak/mail/AndroidAppLockPolicyTest.kt new file mode 100644 index 0000000..7fb879d --- /dev/null +++ b/android/app/src/test/java/studio/daybreak/mail/AndroidAppLockPolicyTest.kt @@ -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) + } + } +} diff --git a/android/app/src/test/java/studio/daybreak/mail/AndroidDownloadPolicyTest.kt b/android/app/src/test/java/studio/daybreak/mail/AndroidDownloadPolicyTest.kt new file mode 100644 index 0000000..2803e0c --- /dev/null +++ b/android/app/src/test/java/studio/daybreak/mail/AndroidDownloadPolicyTest.kt @@ -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")) + } +} diff --git a/android/app/src/test/java/studio/daybreak/mail/BoundedInputReaderTest.kt b/android/app/src/test/java/studio/daybreak/mail/BoundedInputReaderTest.kt new file mode 100644 index 0000000..78a2dc1 --- /dev/null +++ b/android/app/src/test/java/studio/daybreak/mail/BoundedInputReaderTest.kt @@ -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) + ) + } +} diff --git a/package-lock.json b/package-lock.json index f178ff1..d5c4b5f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.5.12", + "version": "0.5.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.5.12", + "version": "0.5.13", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index 2fa8d7e..d692fd5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.5.12", + "version": "0.5.13", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", diff --git a/pgp-mail-ui.js b/pgp-mail-ui.js index 1c3a004..3c3165e 100644 --- a/pgp-mail-ui.js +++ b/pgp-mail-ui.js @@ -6,70 +6,70 @@ const selectAllPgpMailUi = pgpMailUi.selectAll; const toastPgpMailUi = pgpMailUi.toast; const escapePgpMailUi = pgpMailUi.escapeHtml; const pgpApi = () => window.daybreakMail?.pgp; - -function pgpAskPassphrase(title, detail) { - return new Promise(resolve => { - const overlay = document.createElement('div'); - overlay.className = 'modal-overlay pgp-prompt'; - overlay.innerHTML = `
`; - overlay.querySelector('.modal-head span').textContent = title; - overlay.querySelector('.account-note').textContent = detail; - const finish = value => { overlay.remove(); resolve(value); }; - overlay.querySelector('form').onsubmit = event => { - event.preventDefault(); - const value = overlay.querySelector('input').value; - if (value) finish(value); - }; - overlay.querySelector('[data-cancel]').onclick = () => finish(null); - overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } }); - document.body.append(overlay); - overlay.querySelector('input').focus(); - }); -} - -function pgpFormatFingerprint(value) { - return String(value || '').match(/.{1,4}/g)?.join(' ') || ''; -} - -function pgpSignatureHtml(signatures, encrypted) { - const items = Array.isArray(signatures) ? signatures : []; - const lock = encrypted ? '🔒 Encrypted. ' : ''; - if (!items.length) { - return encrypted ? `
${lock}Not signedThe sender is not authenticated: anyone with your public key could have written this.
` : ''; - } - return items.map(signature => { - const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet'; - 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.mismatch) notes.push('The signing key does not belong to the sender address.'); - if (signature.status === 'valid') { - const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok'; + +function pgpAskPassphrase(title, detail) { + return new Promise(resolve => { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay pgp-prompt'; + overlay.innerHTML = `
`; + overlay.querySelector('.modal-head span').textContent = title; + overlay.querySelector('.account-note').textContent = detail; + const finish = value => { overlay.remove(); resolve(value); }; + overlay.querySelector('form').onsubmit = event => { + event.preventDefault(); + const value = overlay.querySelector('input').value; + if (value) finish(value); + }; + overlay.querySelector('[data-cancel]').onclick = () => finish(null); + overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } }); + document.body.append(overlay); + overlay.querySelector('input').focus(); + }); +} + +function pgpFormatFingerprint(value) { + return String(value || '').match(/.{1,4}/g)?.join(' ') || ''; +} + +function pgpSignatureHtml(signatures, encrypted) { + const items = Array.isArray(signatures) ? signatures : []; + const lock = encrypted ? '🔒 Encrypted. ' : ''; + if (!items.length) { + return encrypted ? `
${lock}Not signedThe sender is not authenticated: anyone with your public key could have written this.
` : ''; + } + return items.map(signature => { + const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet'; + 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.mismatch) notes.push('The signing key does not belong to the sender address.'); + if (signature.status === 'valid') { + const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok'; return `
${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}${notes.map(note => `${escapePgpMailUi(note)}`).join('')}
`; - } - if (signature.status === 'unknown-key') { + } + if (signature.status === 'unknown-key') { return `
${lock}Signed with an unknown keyKey ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.${notes.map(note => `${escapePgpMailUi(note)}`).join('')}
`; - } - return ``; - }).join(''); -} - -async function pgpAddAttachedKey(key) { - 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; - try { - 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'); - } catch (error) { - toastPgpMailUi(error.message || 'Could not add the key'); - } -} - -function pgpRenderReaderState(message) { - const reader = selectPgpMailUi('#reader-pane'); - const header = reader.querySelector('.reader-header'); - if (!header) return; - reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); - let html = ''; + } + return ``; + }).join(''); +} + +async function pgpAddAttachedKey(key) { + 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; + try { + 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'); + } catch (error) { + toastPgpMailUi(error.message || 'Could not add the key'); + } +} + +function pgpRenderReaderState(message) { + const reader = selectPgpMailUi('#reader-pane'); + const header = reader.querySelector('.reader-header'); + if (!header) return; + reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); + let html = ''; if (message.encrypted && !message.pgpDecrypted) { html = `
🔒 This message is encryptedUnlock it with your key passphrase to read it.
`; } else if (message.encrypted) { @@ -82,44 +82,49 @@ function pgpRenderReaderState(message) { html = '
Checking OpenPGP signature…Do not rely on this message until verification completes.
'; } else if (message.pgpSignatures) { html = pgpSignatureHtml(message.pgpSignatures, false); - } - const keys = message.pgpResult?.attachedKeys || []; + } + const keys = message.pgpResult?.attachedKeys || []; header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `
Public key attached${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}
`).join('')); - reader.querySelectorAll('[data-pgp-key]').forEach(button => { - button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]); - }); - const unlock = selectPgpMailUi('#pgp-unlock'); - if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); -} - + reader.querySelectorAll('[data-pgp-key]').forEach(button => { + button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]); + }); + const unlock = selectPgpMailUi('#pgp-unlock'); + if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); +} + async function pgpUnlockMessage(message, interactive) { - let passphrase = null; - for (let attempt = 0; attempt < 3; attempt += 1) { - let result; - try { - result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase }); - } catch (error) { - toastPgpMailUi(error.message || 'Could not open this message'); - return; - } - if (result.ok) { - Object.assign(message, { - 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 } - }); + let passphrase = null; + for (let attempt = 0; attempt < 3; attempt += 1) { + let result; + try { + result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase }); + } catch (error) { + toastPgpMailUi(error.message || 'Could not open this message'); + return; + } + if (result.ok) { + Object.assign(message, { + 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 } + }); if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id); - return; - } - if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') { - 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'}.`); - if (passphrase === null) return; - continue; - } - const text = selectPgpMailUi('#pgp-banner-text'); - if (text) text.textContent = result.message; - else toastPgpMailUi(result.message); - return; + return; + } + if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') { + if (!interactive) { pgpRenderReaderState(message); return; } + const prompt = result.code === 'BAD_PASSPHRASE' + ? 'That passphrase was incorrect. Try again.' + : result.code === 'BIOMETRIC_INVALIDATED' + ? `${result.message} Enter the passphrase to continue.` + : `Enter the passphrase for ${result.email || 'your key'}.`; + passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt); + if (passphrase === null) return; + continue; + } + const text = selectPgpMailUi('#pgp-banner-text'); + if (text) text.textContent = result.message; + else toastPgpMailUi(result.message); + return; } } @@ -141,7 +146,7 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); const message = pgpMailUi.state.messages.find(item => item.id === id); if (!message || !pgpApi()) return; - pgpRenderReaderState(message); + pgpRenderReaderState(message); if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { message.pgpAutoTried = true; void pgpUnlockMessage(message, false); @@ -154,40 +159,40 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { // Compose: encrypt/sign options. pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { - baseShowCompose(reply, forward); - const footer = selectPgpMailUi('#modal-root .compose-footer'); - if (!footer || !pgpApi()) return; - const box = document.createElement('div'); - box.className = 'pgp-compose'; + baseShowCompose(reply, forward); + const footer = selectPgpMailUi('#modal-root .compose-footer'); + if (!footer || !pgpApi()) return; + const box = document.createElement('div'); + box.className = 'pgp-compose'; box.innerHTML = `${pgpApi().platform === 'android' ? '' : ''}`; - footer.prepend(box); - let touched = false; - const encrypt = selectPgpMailUi('#pgp-encrypt'); - const sign = selectPgpMailUi('#pgp-sign'); - if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } - if (touched) encrypt.dataset.touched = '1'; - encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; }); - let timer = null; - const refresh = async () => { - const to = selectPgpMailUi('#compose-to')?.value || ''; - const cc = selectPgpMailUi('#compose-cc')?.value || ''; - const hint = selectPgpMailUi('#pgp-hint'); - if (!hint) return; - if (!to.trim()) { hint.textContent = ''; return; } - try { - const status = await pgpApi().checkSend({ to, cc, sign: sign.checked }); - if (!selectPgpMailUi('#pgp-hint')) return; - if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`; - else { - hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients'; - if (!touched && !encrypt.checked) encrypt.checked = true; - } - } catch { hint.textContent = ''; } - }; - const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); }; - ['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule)); - sign.addEventListener('change', schedule); - schedule(); + footer.prepend(box); + let touched = false; + const encrypt = selectPgpMailUi('#pgp-encrypt'); + const sign = selectPgpMailUi('#pgp-sign'); + if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } + if (touched) encrypt.dataset.touched = '1'; + encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; }); + let timer = null; + const refresh = async () => { + const to = selectPgpMailUi('#compose-to')?.value || ''; + const cc = selectPgpMailUi('#compose-cc')?.value || ''; + const hint = selectPgpMailUi('#pgp-hint'); + if (!hint) return; + if (!to.trim()) { hint.textContent = ''; return; } + try { + const status = await pgpApi().checkSend({ to, cc, sign: sign.checked }); + if (!selectPgpMailUi('#pgp-hint')) return; + if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`; + else { + hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients'; + if (!touched && !encrypt.checked) encrypt.checked = true; + } + } catch { hint.textContent = ''; } + }; + const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); }; + ['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule)); + sign.addEventListener('change', schedule); + schedule(); }); // Called by the send handler. Returns null (plain mail), false (cancelled) or send options. @@ -196,30 +201,30 @@ async function prepareSend(to, cc) { const plaintextFallback = () => pgpApi().platform === 'android' ? { encrypt: false, sign: false, plaintextFallback: true } : null; - let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked); - const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked); - if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null; - 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. - if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') { + let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked); + const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked); + if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null; + const status = await pgpApi().checkSend({ to, cc, sign }); + // The default-on update is debounced, so a quick send could skip encryption even though keys exist. + if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') { if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) { if (!sign) return plaintextFallback(); - } else return false; - } - if (!encrypt && !sign) return null; - 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?`); + } else return false; + } + if (!encrypt && !sign) return null; + 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?`); if (!sendPlain) return false; encrypt = false; if (!sign) return plaintextFallback(); - } - let passphrase = null; - if (sign) { - if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; } - if (!status.signer.unlocked) { - passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`); - if (passphrase === null) return false; - } + } + let passphrase = null; + if (sign) { + if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; } + if (!status.signer.unlocked && !status.signer.biometricUnlockEnabled) { + passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`); + if (passphrase === null) return false; + } } return { encrypt, sign, passphrase }; } diff --git a/pgp-ui.js b/pgp-ui.js index 22f4bf4..3ee0a48 100644 --- a/pgp-ui.js +++ b/pgp-ui.js @@ -14,8 +14,8 @@ async function saveAndroidPgpExport(label, value) { else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true }; return { saved: true }; } - -function openEncryptionKeys() { + +function openEncryptionKeys() { const root = selectPgpKeyUi('#modal-root'); const account = window.epMailFeatures.mail.connectedAccount || {}; const androidPgp = window.daybreakMail?.pgp?.platform === 'android'; @@ -35,401 +35,437 @@ function openEncryptionKeys() {
`; root.innerHTML = ``; - const close = () => { root.innerHTML = ''; }; - root.querySelector('.modal-close').onclick = close; - root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; - const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; }; - const passphraseField = () => selectPgpKeyUi('#pgp-passphrase'); - let keyServers = []; - const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled); - const updatePublishButtons = () => { - const server = selectedPublishServer(); - selectAllPgpKeyUi('.pgp-publish').forEach(button => { - button.disabled = !server; - button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…'; - }); - }; - const needPassphrase = () => { - const value = passphraseField().value; - if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); } - return value; - }; - - async function render() { - const list = selectPgpKeyUi('#pgp-key-list'); - let keys = []; - try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; } - list.replaceChildren(); - if (!keys.length) { list.textContent = 'No keys yet.'; return; } - keys.forEach(key => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = key.email || 'OpenPGP key'; - const meta = document.createElement('small'); - meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`; - const fingerprint = document.createElement('small'); - fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; - info.append(title, meta, fingerprint); - row.append(info); - const actions = [ - ['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false], - ['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true] - ]; - const changePassphrase = document.createElement('button'); - changePassphrase.className = 'discard'; - changePassphrase.textContent = 'Change passphrase…'; - changePassphrase.onclick = async () => { - const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value; - if (!currentPassphrase) { - status('Enter the current passphrase for this key.'); - selectPgpKeyUi('#pgp-change-current-passphrase').focus(); - return; - } - const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value; - if (newPassphrase.length < 8) { - status('Use a new passphrase of at least 8 characters.'); - selectPgpKeyUi('#pgp-new-passphrase').focus(); - return; - } - if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) { - status('The new passphrases do not match.'); - selectPgpKeyUi('#pgp-confirm-passphrase').focus(); - return; - } - changePassphrase.disabled = true; - try { - await window.daybreakMail.pgp.changePassphrase({ - fingerprint: key.fingerprint, - currentPassphrase, - newPassphrase - }); - selectPgpKeyUi('#pgp-change-current-passphrase').value = ''; - status(`Passphrase changed for ${key.email || key.fingerprint}.`); - } catch (error) { status(error.message || 'Could not change the key passphrase.'); } - finally { - selectPgpKeyUi('#pgp-new-passphrase').value = ''; - selectPgpKeyUi('#pgp-confirm-passphrase').value = ''; - changePassphrase.disabled = false; - } - }; - row.append(changePassphrase); - 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 { +

Passphrase memory

+ +
+ +

Create a key

+ + + +
+ + `; + const close = () => { root.innerHTML = ''; }; + root.querySelector('.modal-close').onclick = close; + root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; + const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; }; + const passphraseField = () => selectPgpKeyUi('#pgp-passphrase'); + let keyServers = []; + const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled); + const updatePublishButtons = () => { + const server = selectedPublishServer(); + selectAllPgpKeyUi('.pgp-publish').forEach(button => { + button.disabled = !server; + button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…'; + }); + }; + const needPassphrase = () => { + const value = passphraseField().value; + if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); } + return value; + }; + + async function render() { + const list = selectPgpKeyUi('#pgp-key-list'); + let keys = []; + try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; } + list.replaceChildren(); + if (!keys.length) { list.textContent = 'No keys yet.'; return; } + keys.forEach(key => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = key.email || 'OpenPGP key'; + const meta = document.createElement('small'); + meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`; + const fingerprint = document.createElement('small'); + fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; + info.append(title, meta, fingerprint); + row.append(info); + const actions = [ + ['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false], + ['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true] + ]; + const changePassphrase = document.createElement('button'); + changePassphrase.className = 'discard'; + changePassphrase.textContent = 'Change passphrase…'; + changePassphrase.onclick = async () => { + const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value; + if (!currentPassphrase) { + status('Enter the current passphrase for this key.'); + selectPgpKeyUi('#pgp-change-current-passphrase').focus(); + return; + } + const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value; + if (newPassphrase.length < 8) { + status('Use a new passphrase of at least 8 characters.'); + selectPgpKeyUi('#pgp-new-passphrase').focus(); + return; + } + if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) { + status('The new passphrases do not match.'); + selectPgpKeyUi('#pgp-confirm-passphrase').focus(); + return; + } + changePassphrase.disabled = true; + try { + await window.daybreakMail.pgp.changePassphrase({ + fingerprint: key.fingerprint, + currentPassphrase, + newPassphrase + }); + selectPgpKeyUi('#pgp-change-current-passphrase').value = ''; + status(`Passphrase changed for ${key.email || key.fingerprint}.`); + } catch (error) { status(error.message || 'Could not change the key passphrase.'); } + finally { + selectPgpKeyUi('#pgp-new-passphrase').value = ''; + selectPgpKeyUi('#pgp-confirm-passphrase').value = ''; + changePassphrase.disabled = false; + } + }; + row.append(changePassphrase); + if (androidPgp) { + const biometric = document.createElement('button'); + biometric.className = 'discard'; + biometric.textContent = 'Checking biometric unlock…'; + biometric.disabled = true; + row.append(biometric); + window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => { + if (!biometric.isConnected) return; + biometric.dataset.enabled = String(enabled); + biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…'; + biometric.disabled = false; + }).catch(error => { + if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.'); + }); + biometric.onclick = async () => { + biometric.disabled = true; + try { + if (biometric.dataset.enabled === 'true') { + if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return; + await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint); + status('Biometric unlock disabled.'); + } else { + const passphrase = needPassphrase(); + if (!passphrase) return; + await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase }); + passphraseField().value = ''; + status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.'); + } + await render(); + } catch (error) { + status(error.message || 'Could not update biometric key unlock.'); + } finally { + biometric.disabled = false; + } + }; + } + if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]); + actions.push(['Delete', async () => { + if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true }; + 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()); - status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : ''); - } catch (error) { status(error.message || 'That action failed.'); } - }; - row.append(button); - }); - const publish = document.createElement('button'); - publish.className = 'discard pgp-publish'; - publish.onclick = async () => { - const server = selectedPublishServer(); - if (!server) { status('Enable a key server and select it as the publication target first.'); return; } - publish.disabled = true; - try { - const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id }); - if (result.canceled) return; - 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 === '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 === '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()); - } catch (error) { status(error.message || 'Could not publish the public key.'); } - finally { updatePublishButtons(); } - }; - row.append(publish); - list.append(row); - }); - updatePublishButtons(); - } - - selectPgpKeyUi('#pgp-generate').onclick = async () => { - const button = selectPgpKeyUi('#pgp-generate'); - button.disabled = true; - status('Creating key…'); - try { - await window.daybreakMail.pgp.generate({ - 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.'); - await render(); - } catch (error) { status(error.message || 'Could not create the key.'); } - button.disabled = false; - }; - selectPgpKeyUi('#pgp-import').onclick = async () => { - const passphrase = needPassphrase(); - if (!passphrase) return; - try { - const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null }); + status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : ''); + } catch (error) { status(error.message || 'That action failed.'); } + }; + row.append(button); + }); + const publish = document.createElement('button'); + publish.className = 'discard pgp-publish'; + publish.onclick = async () => { + const server = selectedPublishServer(); + if (!server) { status('Enable a key server and select it as the publication target first.'); return; } + publish.disabled = true; + try { + const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id }); + if (result.canceled) return; + 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 === '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 === '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()); + } catch (error) { status(error.message || 'Could not publish the public key.'); } + finally { updatePublishButtons(); } + }; + row.append(publish); + list.append(row); + }); + updatePublishButtons(); + } + + selectPgpKeyUi('#pgp-generate').onclick = async () => { + const button = selectPgpKeyUi('#pgp-generate'); + button.disabled = true; + status('Creating key…'); + try { + await window.daybreakMail.pgp.generate({ + 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.'); + await render(); + } catch (error) { status(error.message || 'Could not create the key.'); } + button.disabled = false; + }; + selectPgpKeyUi('#pgp-import').onclick = async () => { + const passphrase = needPassphrase(); + if (!passphrase) return; + try { + const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null }); 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(); - } catch (error) { status(error.message || 'Could not import the key.'); } - }; - async function renderContacts() { - const list = selectPgpKeyUi('#pgp-contact-list'); - let contacts = []; - try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; } - list.replaceChildren(); - if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; } - contacts.forEach(contact => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = contact.emails.join(', ') || contact.name || 'Public key'; - const meta = document.createElement('small'); - meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`; - const fingerprint = document.createElement('small'); - fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`; - info.append(title, meta, fingerprint); - const trust = document.createElement('select'); - trust.className = 'pgp-trust'; - trust.setAttribute('aria-label', 'Key trust'); - [['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => { - const option = document.createElement('option'); - option.value = value; option.textContent = label; option.selected = contact.trust === value; - trust.append(option); - }); - trust.onchange = async () => { - 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; - return; - } - try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); } - catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); } - }; - const actions = [ - ['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)], - ['Remove', async () => { - if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: 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'); - button.className = 'discard'; - button.textContent = label; - button.onclick = async () => { + await render(); + } catch (error) { status(error.message || 'Could not import the key.'); } + }; + async function renderContacts() { + const list = selectPgpKeyUi('#pgp-contact-list'); + let contacts = []; + try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; } + list.replaceChildren(); + if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; } + contacts.forEach(contact => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = contact.emails.join(', ') || contact.name || 'Public key'; + const meta = document.createElement('small'); + meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`; + const fingerprint = document.createElement('small'); + fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`; + info.append(title, meta, fingerprint); + const trust = document.createElement('select'); + trust.className = 'pgp-trust'; + trust.setAttribute('aria-label', 'Key trust'); + [['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => { + const option = document.createElement('option'); + option.value = value; option.textContent = label; option.selected = contact.trust === value; + trust.append(option); + }); + trust.onchange = async () => { + 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; + return; + } + try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); } + catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); } + }; + const actions = [ + ['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)], + ['Remove', async () => { + if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: 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'); + 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.' : ''); } - catch (error) { status(error.message || 'That action failed.'); } - }; - row.append(button); - }); - list.append(row); - }); - } - - selectPgpKeyUi('#pgp-add-contact').onclick = async () => { - try { - 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.'); - await renderContacts(); - } catch (error) { status(error.message || 'Could not import the key.'); } - }; - async function renderKeyServers() { - const list = selectPgpKeyUi('#pgp-server-list'); - const selector = selectPgpKeyUi('#pgp-publish-server'); - const selectedId = selector.value; - try { keyServers = await window.daybreakMail.pgp.keyServers(); } - catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; } - selector.replaceChildren(); - const enabledServers = keyServers.filter(server => server.enabled); - if (!enabledServers.length) { - const option = document.createElement('option'); - option.value = ''; - option.textContent = 'No enabled servers'; - selector.append(option); - } else enabledServers.forEach(server => { - const option = document.createElement('option'); - option.value = server.id; - option.textContent = `${server.name} (${server.protocol.toUpperCase()})`; - option.selected = server.id === selectedId; - selector.append(option); - }); - if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0; - selector.onchange = updatePublishButtons; - list.replaceChildren(); - keyServers.forEach(server => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = server.name; - const details = document.createElement('small'); - details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`; - info.append(title, details); - const enabledLabel = document.createElement('label'); - enabledLabel.className = 'compose-line'; - const enabledText = document.createElement('span'); - enabledText.textContent = 'Use for lookup and publishing'; - const enabled = document.createElement('input'); - enabled.type = 'checkbox'; - enabled.checked = server.enabled; - enabled.setAttribute('aria-label', `${server.name} enabled`); - enabled.onchange = async () => { - enabled.disabled = true; - try { - await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked); - await renderKeyServers(); - status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`); - } catch (error) { - enabled.checked = server.enabled; - status(error.message || `Could not update ${server.name}.`); - } finally { enabled.disabled = false; } - }; - enabledLabel.append(enabledText, enabled); - row.append(info, enabledLabel); - if (!server.builtin) { - const remove = document.createElement('button'); - remove.className = 'discard'; - remove.textContent = 'Remove'; - remove.onclick = async () => { - try { - await window.daybreakMail.pgp.removeKeyServer(server.id); - await renderKeyServers(); - status('Custom key server removed.'); - } catch (error) { status(error.message || 'Could not remove the key server.'); } - }; - row.append(remove); - } - list.append(row); - }); - } - selectPgpKeyUi('#pgp-find-key').onclick = async () => { - const button = selectPgpKeyUi('#pgp-find-key'); - const results = selectPgpKeyUi('#pgp-found-keys'); - button.disabled = true; - results.textContent = 'Searching…'; - try { - const found = await window.daybreakMail.pgp.findKey({ - email: selectPgpKeyUi('#pgp-search-email').value - }); - results.replaceChildren(); - found.keys.forEach(key => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = key.emails.join(', ') || key.name || 'Public key'; - const meta = document.createElement('small'); - meta.textContent = `Found on ${key.sources.join(', ')} · not verified`; - const fingerprint = document.createElement('small'); - fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; - info.append(title, meta, fingerprint); - const add = document.createElement('button'); - add.className = 'discard'; - add.textContent = 'Add to contacts…'; - add.onclick = async () => { - add.disabled = true; - try { - const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' }); - if (result.canceled) return; - 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.'); - await renderContacts(); - row.remove(); - } catch (error) { status(error.message || 'Could not add the public key.'); } - finally { add.disabled = false; } - }; - row.append(info, add); - results.append(row); - }); - found.errors.forEach(error => { - const warning = document.createElement('small'); - 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.` : ''}`); - else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`); - else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`); - } catch (error) { - results.textContent = ''; - 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'); - button.disabled = true; - try { - const result = await window.daybreakMail.pgp.addKeyServer({ - name: selectPgpKeyUi('#pgp-server-name').value, - url: selectPgpKeyUi('#pgp-server-url').value, - protocol: selectPgpKeyUi('#pgp-server-protocol').value - }); - if (result.canceled) return; - selectPgpKeyUi('#pgp-server-name').value = ''; - selectPgpKeyUi('#pgp-server-url').value = ''; - await renderKeyServers(); - status('Custom key server added.'); - } 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 () => { - 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.'); }; + catch (error) { status(error.message || 'That action failed.'); } + }; + row.append(button); + }); + list.append(row); + }); + } + + selectPgpKeyUi('#pgp-add-contact').onclick = async () => { + try { + 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.'); + await renderContacts(); + } catch (error) { status(error.message || 'Could not import the key.'); } + }; + async function renderKeyServers() { + const list = selectPgpKeyUi('#pgp-server-list'); + const selector = selectPgpKeyUi('#pgp-publish-server'); + const selectedId = selector.value; + try { keyServers = await window.daybreakMail.pgp.keyServers(); } + catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; } + selector.replaceChildren(); + const enabledServers = keyServers.filter(server => server.enabled); + if (!enabledServers.length) { + const option = document.createElement('option'); + option.value = ''; + option.textContent = 'No enabled servers'; + selector.append(option); + } else enabledServers.forEach(server => { + const option = document.createElement('option'); + option.value = server.id; + option.textContent = `${server.name} (${server.protocol.toUpperCase()})`; + option.selected = server.id === selectedId; + selector.append(option); + }); + if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0; + selector.onchange = updatePublishButtons; + list.replaceChildren(); + keyServers.forEach(server => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = server.name; + const details = document.createElement('small'); + details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`; + info.append(title, details); + const enabledLabel = document.createElement('label'); + enabledLabel.className = 'compose-line'; + const enabledText = document.createElement('span'); + enabledText.textContent = 'Use for lookup and publishing'; + const enabled = document.createElement('input'); + enabled.type = 'checkbox'; + enabled.checked = server.enabled; + enabled.setAttribute('aria-label', `${server.name} enabled`); + enabled.onchange = async () => { + enabled.disabled = true; + try { + await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked); + await renderKeyServers(); + status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`); + } catch (error) { + enabled.checked = server.enabled; + status(error.message || `Could not update ${server.name}.`); + } finally { enabled.disabled = false; } + }; + enabledLabel.append(enabledText, enabled); + row.append(info, enabledLabel); + if (!server.builtin) { + const remove = document.createElement('button'); + remove.className = 'discard'; + remove.textContent = 'Remove'; + remove.onclick = async () => { + try { + await window.daybreakMail.pgp.removeKeyServer(server.id); + await renderKeyServers(); + status('Custom key server removed.'); + } catch (error) { status(error.message || 'Could not remove the key server.'); } + }; + row.append(remove); + } + list.append(row); + }); + } + selectPgpKeyUi('#pgp-find-key').onclick = async () => { + const button = selectPgpKeyUi('#pgp-find-key'); + const results = selectPgpKeyUi('#pgp-found-keys'); + button.disabled = true; + results.textContent = 'Searching…'; + try { + const found = await window.daybreakMail.pgp.findKey({ + email: selectPgpKeyUi('#pgp-search-email').value + }); + results.replaceChildren(); + found.keys.forEach(key => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = key.emails.join(', ') || key.name || 'Public key'; + const meta = document.createElement('small'); + meta.textContent = `Found on ${key.sources.join(', ')} · not verified`; + const fingerprint = document.createElement('small'); + fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; + info.append(title, meta, fingerprint); + const add = document.createElement('button'); + add.className = 'discard'; + add.textContent = 'Add to contacts…'; + add.onclick = async () => { + add.disabled = true; + try { + const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' }); + if (result.canceled) return; + 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.'); + await renderContacts(); + row.remove(); + } catch (error) { status(error.message || 'Could not add the public key.'); } + finally { add.disabled = false; } + }; + row.append(info, add); + results.append(row); + }); + found.errors.forEach(error => { + const warning = document.createElement('small'); + 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.` : ''}`); + else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`); + else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`); + } catch (error) { + results.textContent = ''; + 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'); + button.disabled = true; + try { + const result = await window.daybreakMail.pgp.addKeyServer({ + name: selectPgpKeyUi('#pgp-server-name').value, + url: selectPgpKeyUi('#pgp-server-url').value, + protocol: selectPgpKeyUi('#pgp-server-protocol').value + }); + if (result.canceled) return; + selectPgpKeyUi('#pgp-server-name').value = ''; + selectPgpKeyUi('#pgp-server-url').value = ''; + await renderKeyServers(); + status('Custom key server added.'); + } 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 () => { + 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.'); }; if (!androidPgp) void renderKeyServers(); - void renderContacts(); - void render(); -} - + void renderContacts(); + void render(); +} + window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () { baseOpenPreferences(); - const fields = selectPgpKeyUi('#modal-root .compose-fields'); - if (!fields || !pgpAvailable()) return; - const button = document.createElement('button'); - button.type = 'button'; - button.className = 'discard'; - button.id = 'open-encryption-keys'; - button.textContent = 'Encryption keys…'; - button.onclick = openEncryptionKeys; - fields.append(button); + const fields = selectPgpKeyUi('#modal-root .compose-fields'); + if (!fields || !pgpAvailable()) return; + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'discard'; + button.id = 'open-encryption-keys'; + button.textContent = 'Encryption keys…'; + button.onclick = openEncryptionKeys; + fields.append(button); }); })(); diff --git a/platform-bridge.js b/platform-bridge.js index 2a2b271..49c4654 100644 --- a/platform-bridge.js +++ b/platform-bridge.js @@ -10240,20 +10240,30 @@ Add the new key as an unverified key? Compare fingerprints with the owner before async function unlock(fingerprint, passphrase) { const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint); if (!entry) throw new Error("That key was not found."); + 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 po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase }); } catch { throw new Error("The passphrase is incorrect."); } } + async function biometricPassphrase(fingerprint) { + if (typeof EpMail2.getPgpBiometricPassphrase !== "function") return null; + const result = await EpMail2.getPgpBiometricPassphrase({ fingerprint }); + return result?.enabled && typeof result.passphrase === "string" ? result.passphrase : null; + } async function signerFor(account, passphrase) { const data = await store(); const entry = data.keys.find((item) => item.email.toLowerCase() === String(account.email).toLowerCase()); if (!entry) throw Object.assign(new Error("Create or import an encryption key for this address first."), { code: "NO_SIGNING_KEY" }); - const secret = passphrase || cached(entry.fingerprint); + 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 }); try { - const key = await unlock(entry.fingerprint, secret); + const key = await unlockWithPassphrase(entry, secret); cache(entry.fingerprint, secret); return { key, entry }; } catch { @@ -10364,6 +10374,7 @@ ${body}`); selected = candidates.find((entry) => cached(entry.fingerprint)) || selected; 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." }; let privateKey; try { @@ -10536,6 +10547,23 @@ ${body}`); clear(fingerprint); return { removed: true }; }, + async enableBiometricUnlock({ fingerprint, passphrase }) { + if (typeof EpMail2.setPgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device."); + const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint); + if (!entry) throw new Error("That key was not found."); + if (!passphrase) throw new Error("Enter the key passphrase first."); + await unlockWithPassphrase(entry, passphrase); + return EpMail2.setPgpBiometricUnlock({ fingerprint, passphrase }); + }, + async biometricUnlockEnabled(fingerprint) { + if (typeof EpMail2.pgpBiometricUnlockEnabled !== "function") return false; + return Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled); + }, + async disableBiometricUnlock(fingerprint) { + if (typeof EpMail2.removePgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device."); + clear(fingerprint); + return EpMail2.removePgpBiometricUnlock({ fingerprint }); + }, async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); }, @@ -10575,10 +10603,20 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error const { keys, missing } = await resolveRecipients(addresses); const account = await getAccount(); const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null; + let biometricUnlockEnabled = false; + if (entry && typeof EpMail2.pgpBiometricUnlockEnabled === "function") { + biometricUnlockEnabled = Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled); + } 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, @@ -10637,6 +10675,8 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }), getAppLockSettings: () => EpMail.getAppLockSettings(), setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }), + setAppLockDelay: (seconds) => EpMail.setAppLockDelay({ seconds }), + deleteAllLocalData: () => EpMail.deleteAllLocalData(), getAccount: () => EpMail.getAccount(), listAccounts: () => EpMail.listAccounts(), selectAccount: (id) => EpMail.selectAccount({ id }), diff --git a/productivity.js b/productivity.js index 71b4049..63b41e0 100644 --- a/productivity.js +++ b/productivity.js @@ -6,58 +6,61 @@ const selectAllProductivityUi = productivityMailUi.selectAll; const toastProductivityUi = productivityMailUi.toast; const escapeProductivityUi = productivityMailUi.escapeHtml; const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' }; -const 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)); -let profileSettings = productRead(productKeys.profile, { name: '' }); -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); -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())); -productWrite(productKeys.contacts, savedContacts); -let savedEvents = productRead(productKeys.events, []); -let customLabels = productRead(productKeys.labels, []); -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 openAccountSettings() { - const root=selectProductivityUi('#modal-root'); - root.innerHTML=``; - const close=()=>root.innerHTML=''; - selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); - selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; - selectProductivityUi('#save-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(); -} +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)); +let profileSettings = productRead(productKeys.profile, { name: '' }); +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); +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())); +productWrite(productKeys.contacts, savedContacts); +let savedEvents = productRead(productKeys.events, []); +let customLabels = productRead(productKeys.labels, []); +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 openAccountSettings() { + const root=selectProductivityUi('#modal-root'); + root.innerHTML=``; + const close=()=>root.innerHTML=''; + selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); + selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + selectProductivityUi('#save-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(); +} async function openPreferences() { const root=selectProductivityUi('#modal-root'); const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; const options=themes.map(([value,label])=>``).join(''); 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 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(appLockBridge){try{appLockSettings=await appLockBridge.getAppLockSettings()}catch(error){toastProductivityUi(error.message||'Could not load app-lock settings');return}} const notificationSetting=notificationBridge?``:''; - const appLockSetting=appLockBridge?``:''; - root.innerHTML=``; - const close=()=>root.innerHTML=''; - selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); - selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; - selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge)await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked);productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}}; - selectProductivityUi('#theme-select').focus(); -} -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=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); } -function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}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=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;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=``;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()} -function renderContacts(){const cards=savedContacts.map((c,i)=>`
${escapeProductivityUi(c.initials)}
${escapeProductivityUi(c.name)}${escapeProductivityUi(c.email)}${escapeProductivityUi(c.note)}
`).join('');selectProductivityUi('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}} -function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} -function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})} -function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')} -function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()} -async function actOnSelected(action){const selected=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='';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()} + const appLockSetting=appLockBridge?``:''; + const localDataSetting=localDataBridge?`

Local data

`:''; + root.innerHTML=``; + const close=()=>root.innerHTML=''; + selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); + selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge){await appLockBridge.setAppLockDelay(Number(selectProductivityUi('#app-lock-delay').value));await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked)}productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}}; + if(localDataBridge)selectProductivityUi('#delete-all-local-data').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await localDataBridge.deleteAllLocalData();if(!result?.deleted){button.disabled=false;return}if('serviceWorker'in navigator){const registrations=await navigator.serviceWorker.getRegistrations();await Promise.all(registrations.map(registration=>registration.unregister()))}if('caches'in window){const names=await caches.keys();await Promise.all(names.map(name=>caches.delete(name)))}localStorage.clear();window.location.reload()}catch(error){button.disabled=false;toastProductivityUi(error.message||'Native data was deleted, but browser data cleanup did not finish. Restart ep-mail to complete cleanup.')}}; + selectProductivityUi('#theme-select').focus(); +} +function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); } +function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}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=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;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=``;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()} +function renderContacts(){const cards=savedContacts.map((c,i)=>`
${escapeProductivityUi(c.initials)}
${escapeProductivityUi(c.name)}${escapeProductivityUi(c.email)}${escapeProductivityUi(c.note)}
`).join('');selectProductivityUi('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}} +function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} +function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})} +function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')} +function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()} +async function actOnSelected(action){const selected=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='';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 () { const state = productivityMailUi.state; if (state.activeFolder === 'Drafts') { @@ -79,7 +82,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () { return; } return baseMessageRenderer(); -}); +}); document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}const decrypted=message?.attachments?.find(file=>file.filename===filename&&file.contentBase64);const saving=decrypted&&window.daybreakMail?.savePgpAttachment?window.daybreakMail.savePgpAttachment(decrypted):message?.uid&&window.daybreakMail?.saveAttachment?window.daybreakMail.saveAttachment({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,filename}):null;if(!saving){toastProductivityUi('Attachment download is available for connected mailbox messages');return}saving.then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true); window.epMailFeatures.productivity = Object.freeze({ diff --git a/scripts/android-bridge.js b/scripts/android-bridge.js index 66d7f80..7fe635c 100644 --- a/scripts/android-bridge.js +++ b/scripts/android-bridge.js @@ -1,15 +1,17 @@ -import { Capacitor, registerPlugin } from '@capacitor/core'; -import { createAndroidPgp } from './android-pgp.js'; +import { Capacitor, registerPlugin } from '@capacitor/core'; +import { createAndroidPgp } from './android-pgp.js'; const EpMail = registerPlugin('EpMail'); -if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { - const daybreakMail = { +if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { + const daybreakMail = { getAppVersion: () => EpMail.getAppVersion().then(result => result.version), - getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), - setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }), - getAppLockSettings: () => EpMail.getAppLockSettings(), - setAppLockEnabled: enabled => EpMail.setAppLockEnabled({ enabled }), + getNotificationPrivacy: () => EpMail.getNotificationPrivacy(), + setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }), + getAppLockSettings: () => EpMail.getAppLockSettings(), + setAppLockEnabled: enabled => EpMail.setAppLockEnabled({ enabled }), + setAppLockDelay: seconds => EpMail.setAppLockDelay({ seconds }), + deleteAllLocalData: () => EpMail.deleteAllLocalData(), getAccount: () => EpMail.getAccount(), listAccounts: () => EpMail.listAccounts(), selectAccount: id => EpMail.selectAccount({ id }), @@ -30,24 +32,24 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { previewAttachment: details => EpMail.previewAttachment(details), saveAttachment: details => EpMail.saveAttachment(details), openExternal: url => EpMail.openExternal({ url }), - send: async message => { - if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) { - if (message?.pgp?.plaintextFallback) { - const { pgp: _options, ...plainMessage } = message; - return EpMail.send({ ...plainMessage, pgpRequested: true }); - } - return EpMail.send(message); - } - try { - const { rawBase64, to, from } = await daybreakMail.pgp.buildOutgoing(message); - const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message; - return await EpMail.send({ ...headers, rawBase64, envelope: { from, to }, text: '', attachments: [] }); - } catch (error) { - return { failed: true, code: error.code || 'PGP_ERROR', message: error.message || 'Could not encrypt this message.' }; - } - }, - pgpGetMessageSource: details => EpMail.pgpGetMessageSource(details), - savePgpAttachment: details => EpMail.savePgpAttachment(details), + send: async message => { + if (!message?.pgp || (!message.pgp.encrypt && !message.pgp.sign)) { + if (message?.pgp?.plaintextFallback) { + const { pgp: _options, ...plainMessage } = message; + return EpMail.send({ ...plainMessage, pgpRequested: true }); + } + return EpMail.send(message); + } + try { + const { rawBase64, to, from } = await daybreakMail.pgp.buildOutgoing(message); + const { pgp: _options, text: _text, attachments: _attachments, ...headers } = message; + return await EpMail.send({ ...headers, rawBase64, envelope: { from, to }, text: '', attachments: [] }); + } catch (error) { + return { failed: true, code: error.code || 'PGP_ERROR', message: error.message || 'Could not encrypt this message.' }; + } + }, + pgpGetMessageSource: details => EpMail.pgpGetMessageSource(details), + savePgpAttachment: details => EpMail.savePgpAttachment(details), disconnect: id => EpMail.removeAccount({ id }), davList: () => EpMail.davList(), davConnect: config => EpMail.davConnect(config), @@ -57,8 +59,8 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') { davSaveEvent: event => EpMail.davSaveEvent(event), davDeleteEvent: remote => EpMail.davDeleteEvent(remote), davSaveContact: contact => EpMail.davSaveContact(contact), - davDeleteContact: remote => EpMail.davDeleteContact(remote) - }; - daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount() }); - window.daybreakMail = daybreakMail; -} + davDeleteContact: remote => EpMail.davDeleteContact(remote) + }; + daybreakMail.pgp = createAndroidPgp({ EpMail, getAccount: () => EpMail.getAccount() }); + window.daybreakMail = daybreakMail; +} diff --git a/scripts/android-pgp.js b/scripts/android-pgp.js index 2f3bfbd..a9908e6 100644 --- a/scripts/android-pgp.js +++ b/scripts/android-pgp.js @@ -335,16 +335,26 @@ export function createAndroidPgp({ EpMail, getAccount }) { async function unlock(fingerprint, passphrase) { const entry = (await store()).keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); + 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 }); } 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) { const data = await store(); const entry = data.keys.find(item => item.email.toLowerCase() === String(account.email).toLowerCase()); if (!entry) throw Object.assign(new Error('Create or import an encryption key for this address first.'), { code: 'NO_SIGNING_KEY' }); - const secret = passphrase || cached(entry.fingerprint); + 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 }); - 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 }); } } async function buildOutgoing(message) { @@ -425,6 +435,7 @@ export function createAndroidPgp({ EpMail, getAccount }) { selected = candidates.find(entry => cached(entry.fingerprint)) || selected; 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.' }; let privateKey; try { privateKey = await unlock(selected.fingerprint, secret); } @@ -529,6 +540,23 @@ export function createAndroidPgp({ EpMail, getAccount }) { 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 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 addContact(input = {}) { const armoredKey = input.armoredKey || prompt('Paste an ASCII-armored OpenPGP public key (up to 200 KB):') || ''; @@ -547,8 +575,13 @@ export function createAndroidPgp({ EpMail, getAccount }) { const { keys, missing } = await resolveRecipients(addresses); const account = await getAccount(); const entry = sign ? (await store()).keys.find(item => item.email.toLowerCase() === String(account?.email || '').toLowerCase()) : null; + 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, - 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, verifyMessage, diff --git a/tests/android-pgp.test.cjs b/tests/android-pgp.test.cjs index 2657d79..d771012 100644 --- a/tests/android-pgp.test.cjs +++ b/tests/android-pgp.test.cjs @@ -30,6 +30,7 @@ function makeEndpoint(account) { }; return { api: createAndroidPgp({ EpMail, getAccount: async () => account }), + EpMail, setMessage(value) { messageSource = value; }, vault }; @@ -167,3 +168,54 @@ test('Android rejects tampered, malformed, and oversized encrypted input', async 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); +}); diff --git a/tests/android-ui-support.test.cjs b/tests/android-ui-support.test.cjs index 7b64b7a..b9a787f 100644 --- a/tests/android-ui-support.test.cjs +++ b/tests/android-ui-support.test.cjs @@ -20,6 +20,11 @@ const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8'); const 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 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', () => { assert.match(styles, /min-width:320px/); @@ -79,7 +84,64 @@ test('Android app lock is native-enforced and requires a secure device credentia assert.match(mainActivity, /setJavaScriptEnabled\(false\)/); assert.match(androidBridge, /getAppLockSettings/); assert.match(androidBridge, /setAppLockEnabled/); + assert.match(androidBridge, /setAppLockDelay/); assert.match(productivity, /Lock when leaving ep-mail/); + assert.match(productivity, /app-lock-delay/); + assert.match(mainActivity, /postDelayed\(delayedAppLock/); + assert.match(mainActivity, /FLAG_SECURE/); +}); + +test('Android biometric PGP unlock keeps secrets behind an authentication-bound Keystore key', () => { + assert.match(plugin, /fun setPgpBiometricUnlock/); + assert.match(plugin, /fun getPgpBiometricPassphrase/); + assert.match(plugin, /fun removePgpBiometricUnlock/); + assert.match(plugin, /fun pgpBiometricUnlockEnabled/); + assert.match(mainActivity, /authenticatePgpCipher/); + assert.match(mainActivity, /pgpAuthInProgress/); + assert.match(biometricUnlock, /setUserAuthenticationRequired\(true\)/); + assert.match(biometricUnlock, /setUserAuthenticationParameters/); + assert.match(vault, /pgpBiometricUnlocks/); + assert.match(vault, /removedFingerprints\.forEach/); + assert.match(androidPgp, /enableBiometricUnlock/); + assert.match(androidPgp, /getPgpBiometricPassphrase/); + assert.match(pgpMailUi, /BIOMETRIC_INVALIDATED/); +}); + +test('Android full local-data deletion is explicit, scoped, and clears stored web data', () => { + assert.match(productivity, /Delete all local data/); + assert.match(androidBridge, /deleteAllLocalData/); + assert.match(plugin, /fun deleteAllLocalData/); + assert.match(plugin, /setPositiveButton\("Delete all data"\)/); + assert.match(vault, /fun wipe\(\)/); + assert.match(androidMailService, /fun deleteSavedAttachments/); + assert.match(androidMailService, /isAppOwnedDownload/); + assert.match(androidMailService, /BoundedInputReader\.read\(it, 5 \* 1048576 \+ 1\)/); + assert.match(androidMailService, /BoundedInputReader\.read\(it, 100001\)/); + assert.match(androidMailService, /saveAttachmentStream/); + assert.match(boundedInputReader, /while \(output\.size\(\) < maxBytes\)/); + assert.match(mainActivity, /clearLocalWebData/); + assert.match(productivity, /getRegistrations\(\)/); + assert.match(productivity, /caches\.delete\(name\)/); +}); + +test('Android WebView CSP, manifest, navigation, and DAV transport stay constrained', () => { + const csp = /http-equiv="Content-Security-Policy" content="([^"]+)"/i.exec(index)?.[1] || ''; + assert.match(csp, /default-src 'self'/); + assert.match(csp, /script-src 'self'/); + assert.match(csp, /connect-src 'none'/); + assert.match(csp, /frame-src 'none'/); + assert.match(csp, /object-src 'none'/); + assert.match(csp, /base-uri 'none'/); + assert.match(csp, /form-action 'none'/); + assert.doesNotMatch(csp, /script-src[^;]*unsafe-inline/i); + assert.match(manifest, /android:allowBackup="false"/); + assert.match(manifest, /android:usesCleartextTraffic="false"/); + assert.doesNotMatch(manifest, /READ_EXTERNAL_STORAGE|WRITE_EXTERNAL_STORAGE|MANAGE_EXTERNAL_STORAGE|REQUEST_INSTALL_PACKAGES/); + assert.match(plugin, /Only standard web links can be opened from mail/); + assert.match(plugin, /uri\.scheme\?\.lowercase\(Locale\.ROOT\) !in setOf\("http", "https"\)/); + assert.match(davService, /followRedirects\(false\)/); + assert.match(davService, /followSslRedirects\(false\)/); + assert.match(davService, /DavUrlPolicy\.requireSameOrigin/); }); test('Android OpenPGP uses the encrypted vault and queues only built MIME data', () => { diff --git a/www/pgp-mail-ui.js b/www/pgp-mail-ui.js index 1c3a004..3c3165e 100644 --- a/www/pgp-mail-ui.js +++ b/www/pgp-mail-ui.js @@ -6,70 +6,70 @@ const selectAllPgpMailUi = pgpMailUi.selectAll; const toastPgpMailUi = pgpMailUi.toast; const escapePgpMailUi = pgpMailUi.escapeHtml; const pgpApi = () => window.daybreakMail?.pgp; - -function pgpAskPassphrase(title, detail) { - return new Promise(resolve => { - const overlay = document.createElement('div'); - overlay.className = 'modal-overlay pgp-prompt'; - overlay.innerHTML = `
`; - overlay.querySelector('.modal-head span').textContent = title; - overlay.querySelector('.account-note').textContent = detail; - const finish = value => { overlay.remove(); resolve(value); }; - overlay.querySelector('form').onsubmit = event => { - event.preventDefault(); - const value = overlay.querySelector('input').value; - if (value) finish(value); - }; - overlay.querySelector('[data-cancel]').onclick = () => finish(null); - overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } }); - document.body.append(overlay); - overlay.querySelector('input').focus(); - }); -} - -function pgpFormatFingerprint(value) { - return String(value || '').match(/.{1,4}/g)?.join(' ') || ''; -} - -function pgpSignatureHtml(signatures, encrypted) { - const items = Array.isArray(signatures) ? signatures : []; - const lock = encrypted ? '🔒 Encrypted. ' : ''; - if (!items.length) { - return encrypted ? `
${lock}Not signedThe sender is not authenticated: anyone with your public key could have written this.
` : ''; - } - return items.map(signature => { - const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet'; - 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.mismatch) notes.push('The signing key does not belong to the sender address.'); - if (signature.status === 'valid') { - const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok'; + +function pgpAskPassphrase(title, detail) { + return new Promise(resolve => { + const overlay = document.createElement('div'); + overlay.className = 'modal-overlay pgp-prompt'; + overlay.innerHTML = `
`; + overlay.querySelector('.modal-head span').textContent = title; + overlay.querySelector('.account-note').textContent = detail; + const finish = value => { overlay.remove(); resolve(value); }; + overlay.querySelector('form').onsubmit = event => { + event.preventDefault(); + const value = overlay.querySelector('input').value; + if (value) finish(value); + }; + overlay.querySelector('[data-cancel]').onclick = () => finish(null); + overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } }); + document.body.append(overlay); + overlay.querySelector('input').focus(); + }); +} + +function pgpFormatFingerprint(value) { + return String(value || '').match(/.{1,4}/g)?.join(' ') || ''; +} + +function pgpSignatureHtml(signatures, encrypted) { + const items = Array.isArray(signatures) ? signatures : []; + const lock = encrypted ? '🔒 Encrypted. ' : ''; + if (!items.length) { + return encrypted ? `
${lock}Not signedThe sender is not authenticated: anyone with your public key could have written this.
` : ''; + } + return items.map(signature => { + const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet'; + 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.mismatch) notes.push('The signing key does not belong to the sender address.'); + if (signature.status === 'valid') { + const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok'; return `
${lock}Valid signature from ${escapePgpMailUi(signature.email || 'a known key')}${escapePgpMailUi(trust)} · ${escapePgpMailUi(pgpFormatFingerprint(signature.fingerprint))}${notes.map(note => `${escapePgpMailUi(note)}`).join('')}
`; - } - if (signature.status === 'unknown-key') { + } + if (signature.status === 'unknown-key') { return `
${lock}Signed with an unknown keyKey ID ${escapePgpMailUi(signature.keyId)} is not in your contacts, so the signature cannot be checked.${notes.map(note => `${escapePgpMailUi(note)}`).join('')}
`; - } - return ``; - }).join(''); -} - -async function pgpAddAttachedKey(key) { - 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; - try { - 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'); - } catch (error) { - toastPgpMailUi(error.message || 'Could not add the key'); - } -} - -function pgpRenderReaderState(message) { - const reader = selectPgpMailUi('#reader-pane'); - const header = reader.querySelector('.reader-header'); - if (!header) return; - reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); - let html = ''; + } + return ``; + }).join(''); +} + +async function pgpAddAttachedKey(key) { + 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; + try { + 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'); + } catch (error) { + toastPgpMailUi(error.message || 'Could not add the key'); + } +} + +function pgpRenderReaderState(message) { + const reader = selectPgpMailUi('#reader-pane'); + const header = reader.querySelector('.reader-header'); + if (!header) return; + reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); + let html = ''; if (message.encrypted && !message.pgpDecrypted) { html = `
🔒 This message is encryptedUnlock it with your key passphrase to read it.
`; } else if (message.encrypted) { @@ -82,44 +82,49 @@ function pgpRenderReaderState(message) { html = '
Checking OpenPGP signature…Do not rely on this message until verification completes.
'; } else if (message.pgpSignatures) { html = pgpSignatureHtml(message.pgpSignatures, false); - } - const keys = message.pgpResult?.attachedKeys || []; + } + const keys = message.pgpResult?.attachedKeys || []; header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `
Public key attached${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}
`).join('')); - reader.querySelectorAll('[data-pgp-key]').forEach(button => { - button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]); - }); - const unlock = selectPgpMailUi('#pgp-unlock'); - if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); -} - + reader.querySelectorAll('[data-pgp-key]').forEach(button => { + button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]); + }); + const unlock = selectPgpMailUi('#pgp-unlock'); + if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); +} + async function pgpUnlockMessage(message, interactive) { - let passphrase = null; - for (let attempt = 0; attempt < 3; attempt += 1) { - let result; - try { - result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase }); - } catch (error) { - toastPgpMailUi(error.message || 'Could not open this message'); - return; - } - if (result.ok) { - Object.assign(message, { - 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 } - }); + let passphrase = null; + for (let attempt = 0; attempt < 3; attempt += 1) { + let result; + try { + result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase }); + } catch (error) { + toastPgpMailUi(error.message || 'Could not open this message'); + return; + } + if (result.ok) { + Object.assign(message, { + 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 } + }); if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id); - return; - } - if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') { - 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'}.`); - if (passphrase === null) return; - continue; - } - const text = selectPgpMailUi('#pgp-banner-text'); - if (text) text.textContent = result.message; - else toastPgpMailUi(result.message); - return; + return; + } + if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') { + if (!interactive) { pgpRenderReaderState(message); return; } + const prompt = result.code === 'BAD_PASSPHRASE' + ? 'That passphrase was incorrect. Try again.' + : result.code === 'BIOMETRIC_INVALIDATED' + ? `${result.message} Enter the passphrase to continue.` + : `Enter the passphrase for ${result.email || 'your key'}.`; + passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt); + if (passphrase === null) return; + continue; + } + const text = selectPgpMailUi('#pgp-banner-text'); + if (text) text.textContent = result.message; + else toastPgpMailUi(result.message); + return; } } @@ -141,7 +146,7 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { baseOpenMessage(id); const message = pgpMailUi.state.messages.find(item => item.id === id); if (!message || !pgpApi()) return; - pgpRenderReaderState(message); + pgpRenderReaderState(message); if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { message.pgpAutoTried = true; void pgpUnlockMessage(message, false); @@ -154,40 +159,40 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { // Compose: encrypt/sign options. pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) { - baseShowCompose(reply, forward); - const footer = selectPgpMailUi('#modal-root .compose-footer'); - if (!footer || !pgpApi()) return; - const box = document.createElement('div'); - box.className = 'pgp-compose'; + baseShowCompose(reply, forward); + const footer = selectPgpMailUi('#modal-root .compose-footer'); + if (!footer || !pgpApi()) return; + const box = document.createElement('div'); + box.className = 'pgp-compose'; box.innerHTML = `${pgpApi().platform === 'android' ? '' : ''}`; - footer.prepend(box); - let touched = false; - const encrypt = selectPgpMailUi('#pgp-encrypt'); - const sign = selectPgpMailUi('#pgp-sign'); - if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } - if (touched) encrypt.dataset.touched = '1'; - encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; }); - let timer = null; - const refresh = async () => { - const to = selectPgpMailUi('#compose-to')?.value || ''; - const cc = selectPgpMailUi('#compose-cc')?.value || ''; - const hint = selectPgpMailUi('#pgp-hint'); - if (!hint) return; - if (!to.trim()) { hint.textContent = ''; return; } - try { - const status = await pgpApi().checkSend({ to, cc, sign: sign.checked }); - if (!selectPgpMailUi('#pgp-hint')) return; - if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`; - else { - hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients'; - if (!touched && !encrypt.checked) encrypt.checked = true; - } - } catch { hint.textContent = ''; } - }; - const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); }; - ['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule)); - sign.addEventListener('change', schedule); - schedule(); + footer.prepend(box); + let touched = false; + const encrypt = selectPgpMailUi('#pgp-encrypt'); + const sign = selectPgpMailUi('#pgp-sign'); + if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } + if (touched) encrypt.dataset.touched = '1'; + encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; }); + let timer = null; + const refresh = async () => { + const to = selectPgpMailUi('#compose-to')?.value || ''; + const cc = selectPgpMailUi('#compose-cc')?.value || ''; + const hint = selectPgpMailUi('#pgp-hint'); + if (!hint) return; + if (!to.trim()) { hint.textContent = ''; return; } + try { + const status = await pgpApi().checkSend({ to, cc, sign: sign.checked }); + if (!selectPgpMailUi('#pgp-hint')) return; + if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`; + else { + hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients'; + if (!touched && !encrypt.checked) encrypt.checked = true; + } + } catch { hint.textContent = ''; } + }; + const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); }; + ['#compose-to', '#compose-cc'].forEach(selector => selectPgpMailUi(selector)?.addEventListener('input', schedule)); + sign.addEventListener('change', schedule); + schedule(); }); // Called by the send handler. Returns null (plain mail), false (cancelled) or send options. @@ -196,30 +201,30 @@ async function prepareSend(to, cc) { const plaintextFallback = () => pgpApi().platform === 'android' ? { encrypt: false, sign: false, plaintextFallback: true } : null; - let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked); - const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked); - if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null; - 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. - if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') { + let encrypt = Boolean(selectPgpMailUi('#pgp-encrypt')?.checked); + const sign = Boolean(selectPgpMailUi('#pgp-sign')?.checked); + if (!encrypt && !sign && selectPgpMailUi('#pgp-encrypt')?.dataset.touched === '1') return null; + const status = await pgpApi().checkSend({ to, cc, sign }); + // The default-on update is debounced, so a quick send could skip encryption even though keys exist. + if (!encrypt && !status.missing.length && status.recipients.length && selectPgpMailUi('#pgp-encrypt')?.dataset.touched !== '1') { if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) { if (!sign) return plaintextFallback(); - } else return false; - } - if (!encrypt && !sign) return null; - 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?`); + } else return false; + } + if (!encrypt && !sign) return null; + 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?`); if (!sendPlain) return false; encrypt = false; if (!sign) return plaintextFallback(); - } - let passphrase = null; - if (sign) { - if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; } - if (!status.signer.unlocked) { - passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`); - if (passphrase === null) return false; - } + } + let passphrase = null; + if (sign) { + if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; } + if (!status.signer.unlocked && !status.signer.biometricUnlockEnabled) { + passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`); + if (passphrase === null) return false; + } } return { encrypt, sign, passphrase }; } diff --git a/www/pgp-ui.js b/www/pgp-ui.js index 22f4bf4..3ee0a48 100644 --- a/www/pgp-ui.js +++ b/www/pgp-ui.js @@ -14,8 +14,8 @@ async function saveAndroidPgpExport(label, value) { else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true }; return { saved: true }; } - -function openEncryptionKeys() { + +function openEncryptionKeys() { const root = selectPgpKeyUi('#modal-root'); const account = window.epMailFeatures.mail.connectedAccount || {}; const androidPgp = window.daybreakMail?.pgp?.platform === 'android'; @@ -35,401 +35,437 @@ function openEncryptionKeys() {
`; root.innerHTML = ``; - const close = () => { root.innerHTML = ''; }; - root.querySelector('.modal-close').onclick = close; - root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; - const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; }; - const passphraseField = () => selectPgpKeyUi('#pgp-passphrase'); - let keyServers = []; - const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled); - const updatePublishButtons = () => { - const server = selectedPublishServer(); - selectAllPgpKeyUi('.pgp-publish').forEach(button => { - button.disabled = !server; - button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…'; - }); - }; - const needPassphrase = () => { - const value = passphraseField().value; - if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); } - return value; - }; - - async function render() { - const list = selectPgpKeyUi('#pgp-key-list'); - let keys = []; - try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; } - list.replaceChildren(); - if (!keys.length) { list.textContent = 'No keys yet.'; return; } - keys.forEach(key => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = key.email || 'OpenPGP key'; - const meta = document.createElement('small'); - meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`; - const fingerprint = document.createElement('small'); - fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; - info.append(title, meta, fingerprint); - row.append(info); - const actions = [ - ['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false], - ['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true] - ]; - const changePassphrase = document.createElement('button'); - changePassphrase.className = 'discard'; - changePassphrase.textContent = 'Change passphrase…'; - changePassphrase.onclick = async () => { - const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value; - if (!currentPassphrase) { - status('Enter the current passphrase for this key.'); - selectPgpKeyUi('#pgp-change-current-passphrase').focus(); - return; - } - const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value; - if (newPassphrase.length < 8) { - status('Use a new passphrase of at least 8 characters.'); - selectPgpKeyUi('#pgp-new-passphrase').focus(); - return; - } - if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) { - status('The new passphrases do not match.'); - selectPgpKeyUi('#pgp-confirm-passphrase').focus(); - return; - } - changePassphrase.disabled = true; - try { - await window.daybreakMail.pgp.changePassphrase({ - fingerprint: key.fingerprint, - currentPassphrase, - newPassphrase - }); - selectPgpKeyUi('#pgp-change-current-passphrase').value = ''; - status(`Passphrase changed for ${key.email || key.fingerprint}.`); - } catch (error) { status(error.message || 'Could not change the key passphrase.'); } - finally { - selectPgpKeyUi('#pgp-new-passphrase').value = ''; - selectPgpKeyUi('#pgp-confirm-passphrase').value = ''; - changePassphrase.disabled = false; - } - }; - row.append(changePassphrase); - 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 { +

Passphrase memory

+ +
+ +

Create a key

+ + + +
+ + `; + const close = () => { root.innerHTML = ''; }; + root.querySelector('.modal-close').onclick = close; + root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; + const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; }; + const passphraseField = () => selectPgpKeyUi('#pgp-passphrase'); + let keyServers = []; + const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled); + const updatePublishButtons = () => { + const server = selectedPublishServer(); + selectAllPgpKeyUi('.pgp-publish').forEach(button => { + button.disabled = !server; + button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…'; + }); + }; + const needPassphrase = () => { + const value = passphraseField().value; + if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); } + return value; + }; + + async function render() { + const list = selectPgpKeyUi('#pgp-key-list'); + let keys = []; + try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; } + list.replaceChildren(); + if (!keys.length) { list.textContent = 'No keys yet.'; return; } + keys.forEach(key => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = key.email || 'OpenPGP key'; + const meta = document.createElement('small'); + meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`; + const fingerprint = document.createElement('small'); + fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; + info.append(title, meta, fingerprint); + row.append(info); + const actions = [ + ['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false], + ['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true] + ]; + const changePassphrase = document.createElement('button'); + changePassphrase.className = 'discard'; + changePassphrase.textContent = 'Change passphrase…'; + changePassphrase.onclick = async () => { + const currentPassphrase = selectPgpKeyUi('#pgp-change-current-passphrase').value; + if (!currentPassphrase) { + status('Enter the current passphrase for this key.'); + selectPgpKeyUi('#pgp-change-current-passphrase').focus(); + return; + } + const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value; + if (newPassphrase.length < 8) { + status('Use a new passphrase of at least 8 characters.'); + selectPgpKeyUi('#pgp-new-passphrase').focus(); + return; + } + if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) { + status('The new passphrases do not match.'); + selectPgpKeyUi('#pgp-confirm-passphrase').focus(); + return; + } + changePassphrase.disabled = true; + try { + await window.daybreakMail.pgp.changePassphrase({ + fingerprint: key.fingerprint, + currentPassphrase, + newPassphrase + }); + selectPgpKeyUi('#pgp-change-current-passphrase').value = ''; + status(`Passphrase changed for ${key.email || key.fingerprint}.`); + } catch (error) { status(error.message || 'Could not change the key passphrase.'); } + finally { + selectPgpKeyUi('#pgp-new-passphrase').value = ''; + selectPgpKeyUi('#pgp-confirm-passphrase').value = ''; + changePassphrase.disabled = false; + } + }; + row.append(changePassphrase); + if (androidPgp) { + const biometric = document.createElement('button'); + biometric.className = 'discard'; + biometric.textContent = 'Checking biometric unlock…'; + biometric.disabled = true; + row.append(biometric); + window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => { + if (!biometric.isConnected) return; + biometric.dataset.enabled = String(enabled); + biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…'; + biometric.disabled = false; + }).catch(error => { + if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.'); + }); + biometric.onclick = async () => { + biometric.disabled = true; + try { + if (biometric.dataset.enabled === 'true') { + if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return; + await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint); + status('Biometric unlock disabled.'); + } else { + const passphrase = needPassphrase(); + if (!passphrase) return; + await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase }); + passphraseField().value = ''; + status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.'); + } + await render(); + } catch (error) { + status(error.message || 'Could not update biometric key unlock.'); + } finally { + biometric.disabled = false; + } + }; + } + if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]); + actions.push(['Delete', async () => { + if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true }; + 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()); - status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : ''); - } catch (error) { status(error.message || 'That action failed.'); } - }; - row.append(button); - }); - const publish = document.createElement('button'); - publish.className = 'discard pgp-publish'; - publish.onclick = async () => { - const server = selectedPublishServer(); - if (!server) { status('Enable a key server and select it as the publication target first.'); return; } - publish.disabled = true; - try { - const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id }); - if (result.canceled) return; - 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 === '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 === '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()); - } catch (error) { status(error.message || 'Could not publish the public key.'); } - finally { updatePublishButtons(); } - }; - row.append(publish); - list.append(row); - }); - updatePublishButtons(); - } - - selectPgpKeyUi('#pgp-generate').onclick = async () => { - const button = selectPgpKeyUi('#pgp-generate'); - button.disabled = true; - status('Creating key…'); - try { - await window.daybreakMail.pgp.generate({ - 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.'); - await render(); - } catch (error) { status(error.message || 'Could not create the key.'); } - button.disabled = false; - }; - selectPgpKeyUi('#pgp-import').onclick = async () => { - const passphrase = needPassphrase(); - if (!passphrase) return; - try { - const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null }); + status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : ''); + } catch (error) { status(error.message || 'That action failed.'); } + }; + row.append(button); + }); + const publish = document.createElement('button'); + publish.className = 'discard pgp-publish'; + publish.onclick = async () => { + const server = selectedPublishServer(); + if (!server) { status('Enable a key server and select it as the publication target first.'); return; } + publish.disabled = true; + try { + const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id }); + if (result.canceled) return; + 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 === '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 === '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()); + } catch (error) { status(error.message || 'Could not publish the public key.'); } + finally { updatePublishButtons(); } + }; + row.append(publish); + list.append(row); + }); + updatePublishButtons(); + } + + selectPgpKeyUi('#pgp-generate').onclick = async () => { + const button = selectPgpKeyUi('#pgp-generate'); + button.disabled = true; + status('Creating key…'); + try { + await window.daybreakMail.pgp.generate({ + 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.'); + await render(); + } catch (error) { status(error.message || 'Could not create the key.'); } + button.disabled = false; + }; + selectPgpKeyUi('#pgp-import').onclick = async () => { + const passphrase = needPassphrase(); + if (!passphrase) return; + try { + const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null }); 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(); - } catch (error) { status(error.message || 'Could not import the key.'); } - }; - async function renderContacts() { - const list = selectPgpKeyUi('#pgp-contact-list'); - let contacts = []; - try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; } - list.replaceChildren(); - if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; } - contacts.forEach(contact => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = contact.emails.join(', ') || contact.name || 'Public key'; - const meta = document.createElement('small'); - meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`; - const fingerprint = document.createElement('small'); - fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`; - info.append(title, meta, fingerprint); - const trust = document.createElement('select'); - trust.className = 'pgp-trust'; - trust.setAttribute('aria-label', 'Key trust'); - [['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => { - const option = document.createElement('option'); - option.value = value; option.textContent = label; option.selected = contact.trust === value; - trust.append(option); - }); - trust.onchange = async () => { - 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; - return; - } - try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); } - catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); } - }; - const actions = [ - ['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)], - ['Remove', async () => { - if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: 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'); - button.className = 'discard'; - button.textContent = label; - button.onclick = async () => { + await render(); + } catch (error) { status(error.message || 'Could not import the key.'); } + }; + async function renderContacts() { + const list = selectPgpKeyUi('#pgp-contact-list'); + let contacts = []; + try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; } + list.replaceChildren(); + if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; } + contacts.forEach(contact => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = contact.emails.join(', ') || contact.name || 'Public key'; + const meta = document.createElement('small'); + meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`; + const fingerprint = document.createElement('small'); + fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`; + info.append(title, meta, fingerprint); + const trust = document.createElement('select'); + trust.className = 'pgp-trust'; + trust.setAttribute('aria-label', 'Key trust'); + [['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => { + const option = document.createElement('option'); + option.value = value; option.textContent = label; option.selected = contact.trust === value; + trust.append(option); + }); + trust.onchange = async () => { + 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; + return; + } + try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); } + catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); } + }; + const actions = [ + ['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)], + ['Remove', async () => { + if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: 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'); + 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.' : ''); } - catch (error) { status(error.message || 'That action failed.'); } - }; - row.append(button); - }); - list.append(row); - }); - } - - selectPgpKeyUi('#pgp-add-contact').onclick = async () => { - try { - 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.'); - await renderContacts(); - } catch (error) { status(error.message || 'Could not import the key.'); } - }; - async function renderKeyServers() { - const list = selectPgpKeyUi('#pgp-server-list'); - const selector = selectPgpKeyUi('#pgp-publish-server'); - const selectedId = selector.value; - try { keyServers = await window.daybreakMail.pgp.keyServers(); } - catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; } - selector.replaceChildren(); - const enabledServers = keyServers.filter(server => server.enabled); - if (!enabledServers.length) { - const option = document.createElement('option'); - option.value = ''; - option.textContent = 'No enabled servers'; - selector.append(option); - } else enabledServers.forEach(server => { - const option = document.createElement('option'); - option.value = server.id; - option.textContent = `${server.name} (${server.protocol.toUpperCase()})`; - option.selected = server.id === selectedId; - selector.append(option); - }); - if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0; - selector.onchange = updatePublishButtons; - list.replaceChildren(); - keyServers.forEach(server => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = server.name; - const details = document.createElement('small'); - details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`; - info.append(title, details); - const enabledLabel = document.createElement('label'); - enabledLabel.className = 'compose-line'; - const enabledText = document.createElement('span'); - enabledText.textContent = 'Use for lookup and publishing'; - const enabled = document.createElement('input'); - enabled.type = 'checkbox'; - enabled.checked = server.enabled; - enabled.setAttribute('aria-label', `${server.name} enabled`); - enabled.onchange = async () => { - enabled.disabled = true; - try { - await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked); - await renderKeyServers(); - status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`); - } catch (error) { - enabled.checked = server.enabled; - status(error.message || `Could not update ${server.name}.`); - } finally { enabled.disabled = false; } - }; - enabledLabel.append(enabledText, enabled); - row.append(info, enabledLabel); - if (!server.builtin) { - const remove = document.createElement('button'); - remove.className = 'discard'; - remove.textContent = 'Remove'; - remove.onclick = async () => { - try { - await window.daybreakMail.pgp.removeKeyServer(server.id); - await renderKeyServers(); - status('Custom key server removed.'); - } catch (error) { status(error.message || 'Could not remove the key server.'); } - }; - row.append(remove); - } - list.append(row); - }); - } - selectPgpKeyUi('#pgp-find-key').onclick = async () => { - const button = selectPgpKeyUi('#pgp-find-key'); - const results = selectPgpKeyUi('#pgp-found-keys'); - button.disabled = true; - results.textContent = 'Searching…'; - try { - const found = await window.daybreakMail.pgp.findKey({ - email: selectPgpKeyUi('#pgp-search-email').value - }); - results.replaceChildren(); - found.keys.forEach(key => { - const row = document.createElement('div'); - row.className = 'attachment-row'; - const info = document.createElement('div'); - info.className = 'attachment-row-info'; - const title = document.createElement('strong'); - title.textContent = key.emails.join(', ') || key.name || 'Public key'; - const meta = document.createElement('small'); - meta.textContent = `Found on ${key.sources.join(', ')} · not verified`; - const fingerprint = document.createElement('small'); - fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; - info.append(title, meta, fingerprint); - const add = document.createElement('button'); - add.className = 'discard'; - add.textContent = 'Add to contacts…'; - add.onclick = async () => { - add.disabled = true; - try { - const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' }); - if (result.canceled) return; - 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.'); - await renderContacts(); - row.remove(); - } catch (error) { status(error.message || 'Could not add the public key.'); } - finally { add.disabled = false; } - }; - row.append(info, add); - results.append(row); - }); - found.errors.forEach(error => { - const warning = document.createElement('small'); - 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.` : ''}`); - else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`); - else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`); - } catch (error) { - results.textContent = ''; - 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'); - button.disabled = true; - try { - const result = await window.daybreakMail.pgp.addKeyServer({ - name: selectPgpKeyUi('#pgp-server-name').value, - url: selectPgpKeyUi('#pgp-server-url').value, - protocol: selectPgpKeyUi('#pgp-server-protocol').value - }); - if (result.canceled) return; - selectPgpKeyUi('#pgp-server-name').value = ''; - selectPgpKeyUi('#pgp-server-url').value = ''; - await renderKeyServers(); - status('Custom key server added.'); - } 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 () => { - 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.'); }; + catch (error) { status(error.message || 'That action failed.'); } + }; + row.append(button); + }); + list.append(row); + }); + } + + selectPgpKeyUi('#pgp-add-contact').onclick = async () => { + try { + 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.'); + await renderContacts(); + } catch (error) { status(error.message || 'Could not import the key.'); } + }; + async function renderKeyServers() { + const list = selectPgpKeyUi('#pgp-server-list'); + const selector = selectPgpKeyUi('#pgp-publish-server'); + const selectedId = selector.value; + try { keyServers = await window.daybreakMail.pgp.keyServers(); } + catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; } + selector.replaceChildren(); + const enabledServers = keyServers.filter(server => server.enabled); + if (!enabledServers.length) { + const option = document.createElement('option'); + option.value = ''; + option.textContent = 'No enabled servers'; + selector.append(option); + } else enabledServers.forEach(server => { + const option = document.createElement('option'); + option.value = server.id; + option.textContent = `${server.name} (${server.protocol.toUpperCase()})`; + option.selected = server.id === selectedId; + selector.append(option); + }); + if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0; + selector.onchange = updatePublishButtons; + list.replaceChildren(); + keyServers.forEach(server => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = server.name; + const details = document.createElement('small'); + details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`; + info.append(title, details); + const enabledLabel = document.createElement('label'); + enabledLabel.className = 'compose-line'; + const enabledText = document.createElement('span'); + enabledText.textContent = 'Use for lookup and publishing'; + const enabled = document.createElement('input'); + enabled.type = 'checkbox'; + enabled.checked = server.enabled; + enabled.setAttribute('aria-label', `${server.name} enabled`); + enabled.onchange = async () => { + enabled.disabled = true; + try { + await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked); + await renderKeyServers(); + status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`); + } catch (error) { + enabled.checked = server.enabled; + status(error.message || `Could not update ${server.name}.`); + } finally { enabled.disabled = false; } + }; + enabledLabel.append(enabledText, enabled); + row.append(info, enabledLabel); + if (!server.builtin) { + const remove = document.createElement('button'); + remove.className = 'discard'; + remove.textContent = 'Remove'; + remove.onclick = async () => { + try { + await window.daybreakMail.pgp.removeKeyServer(server.id); + await renderKeyServers(); + status('Custom key server removed.'); + } catch (error) { status(error.message || 'Could not remove the key server.'); } + }; + row.append(remove); + } + list.append(row); + }); + } + selectPgpKeyUi('#pgp-find-key').onclick = async () => { + const button = selectPgpKeyUi('#pgp-find-key'); + const results = selectPgpKeyUi('#pgp-found-keys'); + button.disabled = true; + results.textContent = 'Searching…'; + try { + const found = await window.daybreakMail.pgp.findKey({ + email: selectPgpKeyUi('#pgp-search-email').value + }); + results.replaceChildren(); + found.keys.forEach(key => { + const row = document.createElement('div'); + row.className = 'attachment-row'; + const info = document.createElement('div'); + info.className = 'attachment-row-info'; + const title = document.createElement('strong'); + title.textContent = key.emails.join(', ') || key.name || 'Public key'; + const meta = document.createElement('small'); + meta.textContent = `Found on ${key.sources.join(', ')} · not verified`; + const fingerprint = document.createElement('small'); + fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; + info.append(title, meta, fingerprint); + const add = document.createElement('button'); + add.className = 'discard'; + add.textContent = 'Add to contacts…'; + add.onclick = async () => { + add.disabled = true; + try { + const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' }); + if (result.canceled) return; + 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.'); + await renderContacts(); + row.remove(); + } catch (error) { status(error.message || 'Could not add the public key.'); } + finally { add.disabled = false; } + }; + row.append(info, add); + results.append(row); + }); + found.errors.forEach(error => { + const warning = document.createElement('small'); + 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.` : ''}`); + else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`); + else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`); + } catch (error) { + results.textContent = ''; + 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'); + button.disabled = true; + try { + const result = await window.daybreakMail.pgp.addKeyServer({ + name: selectPgpKeyUi('#pgp-server-name').value, + url: selectPgpKeyUi('#pgp-server-url').value, + protocol: selectPgpKeyUi('#pgp-server-protocol').value + }); + if (result.canceled) return; + selectPgpKeyUi('#pgp-server-name').value = ''; + selectPgpKeyUi('#pgp-server-url').value = ''; + await renderKeyServers(); + status('Custom key server added.'); + } 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 () => { + 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.'); }; if (!androidPgp) void renderKeyServers(); - void renderContacts(); - void render(); -} - + void renderContacts(); + void render(); +} + window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => function () { baseOpenPreferences(); - const fields = selectPgpKeyUi('#modal-root .compose-fields'); - if (!fields || !pgpAvailable()) return; - const button = document.createElement('button'); - button.type = 'button'; - button.className = 'discard'; - button.id = 'open-encryption-keys'; - button.textContent = 'Encryption keys…'; - button.onclick = openEncryptionKeys; - fields.append(button); + const fields = selectPgpKeyUi('#modal-root .compose-fields'); + if (!fields || !pgpAvailable()) return; + const button = document.createElement('button'); + button.type = 'button'; + button.className = 'discard'; + button.id = 'open-encryption-keys'; + button.textContent = 'Encryption keys…'; + button.onclick = openEncryptionKeys; + fields.append(button); }); })(); diff --git a/www/platform-bridge.js b/www/platform-bridge.js index 2a2b271..49c4654 100644 --- a/www/platform-bridge.js +++ b/www/platform-bridge.js @@ -10240,20 +10240,30 @@ Add the new key as an unverified key? Compare fingerprints with the owner before async function unlock(fingerprint, passphrase) { const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint); if (!entry) throw new Error("That key was not found."); + 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 po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase }); } catch { throw new Error("The passphrase is incorrect."); } } + async function biometricPassphrase(fingerprint) { + if (typeof EpMail2.getPgpBiometricPassphrase !== "function") return null; + const result = await EpMail2.getPgpBiometricPassphrase({ fingerprint }); + return result?.enabled && typeof result.passphrase === "string" ? result.passphrase : null; + } async function signerFor(account, passphrase) { const data = await store(); const entry = data.keys.find((item) => item.email.toLowerCase() === String(account.email).toLowerCase()); if (!entry) throw Object.assign(new Error("Create or import an encryption key for this address first."), { code: "NO_SIGNING_KEY" }); - const secret = passphrase || cached(entry.fingerprint); + 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 }); try { - const key = await unlock(entry.fingerprint, secret); + const key = await unlockWithPassphrase(entry, secret); cache(entry.fingerprint, secret); return { key, entry }; } catch { @@ -10364,6 +10374,7 @@ ${body}`); selected = candidates.find((entry) => cached(entry.fingerprint)) || selected; 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." }; let privateKey; try { @@ -10536,6 +10547,23 @@ ${body}`); clear(fingerprint); return { removed: true }; }, + async enableBiometricUnlock({ fingerprint, passphrase }) { + if (typeof EpMail2.setPgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device."); + const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint); + if (!entry) throw new Error("That key was not found."); + if (!passphrase) throw new Error("Enter the key passphrase first."); + await unlockWithPassphrase(entry, passphrase); + return EpMail2.setPgpBiometricUnlock({ fingerprint, passphrase }); + }, + async biometricUnlockEnabled(fingerprint) { + if (typeof EpMail2.pgpBiometricUnlockEnabled !== "function") return false; + return Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled); + }, + async disableBiometricUnlock(fingerprint) { + if (typeof EpMail2.removePgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device."); + clear(fingerprint); + return EpMail2.removePgpBiometricUnlock({ fingerprint }); + }, async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); }, @@ -10575,10 +10603,20 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error const { keys, missing } = await resolveRecipients(addresses); const account = await getAccount(); const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null; + let biometricUnlockEnabled = false; + if (entry && typeof EpMail2.pgpBiometricUnlockEnabled === "function") { + biometricUnlockEnabled = Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled); + } 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, @@ -10637,6 +10675,8 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }), getAppLockSettings: () => EpMail.getAppLockSettings(), setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }), + setAppLockDelay: (seconds) => EpMail.setAppLockDelay({ seconds }), + deleteAllLocalData: () => EpMail.deleteAllLocalData(), getAccount: () => EpMail.getAccount(), listAccounts: () => EpMail.listAccounts(), selectAccount: (id) => EpMail.selectAccount({ id }), diff --git a/www/productivity.js b/www/productivity.js index 71b4049..63b41e0 100644 --- a/www/productivity.js +++ b/www/productivity.js @@ -6,58 +6,61 @@ const selectAllProductivityUi = productivityMailUi.selectAll; const toastProductivityUi = productivityMailUi.toast; const escapeProductivityUi = productivityMailUi.escapeHtml; const productKeys = { profile: 'daybreak-profile', events: 'daybreak-events', contacts: 'daybreak-contacts', labels: 'daybreak-labels', snoozed: 'daybreak-snoozed' }; -const 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)); -let profileSettings = productRead(productKeys.profile, { name: '' }); -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); -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())); -productWrite(productKeys.contacts, savedContacts); -let savedEvents = productRead(productKeys.events, []); -let customLabels = productRead(productKeys.labels, []); -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 openAccountSettings() { - const root=selectProductivityUi('#modal-root'); - root.innerHTML=``; - const close=()=>root.innerHTML=''; - selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); - selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; - selectProductivityUi('#save-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(); -} +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)); +let profileSettings = productRead(productKeys.profile, { name: '' }); +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); +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())); +productWrite(productKeys.contacts, savedContacts); +let savedEvents = productRead(productKeys.events, []); +let customLabels = productRead(productKeys.labels, []); +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 openAccountSettings() { + const root=selectProductivityUi('#modal-root'); + root.innerHTML=``; + const close=()=>root.innerHTML=''; + selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); + selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + selectProductivityUi('#save-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(); +} async function openPreferences() { const root=selectProductivityUi('#modal-root'); const themes=[['daylight','Eternity Daylight'],['wasteland','Wasteland'],['ep-wasteland','EP Wasteland'],['ep-daylight','EP Daylight']]; const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland'; const options=themes.map(([value,label])=>``).join(''); 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 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(appLockBridge){try{appLockSettings=await appLockBridge.getAppLockSettings()}catch(error){toastProductivityUi(error.message||'Could not load app-lock settings');return}} const notificationSetting=notificationBridge?``:''; - const appLockSetting=appLockBridge?``:''; - root.innerHTML=``; - const close=()=>root.innerHTML=''; - selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); - selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; - selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge)await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked);productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}}; - selectProductivityUi('#theme-select').focus(); -} -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=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); } -function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}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=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;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=``;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()} -function renderContacts(){const cards=savedContacts.map((c,i)=>`
${escapeProductivityUi(c.initials)}
${escapeProductivityUi(c.name)}${escapeProductivityUi(c.email)}${escapeProductivityUi(c.note)}
`).join('');selectProductivityUi('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}} -function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} -function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})} -function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')} -function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()} -async function actOnSelected(action){const selected=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='';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()} + const appLockSetting=appLockBridge?``:''; + const localDataSetting=localDataBridge?`

Local data

`:''; + root.innerHTML=``; + const close=()=>root.innerHTML=''; + selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close); + selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()}; + selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge){await appLockBridge.setAppLockDelay(Number(selectProductivityUi('#app-lock-delay').value));await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked)}productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}}; + if(localDataBridge)selectProductivityUi('#delete-all-local-data').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await localDataBridge.deleteAllLocalData();if(!result?.deleted){button.disabled=false;return}if('serviceWorker'in navigator){const registrations=await navigator.serviceWorker.getRegistrations();await Promise.all(registrations.map(registration=>registration.unregister()))}if('caches'in window){const names=await caches.keys();await Promise.all(names.map(name=>caches.delete(name)))}localStorage.clear();window.location.reload()}catch(error){button.disabled=false;toastProductivityUi(error.message||'Native data was deleted, but browser data cleanup did not finish. Restart ep-mail to complete cleanup.')}}; + selectProductivityUi('#theme-select').focus(); +} +function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=``; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); } +function renderCalendar(){const year=calendarMonth.getFullYear(),month=calendarMonth.getMonth(),first=new Date(year,month,1),start=new Date(year,month,1-first.getDay()),days=['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];let cells='';for(let i=0;i<42;i++){const d=new Date(start);d.setDate(start.getDate()+i);const key=`${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`,items=savedEvents.filter(e=>e.date===key);cells+=`
${d.getDate()}${items.slice(0,3).map(e=>`
${escapeProductivityUi(e.time?`${e.time} `:'')}${escapeProductivityUi(e.title)}
`).join('')}${items.length>3?`+${items.length-3} more`:''}
`}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=`

YOUR TIME, WITH ROOM TO BREATHE

${new Intl.DateTimeFormat('en-US',{month:'long',year:'numeric'}).format(calendarMonth)}

${savedEvents.length} saved events

${days.map(d=>`${d}`).join('')}
${cells}

Coming up

${upcoming.length?upcoming.map(e=>``).join(''):'

No upcoming events yet.

'}
`;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=``;const close=()=>root.innerHTML='';selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close);selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()};selectProductivityUi('#save-contact').onclick=async()=>{const name=selectProductivityUi('#contact-name').value.trim(),email=selectProductivityUi('#contact-email').value.trim();if(!name||!email){toastProductivityUi('Add a name and email');return}const item={...(existing||{}),name,email,note:selectProductivityUi('#contact-note').value.trim()||'Contact',initials:name.split(/\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:existing?.color||'#e7dfce'};if(window.daybreakMail?.davSaveContact){try{const remote=await window.daybreakMail.davSaveContact(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; CardDAV sync failed: '+error.message)}}if(existing)savedContacts[index]=item;else savedContacts.push(item);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi(existing?'Contact updated':'Contact saved')};if(existing)selectProductivityUi('#delete-contact').onclick=async()=>{if(existing._dav&&window.daybreakMail?.davDeleteContact){try{await window.daybreakMail.davDeleteContact(existing._dav)}catch(error){toastProductivityUi('Could not delete remote contact: '+error.message);return}}savedContacts.splice(index,1);productWrite(productKeys.contacts,savedContacts);close();renderContacts();toastProductivityUi('Contact removed')};selectProductivityUi('#contact-name').focus()} +function renderContacts(){const cards=savedContacts.map((c,i)=>`
${escapeProductivityUi(c.initials)}
${escapeProductivityUi(c.name)}${escapeProductivityUi(c.email)}${escapeProductivityUi(c.note)}
`).join('');selectProductivityUi('#contacts-view').innerHTML=`

THE PEOPLE WHO MAKE LIFE FULLER

Your people

${savedContacts.length} contacts, all in one place.

${cards||'

No contacts yet. Add someone to get started.

'}
`;selectProductivityUi('#add-contact').onclick=()=>showContact();selectProductivityUi('#contact-search').oninput=e=>selectAllProductivityUi('.contact-card').forEach(c=>c.classList.toggle('hidden',!c.innerText.toLowerCase().includes(e.target.value.toLowerCase())));selectProductivityUi('#contacts-view').onclick=e=>{const edit=e.target.closest('[data-edit-contact]');if(edit){showContact(Number(edit.dataset.editContact));return}const email=e.target.closest('.contact-email');if(email)productivityMailUi.showCompose({email:email.dataset.email,subject:'',date:''})};selectProductivityUi('#contacts-view').oncontextmenu=e=>{const card=e.target.closest('.contact-card');if(!card)return;e.preventDefault();const i=Number(card.dataset.contact);if(confirm(`Remove ${savedContacts[i].name} from contacts?`)){savedContacts.splice(i,1);productWrite(productKeys.contacts,savedContacts);renderContacts();toastProductivityUi('Contact removed')}}} +function accountRuleLabels(){return [...new Set((productivityMailUi.connectedAccount?.rules||[]).filter(rule=>rule.action==='label').map(rule=>rule.value).filter(Boolean))]} +function renderLabels(){const box=selectProductivityUi('#custom-labels');if(!box)return;const labels=[...new Set([...customLabels,...accountRuleLabels()])];box.innerHTML=labels.map(label=>``).join('');selectAllProductivityUi('.label-link').forEach(b=>b.onclick=()=>{document.querySelectorAll('.label-link').forEach(x=>x.classList.toggle('active',x===b));productivityMailUi.state.activeFolder=b.dataset.label;selectProductivityUi('#sidebar-title').textContent=productivityMailUi.state.activeFolder;selectProductivityUi('#crumb-current').textContent=productivityMailUi.state.activeFolder;productivityMailUi.renderList()})} +function addCustomLabel(){const label=prompt('Name this label');if(!label?.trim())return;const clean=label.trim();if(customLabels.some(x=>x.toLowerCase()===clean.toLowerCase())){toastProductivityUi('That label already exists');return}customLabels.push(clean);productWrite(productKeys.labels,customLabels);renderLabels();toastProductivityUi('Label added')} +function messageAction(message,action){if(productivityMailUi.connectedAccount&&window.daybreakMail&&message.uid){return window.daybreakMail.updateMessage({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,action,enabled:action==='star'?!message.star:true}).then(result=>{if(result?.queued)toastProductivityUi('Offline: action queued and will sync when connected');return result})}return Promise.resolve()} +async function actOnSelected(action){const selected=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='';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 () { const state = productivityMailUi.state; if (state.activeFolder === 'Drafts') { @@ -79,7 +82,7 @@ productivityMailUi.wrapRenderList(baseMessageRenderer => function () { return; } return baseMessageRenderer(); -}); +}); document.addEventListener('click',event=>{const button=event.target.closest('.download');if(!button)return;event.stopImmediatePropagation();const message=productivityMailUi.state.messages.find(item=>item.id===productivityMailUi.state.activeMessage);const filename=button.dataset.filename||message?.attachment;if(!filename){toastProductivityUi('This message has no downloadable attachment');return}const decrypted=message?.attachments?.find(file=>file.filename===filename&&file.contentBase64);const saving=decrypted&&window.daybreakMail?.savePgpAttachment?window.daybreakMail.savePgpAttachment(decrypted):message?.uid&&window.daybreakMail?.saveAttachment?window.daybreakMail.saveAttachment({uid:message.uid,folder:message.sourceFolder||productivityMailUi.state.activeFolder,filename}):null;if(!saving){toastProductivityUi('Attachment download is available for connected mailbox messages');return}saving.then(result=>{if(result.saved)toastProductivityUi('Attachment saved')}).catch(error=>toastProductivityUi(error.message||'Could not save attachment'))},true); window.epMailFeatures.productivity = Object.freeze({