Compare commits

..
2 Commits
25 changed files with 1067 additions and 141 deletions
+14 -13
View File
@@ -6,17 +6,17 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU
## Implementation progress (2026-11-03) ## Implementation progress (2026-11-03)
- **Phase 0 — Baseline:** Mostly implemented; release verification remains open. - **Phase 0 — Baseline:** The merged release manifest and core WebView/network settings have now been reviewed and hardened. TLS certificate integration tests, the complete plugin audit, and a production-signed APK review remain open, so the Phase 0 release gate is not closed.
- **Phase 1 — Local data/privacy:** Notification privacy and the basic native app lock are implemented; vault lifecycle, deletion, and lock-recovery assurance remain open. - **Phase 1 — Local data/privacy:** Notification privacy, 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 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 3 — WebView/bridge:** Important protections are implemented; complete bridge review and device/content testing remain open.
- **Phase 4 — Assurance:** Open; independent review, release assurance, and vulnerability/maintenance work remain. - **Phase 4 — Assurance:** Open; independent review, release assurance, and vulnerability/maintenance work remain.
Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed. Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed.
OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, and on-demand PGP/MIME or inline-encrypted-message decryption. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**. OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, on-demand PGP/MIME or inline-encrypted-message decryption, and verification of signed-only PGP/MIME and clear-signed messages. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext 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, and the confirmation gate's accept/cancel callback ordering have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock and unlock. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. Phone and landscape layouts were checked for horizontal overflow. Current validation: Android debug build and 20 Android unit tests pass; the Node suite has 151 passes and one version-consistency failure because the working tree's `package-lock.json` is locally set to 0.5.9 while `package.json` remains 0.5.8. That lockfile change was preserved. This does not constitute automated testing of the actual Android dialog UI, live-provider mail testing, or GnuPG/Thunderbird interoperability testing on Android. **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.
**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 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.
@@ -39,31 +39,32 @@ These are implementation observations, not proof that all paths are safe. In par
### Phase 0 — Android security baseline and release gate (P0) ### Phase 0 — Android security baseline and release gate (P0)
- [ ] Complete and record a checklist for the merged manifest and production APK (permissions, exported components, backup rules, cleartext policy, WebView debugging, file access, and plugin exposure). Backup/data-extraction exclusions, cleartext denial, removal of the wildcard origin, and removal of the unused broad `FileProvider` are implemented; the production-artifact review is not. - [x] Generate and review the V0.5.11 worktree release-variant merged manifest. It uses package `studio.daybreak.mail`, versionCode 511/versionName 0.5.11, minSdk 24/targetSdk 36; `allowBackup=false`, `usesCleartextTraffic=false`, and data-extraction exclusions for root/files/databases/shared preferences/external storage. The release manifest has no `debuggable=true` attribute. `MainActivity` is exported only for the launcher; WorkManager's exported job service is protected by `BIND_JOB_SERVICE`; diagnostics/profile receivers require `DUMP`; other merged components are non-exported. The only declared permissions are network, foreground data sync, notifications, wake lock, network-state/boot support, and a signature-protected dynamic-receiver permission. The unused broad `FileProvider` and wildcard origin are absent. The V0.5.10 published APK itself remains debug-signed; no production-signed artifact has been reviewed.
- [~] Require TLS and hostname validation on IMAP/SMTP and DAV. DAV is restricted to HTTPS and the configured origin; transport TLS modes are implemented and covered by unit tests. Invalid, expired, and mismatched certificate integration tests and a full native-client review remain open. - [~] Review release WebView settings. Web contents debugging now follows `BuildConfig.DEBUG`; file/content access, file-URL cross-access, automatic JavaScript windows, and geolocation are disabled; mixed content is explicitly `NEVER_ALLOW`. The packaged app uses the HTTPS localhost origin. The hardened build compiles and loads the app/Capacitor bridge in the emulator; a full supported-device review remains open.
- [~] Require TLS and hostname validation on IMAP/SMTP and DAV. DAV is restricted to HTTPS and the configured origin; transport requires STARTTLS or implicit TLS and verifies host identity. Unit tests check those settings and absence of permissive trust/socket-factory overrides. Invalid, expired, and mismatched certificate integration tests and a full native-client review remain open.
- [~] Review `EpMailPlugin` as an untrusted-input boundary. DAV URLs and attachment names have specific native validation; PGP MIME structure and send confirmations have added native checks. A complete method-by-method bridge review and comprehensive size/state tests remain open. - [~] Review `EpMailPlugin` as an untrusted-input boundary. DAV URLs and attachment names have specific native validation; PGP MIME structure and send confirmations have added native checks. A complete method-by-method bridge review and comprehensive size/state tests remain open.
- [~] Keep signing keys outside the repository, label debug APKs, and require environment-provided credentials for signed builds. No production-signed APK or merged release review has been completed. - [~] Keep signing keys outside the repository, label debug APKs, and require environment-provided credentials for signed builds. No Android release-signing variables are configured here; published Android APKs are clearly labeled debug/test-only, and no production-signed APK has been reviewed.
- [x] Remove/sanitize sensitive native logging; the current mail sync log omits mailbox content and credentials. - [x] Remove/sanitize sensitive native logging; the current mail sync log omits mailbox content and credentials.
**Exit criteria:** documented release manifest/config review; TLS validation and downgrade regression tests pass; no sensitive data in logs; release APK is signed and distinguishable from debug output. **Exit criteria:** documented release manifest/config review; TLS validation and downgrade regression tests pass; no sensitive data in logs; release APK is signed and distinguishable from debug output.
### Phase 1 — Local data and privacy controls (P0) ### Phase 1 — Local data and privacy controls (P0)
- [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. Document and test the key's security/fallback behavior, corruption and reinstall handling, and lock-screen/key invalidation; verify no plaintext fallback across all stored data. - [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. If the key alias is missing while encrypted data remains, the app now refuses to generate a replacement key and shows a recovery screen; it does not reset or expose the data. Add device tests for missing/invalidated keys, corrupted ciphertext, reinstall/migration handling, and the recovery instructions; verify no plaintext fallback for all stored data.
- [~] Account removal exists, but prove deletion covers account caches, queued sends, downloaded files, and related encryption-key lifecycle; document exported files and recovery limits. - [~] 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] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting. - [x] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting.
- [~] A native app lock covers the WebView on background/resume and uses the device credential; background sync continues. Delayed lock, task-switcher obscuring, process-recreation/timeout tests, biometric UX, and recovery polish remain open. - [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` 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.
- [x] Background sync is separate from the UI lock. Further verification of which credentials/key material are available to background workers remains part of the vault lifecycle review. - [x] Background sync is separate from the UI lock. Further verification of which credentials/key material are available to background workers remains part of the vault lifecycle review.
**Exit criteria:** storage migration and failure tests; no plaintext fallback; app-lock/session tests across lifecycle events; notification privacy tests on supported Android versions; data removal tests. **Exit criteria:** storage migration and failure tests; no plaintext fallback; app-lock/session tests across lifecycle events; notification privacy tests on supported Android versions; data removal tests.
### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity) ### Phase 2 — OpenPGP on Android (P0 before claiming encrypted-mail parity)
- [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Independent review and GnuPG/Thunderbird interoperability on Android are release blockers. - [~] OpenPGP.js 6.3.2 is pinned and used by the experimental Android bundle, before the independent review gate is complete solely to enable local testing. Automated Node-harness tests exercise the Android module against GnuPG; independent review and on-device GnuPG/Thunderbird interoperability remain release blockers.
- [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized. Biometric wrapping-key release, lifecycle/recovery handling, and automated checks against unprotected-key persistence remain open. - [~] PGP keys, contacts, trust, and settings are stored in the existing Keystore-encrypted vault; keys generated/imported by the UI are passphrase-protected, and passphrases are not serialized. 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. - [ ] Add optional biometric/device-credential release of PGP key access and test Keystore invalidation/recovery. Background sync does not use PGP private keys.
- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, and trust. Native prompts now guard trust elevation and replacement; automated cancel/confirm regression tests remain open. - [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, trust, and public keys offered as message attachments (never imported silently). 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, and ciphertext-before-queueing are implemented. Signed-only/clear-signed/inline signature parity, full hostile-input/tampering suite, and Android interoperability remain open. - [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open.
- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; the native send path checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open. - [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; 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.
- [x] Key-server lookup and publication are disabled in the initial Android test implementation. - [x] Key-server lookup and publication are disabled in the initial Android test implementation.
+1 -1
View File
@@ -18,7 +18,7 @@ See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
## Android app ## Android app
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, encrypted account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Android Settings can enable an app lock that covers the WebView and disables its JavaScript bridge when the app leaves the foreground; unlock requires the device PIN, pattern, or password, while background mail sync continues. Configure a secure Android screen lock before enabling it. This is a local privacy control, not protection against a compromised or rooted device. Android OpenPGP is now present as an **experimental test-only feature** for key and message testing. It has not had an independent cryptography/security review and is not approved for sensitive or production mail; do not rely on it to protect important messages. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run: The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, encrypted account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Android Settings can enable an app lock that covers the WebView and disables its JavaScript bridge when the app leaves the foreground; it also hides the locked screen from screenshots and recent-app previews. Unlock requires the device PIN, pattern, or password, while background mail sync continues. Configure a secure Android screen lock before enabling it. This is a local privacy control, not protection against a compromised or rooted device. Android OpenPGP is now present as an **experimental test-only feature** for key and message testing. It has not had an independent cryptography/security review and is not approved for sensitive or production mail; do not rely on it to protect important messages. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
```sh ```sh
npm install npm install
+10 -2
View File
@@ -34,8 +34,9 @@
- [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption. - [x] Experimental Android test path: Keystore-encrypted vault key storage, key/contact management, PGP/MIME encryption/signing, and on-demand decryption.
- [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation. - [x] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation.
- [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions. - [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions.
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, full parity/interoperability tests, independent human cryptography/security review, and signed release review. - [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness.
- [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, signed/inline verification parity, and dependency advisory remediation. - [ ] Android release gate: instrumented native-dialog UI and bypass tests, device-level parity/interoperability tests (including Thunderbird/GnuPG on Android), independent human cryptography/security review, and signed release review.
- [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, remaining signature parity/device interoperability, and dependency advisory remediation.
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests. - [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures). - [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
- [x] Phase 6: documentation and release. - [x] Phase 6: documentation and release.
@@ -48,6 +49,13 @@
- [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks. - [ ] Complete the Android security work in [ANDROID_SECURITY_PLAN.md](./ANDROID_SECURITY_PLAN.md), including Android OpenPGP and release security checks.
- [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews. - [x] Make Android notification details opt-in, persist the preference in the encrypted vault, and redact lock-screen previews.
- [x] Add an optional native Android app lock using the device credential while leaving background mail sync available. - [x] Add an optional native Android app lock using the device credential while leaving background mail sync available.
- [x] Set `FLAG_SECURE` while the optional app lock is engaged to hide the screen from screenshots and recents previews.
- [x] Exercise background lock, credential unlock, and screenshot obscuring on an Android emulator.
- [x] Disclose in account-removal confirmation that downloaded files and global OpenPGP keys are retained.
- [x] Refuse to generate a replacement Keystore key when encrypted vault data already exists; show a fail-closed recovery screen with clear-data guidance.
- [ ] Device-test missing/invalidated Keystore keys, corrupted vault data, migration/reinstall behavior, and recovery instructions.
- [ ] Define/test full app-data deletion and downloaded-file/OpenPGP-key retention or removal behavior.
- [ ] Add app-lock timeout/delay options and decide whether to add biometric unlock; test process recreation and lifecycle transitions.
## Appearance and settings ## Appearance and settings
+1 -1
View File
@@ -21,7 +21,7 @@ async function openAccountManager(){
const editButton=event.target.closest('[data-edit-account]'); const editButton=event.target.closest('[data-edit-account]');
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return} if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
const removeButton=event.target.closest('[data-remove-account]'); const removeButton=event.target.closest('[data-remove-account]');
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return} if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?\n\nIts cached mail, drafts and pending sends will be removed. Downloaded attachment files and OpenPGP keys are kept; delete those separately if you want to remove them too.`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
}; };
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')} }catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
} }
@@ -21,12 +21,11 @@ internal object AndroidAccountVault {
private const val ENCRYPTED_VALUE = "encrypted-data" private const val ENCRYPTED_VALUE = "encrypted-data"
private const val GCM_TAG_BITS = 128 private const val GCM_TAG_BITS = 128
@Volatile private var appContext: Context? = null @Volatile private var appContext: Context? = null
fun initialize(context: Context) { fun initialize(context: Context) {
appContext = context.applicationContext appContext = context.applicationContext
secretKey() }
}
@Synchronized @Synchronized
fun read(): JSONObject { fun read(): JSONObject {
@@ -598,10 +597,15 @@ internal object AndroidAccountVault {
appContext ?: throw IllegalStateException("Encrypted account storage is not initialized.") appContext ?: throw IllegalStateException("Encrypted account storage is not initialized.")
@Synchronized @Synchronized
private fun secretKey(): SecretKey { private fun secretKey(): SecretKey {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it } (keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore") 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( generator.init(
KeyGenParameterSpec.Builder( KeyGenParameterSpec.Builder(
KEY_ALIAS, KEY_ALIAS,
@@ -669,6 +669,7 @@ internal object AndroidMailService {
collectParts(message, body, htmlBodies, attachments, links) collectParts(message, body, htmlBodies, attachments, links)
val bodyText = body.joinToString("\n\n").trim().take(8000) val bodyText = body.joinToString("\n\n").trim().take(8000)
val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----") val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----")
val 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 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 snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date() val date = message.receivedDate ?: message.sentDate ?: Date()
@@ -694,6 +695,7 @@ internal object AndroidMailService {
.put("subject", subject) .put("subject", subject)
.put("snippet", snippet) .put("snippet", snippet)
.put("encrypted", encrypted) .put("encrypted", encrypted)
.put("signed", signed)
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date)) .put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date)) .put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
.put("timestamp", date.time) .put("timestamp", date.time)
@@ -723,18 +725,29 @@ internal object AndroidMailService {
} else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true } else if (content is String && content.contains("-----BEGIN PGP MESSAGE-----")) return true
return false return false
} }
private fun isSignedMessage(part: javax.mail.Part): Boolean {
if (part.isMimeType("multipart/signed")) return true
val content = try { part.content } catch (_: Exception) { return false }
if (content is Multipart) {
for (index in 0 until content.count) if (isSignedMessage(content.getBodyPart(index))) return true
} else if (content is String && content.contains("-----BEGIN PGP SIGNED MESSAGE-----")) return true
return false
}
private fun attachmentList(attachments: JSONArray): List<JSONObject> = private fun attachmentList(attachments: JSONArray): List<JSONObject> =
(0 until attachments.length()).map { attachments.getJSONObject(it) } (0 until attachments.length()).map { attachments.getJSONObject(it) }
private fun collectParts( private fun collectParts(
part: javax.mail.Part, part: javax.mail.Part,
body: MutableList<String>, body: MutableList<String>,
htmlBodies: MutableList<String>, htmlBodies: MutableList<String>,
attachments: JSONArray, attachments: JSONArray,
links: MutableSet<String> links: MutableSet<String>
) { ) {
val filename = decode(part.fileName) 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)) { if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
val name = filename.ifBlank { "attachment" } val name = filename.ifBlank { "attachment" }
val size = part.size.coerceAtLeast(0) val size = part.size.coerceAtLeast(0)
@@ -0,0 +1,8 @@
package studio.daybreak.mail
internal object AndroidVaultKeyPolicy {
fun shouldCreateKey(hasEncryptedData: Boolean): Boolean = !hasEncryptedData
const val MISSING_KEY_MESSAGE =
"The Android Keystore key for saved app data is missing. Existing encrypted data was not reset or replaced."
}
@@ -22,8 +22,8 @@ import javax.mail.internet.InternetAddress
class EpMailPlugin : Plugin() { class EpMailPlugin : Plugin() {
private var syncReceiver: BroadcastReceiver? = null private var syncReceiver: BroadcastReceiver? = null
override fun load() { override fun load() {
AndroidAccountVault.initialize(context) AndroidAccountVault.initialize(context)
val filter = IntentFilter(MailIdleService.ACTION_MAIL_SYNC) val filter = IntentFilter(MailIdleService.ACTION_MAIL_SYNC)
val receiver = object : BroadcastReceiver() { val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
@@ -38,12 +38,21 @@ class EpMailPlugin : Plugin() {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
context.registerReceiver(receiver, filter) context.registerReceiver(receiver, filter)
} }
MailIdleService.start(context) ensureVaultAvailableAndStartSync()
} }
override fun handleOnResume() { override fun handleOnResume() {
MailIdleService.start(context) ensureVaultAvailableAndStartSync()
} }
private fun ensureVaultAvailableAndStartSync() {
try {
AndroidAccountVault.read()
MailIdleService.start(context)
} catch (error: Exception) {
android.util.Log.e("EpMailStorage", "Secure local storage is unavailable (${error.javaClass.simpleName})")
}
}
override fun handleOnDestroy() { override fun handleOnDestroy() {
syncReceiver?.let { syncReceiver?.let {
@@ -6,11 +6,13 @@ import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.Color; import android.graphics.Color;
import android.net.Uri;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.view.Gravity; import android.view.Gravity;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView; import android.webkit.WebView;
import android.widget.Button; import android.widget.Button;
import android.widget.FrameLayout; import android.widget.FrameLayout;
@@ -27,12 +29,21 @@ public class MainActivity extends BridgeActivity {
private boolean appLocked; private boolean appLocked;
private boolean awaitingUnlockResult; private boolean awaitingUnlockResult;
private boolean activityResumed; private boolean activityResumed;
private boolean vaultRecoveryRequired;
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
registerPlugin(EpMailPlugin.class); registerPlugin(EpMailPlugin.class);
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
hardenWebView();
AndroidAccountVault.INSTANCE.initialize(getApplicationContext()); AndroidAccountVault.INSTANCE.initialize(getApplicationContext());
try {
AndroidAccountVault.INSTANCE.read();
} catch (Exception storageError) {
vaultRecoveryRequired = true;
createVaultRecoveryOverlay();
return;
}
createAppLockOverlay(); createAppLockOverlay();
if (isAppLockEnabled()) lockWebView(); if (isAppLockEnabled()) lockWebView();
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
@@ -43,6 +54,7 @@ public class MainActivity extends BridgeActivity {
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if (vaultRecoveryRequired) return;
activityResumed = true; activityResumed = true;
if (isAppLockEnabled() && appLocked) { if (isAppLockEnabled() && appLocked) {
lockWebView(); lockWebView();
@@ -53,7 +65,7 @@ public class MainActivity extends BridgeActivity {
@Override @Override
public void onPause() { public void onPause() {
activityResumed = false; activityResumed = false;
if (isAppLockEnabled()) lockWebView(); if (!vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
super.onPause(); super.onPause();
} }
@@ -88,6 +100,77 @@ public class MainActivity extends BridgeActivity {
} }
} }
private void hardenWebView() {
if (getBridge() == null || getBridge().getWebView() == null) return;
WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG);
WebView webView = getBridge().getWebView();
android.webkit.WebSettings settings = webView.getSettings();
settings.setAllowFileAccess(false);
settings.setAllowContentAccess(false);
settings.setAllowFileAccessFromFileURLs(false);
settings.setAllowUniversalAccessFromFileURLs(false);
settings.setGeolocationEnabled(false);
settings.setJavaScriptCanOpenWindowsAutomatically(false);
settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_NEVER_ALLOW);
}
private void createVaultRecoveryOverlay() {
View content = findViewById(android.R.id.content);
if (!(content instanceof FrameLayout)) return;
FrameLayout overlay = new FrameLayout(this);
overlay.setBackgroundColor(Color.rgb(25, 21, 18));
overlay.setClickable(true);
overlay.setFocusable(true);
LinearLayout panel = new LinearLayout(this);
panel.setOrientation(LinearLayout.VERTICAL);
panel.setGravity(Gravity.CENTER);
panel.setPadding(dp(28), dp(28), dp(28), dp(28));
TextView title = new TextView(this);
title.setText("Saved data could not be opened");
title.setTextColor(Color.rgb(238, 230, 215));
title.setTextSize(21);
title.setGravity(Gravity.CENTER);
panel.addView(title, new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
TextView details = new TextView(this);
details.setText("ep-mail could not decrypt its saved local data. It has not been reset or replaced. Try restoring the same device/app state if available. If you cannot recover it, open Android App info and clear ep-mail data to start fresh; this permanently removes saved accounts, cached mail, drafts, queued sends, DAV settings, and OpenPGP keys. Attachments already saved to Downloads remain there.");
details.setTextColor(Color.rgb(210, 199, 181));
details.setTextSize(14);
details.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams detailsParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
detailsParams.topMargin = dp(16);
panel.addView(details, detailsParams);
Button settingsButton = new Button(this);
settingsButton.setText("Open Android App info");
settingsButton.setOnClickListener(view -> {
try {
startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName())));
} catch (Exception ignored) {
// Keep the recovery instructions visible if Settings cannot be launched.
}
});
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
buttonParams.gravity = Gravity.CENTER_HORIZONTAL;
buttonParams.topMargin = dp(24);
panel.addView(settingsButton, buttonParams);
overlay.addView(panel, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
((FrameLayout) content).addView(overlay, new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (getBridge() != null && getBridge().getWebView() != null) {
getBridge().getWebView().getSettings().setJavaScriptEnabled(false);
}
}
private void createAppLockOverlay() { private void createAppLockOverlay() {
View content = findViewById(android.R.id.content); View content = findViewById(android.R.id.content);
if (!(content instanceof FrameLayout)) return; if (!(content instanceof FrameLayout)) return;
@@ -178,6 +261,7 @@ public class MainActivity extends BridgeActivity {
private void lockWebView() { private void lockWebView() {
appLocked = true; appLocked = true;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE); if (appLockOverlay != null) appLockOverlay.setVisibility(View.VISIBLE);
if (getBridge() != null) { if (getBridge() != null) {
WebView webView = getBridge().getWebView(); WebView webView = getBridge().getWebView();
@@ -188,6 +272,7 @@ public class MainActivity extends BridgeActivity {
private void unlockWebView(boolean reload) { private void unlockWebView(boolean reload) {
appLocked = false; appLocked = false;
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (getBridge() != null) { if (getBridge() != null) {
WebView webView = getBridge().getWebView(); WebView webView = getBridge().getWebView();
webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setJavaScriptEnabled(true);
@@ -14,6 +14,8 @@ class AndroidMailTransportTest {
assertEquals("true", properties.getProperty("mail.imap.starttls.enable")) assertEquals("true", properties.getProperty("mail.imap.starttls.enable"))
assertEquals("true", properties.getProperty("mail.imap.starttls.required")) assertEquals("true", properties.getProperty("mail.imap.starttls.required"))
assertEquals("true", properties.getProperty("mail.imap.ssl.checkserveridentity")) assertEquals("true", properties.getProperty("mail.imap.ssl.checkserveridentity"))
assertNull(properties.getProperty("mail.imap.ssl.trust"))
assertNull(properties.getProperty("mail.imap.ssl.socketFactory"))
assertNull(properties.getProperty("mail.imap.ssl.enable")) assertNull(properties.getProperty("mail.imap.ssl.enable"))
} }
@@ -25,6 +27,8 @@ class AndroidMailTransportTest {
assertEquals("imaps", properties.getProperty("mail.store.protocol")) assertEquals("imaps", properties.getProperty("mail.store.protocol"))
assertEquals("true", properties.getProperty("mail.imaps.ssl.enable")) assertEquals("true", properties.getProperty("mail.imaps.ssl.enable"))
assertEquals("true", properties.getProperty("mail.imaps.ssl.checkserveridentity")) assertEquals("true", properties.getProperty("mail.imaps.ssl.checkserveridentity"))
assertNull(properties.getProperty("mail.imaps.ssl.trust"))
assertNull(properties.getProperty("mail.imaps.ssl.socketFactory"))
assertNull(properties.getProperty("mail.imaps.starttls.required")) assertNull(properties.getProperty("mail.imaps.starttls.required"))
} }
@@ -35,12 +39,16 @@ class AndroidMailTransportTest {
) )
assertEquals("true", startTls.getProperty("mail.smtp.starttls.enable")) assertEquals("true", startTls.getProperty("mail.smtp.starttls.enable"))
assertEquals("true", startTls.getProperty("mail.smtp.starttls.required")) assertEquals("true", startTls.getProperty("mail.smtp.starttls.required"))
assertNull(startTls.getProperty("mail.smtp.ssl.trust"))
assertNull(startTls.getProperty("mail.smtp.ssl.socketFactory"))
val implicitTls = AndroidMailTransport.smtpProperties( val implicitTls = AndroidMailTransport.smtpProperties(
MailServerConnection("smtp.example.test", 465, true) MailServerConnection("smtp.example.test", 465, true)
) )
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.enable")) assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.enable"))
assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.checkserveridentity")) assertEquals("true", implicitTls.getProperty("mail.smtp.ssl.checkserveridentity"))
assertNull(implicitTls.getProperty("mail.smtp.ssl.trust"))
assertNull(implicitTls.getProperty("mail.smtp.ssl.socketFactory"))
assertNull(implicitTls.getProperty("mail.smtp.starttls.required")) assertNull(implicitTls.getProperty("mail.smtp.starttls.required"))
} }
} }
@@ -0,0 +1,14 @@
package studio.daybreak.mail
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class AndroidVaultKeyPolicyTest {
@Test
fun newKeyMayBeCreatedOnlyWhenThereIsNoEncryptedStore() {
assertTrue(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = false))
assertFalse(AndroidVaultKeyPolicy.shouldCreateKey(hasEncryptedData = true))
assertTrue(AndroidVaultKeyPolicy.MISSING_KEY_MESSAGE.contains("not reset or replaced"))
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.9", "version": "0.5.12",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.9", "version": "0.5.12",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.5.9", "version": "0.5.12",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
+38 -14
View File
@@ -70,12 +70,18 @@ function pgpRenderReaderState(message) {
if (!header) return; if (!header) return;
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
let html = ''; let html = '';
if (message.encrypted && !message.pgpDecrypted) { if (message.encrypted && !message.pgpDecrypted) {
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`; html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
} else if (message.encrypted) { } else if (message.encrypted) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true); html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.pgpSignatures) { } else if (message.signed && Array.isArray(message.pgpSignatures)) {
html = pgpSignatureHtml(message.pgpSignatures, false); html = pgpSignatureHtml(message.pgpSignatures, false);
} else if (message.signed && message.pgpVerifyFailed) {
html = `<section class="pgp-status pgp-warn" role="status"><strong>Could not check the OpenPGP signature</strong><span>${escapePgpMailUi(message.pgpVerifyFailed)}</span></section>`;
} else if (message.signed) {
html = '<section class="pgp-status pgp-warn" role="status"><strong>Checking OpenPGP signature…</strong><span>Do not rely on this message until verification completes.</span></section>';
} else if (message.pgpSignatures) {
html = pgpSignatureHtml(message.pgpSignatures, false);
} }
const keys = message.pgpResult?.attachedKeys || []; const keys = message.pgpResult?.attachedKeys || [];
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join('')); header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
@@ -86,7 +92,7 @@ function pgpRenderReaderState(message) {
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
} }
async function pgpUnlockMessage(message, interactive) { async function pgpUnlockMessage(message, interactive) {
let passphrase = null; let passphrase = null;
for (let attempt = 0; attempt < 3; attempt += 1) { for (let attempt = 0; attempt < 3; attempt += 1) {
let result; let result;
@@ -114,18 +120,36 @@ async function pgpUnlockMessage(message, interactive) {
if (text) text.textContent = result.message; if (text) text.textContent = result.message;
else toastPgpMailUi(result.message); else toastPgpMailUi(result.message);
return; return;
} }
} }
async function pgpVerifyMessage(message) {
try {
const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid });
if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.';
else {
message.pgpSignatures = result.signatures || [];
message.pgpVerifyFailed = null;
}
} catch (error) {
message.pgpVerifyFailed = error.message || 'The signature could not be checked.';
}
if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message);
}
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
baseOpenMessage(id); baseOpenMessage(id);
const message = pgpMailUi.state.messages.find(item => item.id === id); const message = pgpMailUi.state.messages.find(item => item.id === id);
if (!message || !pgpApi()) return; if (!message || !pgpApi()) return;
pgpRenderReaderState(message); pgpRenderReaderState(message);
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
message.pgpAutoTried = true; message.pgpAutoTried = true;
void pgpUnlockMessage(message, false); void pgpUnlockMessage(message, false);
} }
if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) {
message.pgpVerifyTried = true;
void pgpVerifyMessage(message);
}
}); });
// Compose: encrypt/sign options. // Compose: encrypt/sign options.
+196 -26
View File
@@ -5738,6 +5738,7 @@
super(e2, t2); super(e2, t2);
} }
}; };
var ka = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var Ea = class { var Ea = class {
constructor(e2) { constructor(e2) {
this.packets = e2 || new Gs(); this.packets = e2 || new Gs();
@@ -5753,6 +5754,22 @@
return this.packets.map(((e2) => e2.issuerKeyID)); return this.packets.map(((e2) => e2.issuerKeyID));
} }
}; };
async function va({ armoredSignature: e2, binarySignature: t2, config: r2, ...n2 }) {
r2 = { ...F, ...r2 };
let i2 = e2 || t2;
if (!i2) throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");
if (e2 && !N.isString(e2)) throw Error("readSignature: options.armoredSignature must be a string");
if (t2 && !N.isUint8Array(t2)) throw Error("readSignature: options.binarySignature must be a Uint8Array");
const s2 = Object.keys(n2);
if (s2.length > 0) throw Error("Unknown option: " + s2.join(", "));
if (e2) {
const { type: e3, data: t3 } = await $(i2);
if (e3 !== R.armor.signature) throw Error("Armored text not of type signature");
i2 = t3;
}
const a2 = await Gs.fromBinary(i2, ka, r2);
return new Ea(a2);
}
async function Ia(e2, t2) { async function Ia(e2, t2) {
const r2 = new wa(e2.date, t2); const r2 = new wa(e2.date, t2);
return r2.packets = null, r2.algorithm = R.write(R.publicKey, e2.algorithm), await r2.generate(e2.rsaBits, e2.curve), await r2.computeFingerprintAndKeyID(), r2; return r2.packets = null, r2.algorithm = R.write(R.publicKey, e2.algorithm), await r2.generate(e2.rsaBits, e2.curve), await r2.computeFingerprintAndKeyID(), r2;
@@ -6874,6 +6891,7 @@
const f2 = new no(h2); const f2 = new no(h2);
return f2.fromStream = c2, f2; return f2.fromStream = c2, f2;
} }
var co = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var uo = class _uo { var uo = class _uo {
constructor(e2, t2) { constructor(e2, t2) {
if (this.text = N.removeTrailingSpaces(e2).replace(/\r?\n/g, "\r\n"), t2 && !(t2 instanceof Ea)) throw Error("Invalid signature input"); if (this.text = N.removeTrailingSpaces(e2).replace(/\r?\n/g, "\r\n"), t2 && !(t2 instanceof Ea)) throw Error("Invalid signature input");
@@ -6903,6 +6921,38 @@
return ee(R.armor.signed, r2, void 0, void 0, void 0, t2, e2); return ee(R.armor.signed, r2, void 0, void 0, void 0, t2, e2);
} }
}; };
async function ho({ cleartextMessage: e2, config: t2, ...r2 }) {
if (t2 = { ...F, ...t2 }, !e2) throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");
if (!N.isString(e2)) throw Error("readCleartextMessage: options.cleartextMessage must be a string");
const n2 = Object.keys(r2);
if (n2.length > 0) throw Error("Unknown option: " + n2.join(", "));
const i2 = await $(e2);
if (i2.type !== R.armor.signed) throw Error("No cleartext signed message.");
const s2 = await Gs.fromBinary(i2.data, co, t2);
!(function(e3, t3) {
const r3 = function(e4) {
const r4 = (e5) => (t4) => e5.hashAlgorithm === t4;
for (let n4 = 0; n4 < t3.length; n4++) if (t3[n4].constructor.tag === R.packet.signature && !e4.some(r4(t3[n4]))) return false;
return true;
}, n3 = [];
if (e3.forEach(((e4) => {
const t4 = e4.match(/^Hash: (.+)$/);
if (!t4) throw Error('Only "Hash" header allowed in cleartext signed message');
{
const e5 = t4[1].replace(/\s/g, "").split(",").map(((e6) => {
try {
return R.write(R.hash, e6.toLowerCase());
} catch {
throw Error("Unknown hash algorithm in armor header: " + e6.toLowerCase());
}
}));
n3.push(...e5);
}
})), n3.length && !r3(n3)) throw Error("Hash algorithm mismatch in armor header and signature");
})(i2.headers, s2);
const a2 = new Ea(s2);
return new uo(i2.text, a2);
}
async function lo({ userIDs: e2 = [], passphrase: t2, type: r2, curve: n2, rsaBits: i2 = 4096, keyExpirationTime: s2 = 0, date: a2 = /* @__PURE__ */ new Date(), subkeys: o2 = [{}], format: c2 = "armored", signatureNotations: u2 = [], config: h2, ...f2 }) { async function lo({ userIDs: e2 = [], passphrase: t2, type: r2, curve: n2, rsaBits: i2 = 4096, keyExpirationTime: s2 = 0, date: a2 = /* @__PURE__ */ new Date(), subkeys: o2 = [{}], format: c2 = "armored", signatureNotations: u2 = [], config: h2, ...f2 }) {
Do(h2 = { ...F, ...h2 }), r2 || n2 ? (r2 = r2 || "ecc", n2 = n2 || "curve25519Legacy") : (r2 = h2.v6Keys ? "curve25519" : "ecc", n2 = "curve25519Legacy"), e2 = Uo(e2), u2 = Uo(u2); Do(h2 = { ...F, ...h2 }), r2 || n2 ? (r2 = r2 || "ecc", n2 = n2 || "curve25519Legacy") : (r2 = h2.v6Keys ? "curve25519" : "ecc", n2 = "curve25519Legacy"), e2 = Uo(e2), u2 = Uo(u2);
const l2 = Object.keys(f2); const l2 = Object.keys(f2);
@@ -7011,6 +7061,23 @@
throw N.wrapError("Error signing message", e3); throw N.wrapError("Error signing message", e3);
} }
} }
async function ko({ message: e2, verificationKeys: t2, expectSigned: r2 = false, format: n2 = "utf8", signature: i2 = null, date: s2 = /* @__PURE__ */ new Date(), config: a2, ...o2 }) {
if (Do(a2 = { ...F, ...a2 }), So(e2), t2 = Uo(t2), o2.publicKeys) throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");
const c2 = Object.keys(o2);
if (c2.length > 0) throw Error("Unknown option: " + c2.join(", "));
if (e2 instanceof uo && "binary" === n2) throw Error("Can't return cleartext message data as binary");
if (e2 instanceof uo && i2) throw Error("Can't verify detached cleartext signature");
try {
const o3 = {};
if (o3.signatures = i2 ? await e2.verifyDetached(i2, t2, s2, a2) : await e2.verify(t2, s2, a2), o3.data = "binary" === n2 ? e2.getLiteralData() : e2.getText(), e2.fromStream && !i2 && xo(o3, .../* @__PURE__ */ new Set([e2, e2.unwrapCompressed()])), r2) {
if (0 === o3.signatures.length) throw Error("Message is not signed");
o3.data = A([o3.data, P((async () => (await N.anyPromise(o3.signatures.map(((e3) => e3.verified))), "binary" === n2 ? new Uint8Array() : "")))]);
}
return o3.data = await Po(o3.data), o3;
} catch (e3) {
throw N.wrapError("Error verifying signed message", e3);
}
}
function Bo(e2) { function Bo(e2) {
if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message"); if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message");
} }
@@ -9896,6 +9963,25 @@
visit(bytes); visit(bytes);
return result; return result;
} }
async function attachedPublicKeys(attachments) {
const found = [];
for (const file of attachments || []) {
const type = String(file.contentType || "").toLowerCase();
if (type !== "application/pgp-keys" && !/\.asc$/i.test(file.filename || "")) continue;
if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue;
try {
const binary = atob(file.contentBase64);
const armoredKey = decoder.decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))).trim();
if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) || /-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue;
const key = await Ja({ armoredKey });
await key.getPrimaryUser();
found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
if (found.length === 5) break;
} catch {
}
}
return found;
}
function randomBoundary() { function randomBoundary() {
const bytes = crypto.getRandomValues(new Uint8Array(18)); const bytes = crypto.getRandomValues(new Uint8Array(18));
return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`; return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`;
@@ -9961,6 +10047,72 @@ ${parts.join("")}`;
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768)); for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
return btoa(binary); return btoa(binary);
} }
function bytesToLatin1(bytes) {
let text = "";
for (let index = 0; index < bytes.length; index += 32768) {
text += String.fromCharCode(...bytes.subarray(index, index + 32768));
}
return text;
}
function splitSignedMime(source, boundary) {
if (!boundary || boundary.length > 200) return null;
const text = bytesToLatin1(source);
const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, "g");
const marks = [...text.matchAll(delimiter)];
if (marks.length < 3) return null;
const contentAfter = (mark) => {
const lineEnd = text.indexOf("\n", mark.index + mark[0].length);
return lineEnd < 0 ? text.length : lineEnd + 1;
};
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, "\r\n");
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!signature) return null;
return { signed: Uint8Array.from(signed, (char) => char.charCodeAt(0) & 255), signature };
}
function senderFrom(headers) {
const value = String(headers.from || "");
return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || "").toLowerCase();
}
function invalidSignature() {
return {
status: "invalid",
keyId: "",
fingerprint: null,
trust: null,
email: null,
matchesSender: false,
keyChanged: false
};
}
async function signatureStatuses(signatures, verification, sender) {
const results = [];
for (const signature of signatures || []) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = verification.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === keyId));
let status = "valid";
try {
await signature.verified;
} catch {
status = known ? "invalid" : "unknown-key";
}
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const matchesSender = Boolean(sender && keyEmails.includes(sender));
const changed = Boolean(sender && verification.some((candidate) => !candidate.entry.own && candidate.entry.emails?.includes(sender) && candidate.entry.fingerprint !== known?.entry.fingerprint));
results.push({
status,
keyId,
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {}
});
}
return results;
}
function createAndroidPgp({ EpMail: EpMail2, getAccount }) { function createAndroidPgp({ EpMail: EpMail2, getAccount }) {
let storePromise; let storePromise;
const passphrases = /* @__PURE__ */ new Map(); const passphrases = /* @__PURE__ */ new Map();
@@ -10229,31 +10381,8 @@ ${body}`);
return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." }; return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." };
} }
const content = parseInnerMime(decrypted.data); const content = parseInnerMime(decrypted.data);
const signatures = []; const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
for (const item of decrypted.signatures || []) { const attachedKeys = await attachedPublicKeys(content.attachments);
const known = verify.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
let status = "valid";
try {
await item.verified;
} catch {
status = known ? "invalid" : "unknown-key";
}
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || "";
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || "").toLowerCase();
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const changed = Boolean(sender && data.contacts.some((entry) => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
const matchesSender = Boolean(sender && keyEmails.includes(sender));
signatures.push({
status,
keyId: item.keyID.toHex().toUpperCase(),
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {}
});
}
return { return {
ok: true, ok: true,
body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [],
@@ -10263,12 +10392,52 @@ ${body}`);
attachment: content.attachments[0]?.filename || null, attachment: content.attachments[0]?.filename || null,
size: content.attachments[0]?.size || "", size: content.attachments[0]?.size || "",
signatures, signatures,
attachedKeys: [] attachedKeys
}; };
} catch (error) { } catch (error) {
return { failed: true, code: error.code || "ERROR", message: error.message || "Could not decrypt this message." }; return { failed: true, code: error.code || "ERROR", message: error.message || "Could not decrypt this message." };
} }
} }
async function verifyMessage({ folder = "Inbox", uid }) {
try {
const source = await EpMail2.pgpGetMessageSource({ folder, uid });
const raw = Uint8Array.from(atob(source.rawBase64), (char) => char.charCodeAt(0));
if (raw.byteLength > MAX_MESSAGE_BYTES) {
return { failed: true, code: "TOO_LARGE", message: "This signed message is too large to verify." };
}
const entity = splitEntity(raw);
const contentType = entity.headers["content-type"] || "";
const sender = senderFrom(entity.headers);
const data = await store();
const verification = await verificationKeys(data);
if (/^multipart\/signed/i.test(contentType) && parameter(contentType, "protocol").toLowerCase() === "application/pgp-signature") {
const parts = splitSignedMime(raw, parameter(contentType, "boundary"));
if (!parts) return { signatures: [invalidSignature()] };
try {
const result = await ko({
message: await oo({ binary: parts.signed }),
signature: await va({ armoredSignature: parts.signature }),
verificationKeys: verification.map((item) => item.key)
});
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch {
return { signatures: [invalidSignature()] };
}
}
const body = decoder.decode(decodePart(entity.body, entity.headers["content-transfer-encoding"]));
const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0];
if (!armored) return { signatures: [] };
try {
const message = await ho({ cleartextMessage: armored });
const result = await ko({ message, verificationKeys: verification.map((item) => item.key) });
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch {
return { signatures: [invalidSignature()] };
}
} catch (error) {
return { failed: true, code: error.code || "VERIFY_ERROR", message: error.message || "Could not verify this message." };
}
}
const api = { const api = {
platform: "android", platform: "android",
async list() { async list() {
@@ -10413,6 +10582,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
}; };
}, },
decryptMessage, decryptMessage,
verifyMessage,
async getSettings() { async getSettings() {
const data = await store(); const data = await store();
return { cacheMinutes }; return { cacheMinutes };
+127 -15
View File
@@ -118,6 +118,26 @@ function parseInnerMime(bytes) {
return result; return result;
} }
async function attachedPublicKeys(attachments) {
const found = [];
for (const file of attachments || []) {
const type = String(file.contentType || '').toLowerCase();
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue;
try {
const binary = atob(file.contentBase64);
const armoredKey = decoder.decode(Uint8Array.from(binary, char => char.charCodeAt(0))).trim();
if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) ||
/-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue;
const key = await openpgp.readKey({ armoredKey });
await key.getPrimaryUser();
found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
if (found.length === 5) break;
} catch { /* ignore malformed, expired or non-public key attachments */ }
}
return found;
}
function randomBoundary() { function randomBoundary() {
const bytes = crypto.getRandomValues(new Uint8Array(18)); const bytes = crypto.getRandomValues(new Uint8Array(18));
return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`; return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`;
@@ -171,6 +191,70 @@ function toBase64(bytes) {
return btoa(binary); return btoa(binary);
} }
function bytesToLatin1(bytes) {
let text = '';
for (let index = 0; index < bytes.length; index += 0x8000) {
text += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return text;
}
function splitSignedMime(source, boundary) {
if (!boundary || boundary.length > 200) return null;
const text = bytesToLatin1(source);
const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
const marks = [...text.matchAll(delimiter)];
if (marks.length < 3) return null;
const contentAfter = mark => {
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
return lineEnd < 0 ? text.length : lineEnd + 1;
};
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n');
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!signature) return null;
return { signed: Uint8Array.from(signed, char => char.charCodeAt(0) & 255), signature };
}
function senderFrom(headers) {
const value = String(headers.from || '');
return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || '').toLowerCase();
}
function invalidSignature() {
return { status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null,
matchesSender: false, keyChanged: false };
}
async function signatureStatuses(signatures, verification, sender) {
const results = [];
for (const signature of signatures || []) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = verification.find(candidate => candidate.key.getKeys()
.some(key => key.getKeyID().toHex().toUpperCase() === keyId));
let status = 'valid';
try { await signature.verified; }
catch { status = known ? 'invalid' : 'unknown-key'; }
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const matchesSender = Boolean(sender && keyEmails.includes(sender));
const changed = Boolean(sender && verification.some(candidate =>
!candidate.entry.own && candidate.entry.emails?.includes(sender) &&
candidate.entry.fingerprint !== known?.entry.fingerprint));
results.push({
status,
keyId,
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {})
});
}
return results;
}
export function createAndroidPgp({ EpMail, getAccount }) { export function createAndroidPgp({ EpMail, getAccount }) {
let storePromise; let storePromise;
const passphrases = new Map(); const passphrases = new Map();
@@ -351,28 +435,55 @@ export function createAndroidPgp({ EpMail, getAccount }) {
try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); } try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); }
catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; } catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; }
const content = parseInnerMime(decrypted.data); const content = parseInnerMime(decrypted.data);
const signatures = []; const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
for (const item of decrypted.signatures || []) { const attachedKeys = await attachedPublicKeys(content.attachments);
const known = verify.find(candidate => candidate.key.getKeys().some(key => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
let status = 'valid';
try { await item.verified; } catch { status = known ? 'invalid' : 'unknown-key'; }
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || '';
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || '').toLowerCase();
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const changed = Boolean(sender && data.contacts.some(entry => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
const matchesSender = Boolean(sender && keyEmails.includes(sender));
signatures.push({ status, keyId: item.keyID.toHex().toUpperCase(), fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null, email: keyEmails[0] || null, matchesSender, keyChanged: changed,
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {}) });
}
return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html, return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html,
links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null, links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null,
size: content.attachments[0]?.size || '', signatures, attachedKeys: [] }; size: content.attachments[0]?.size || '', signatures, attachedKeys };
} catch (error) { } catch (error) {
return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' }; return { failed: true, code: error.code || 'ERROR', message: error.message || 'Could not decrypt this message.' };
} }
} }
async function verifyMessage({ folder = 'Inbox', uid }) {
try {
const source = await EpMail.pgpGetMessageSource({ folder, uid });
const raw = Uint8Array.from(atob(source.rawBase64), char => char.charCodeAt(0));
if (raw.byteLength > MAX_MESSAGE_BYTES) {
return { failed: true, code: 'TOO_LARGE', message: 'This signed message is too large to verify.' };
}
const entity = splitEntity(raw);
const contentType = entity.headers['content-type'] || '';
const sender = senderFrom(entity.headers);
const data = await store();
const verification = await verificationKeys(data);
if (/^multipart\/signed/i.test(contentType) &&
parameter(contentType, 'protocol').toLowerCase() === 'application/pgp-signature') {
const parts = splitSignedMime(raw, parameter(contentType, 'boundary'));
if (!parts) return { signatures: [invalidSignature()] };
try {
const result = await openpgp.verify({
message: await openpgp.createMessage({ binary: parts.signed }),
signature: await openpgp.readSignature({ armoredSignature: parts.signature }),
verificationKeys: verification.map(item => item.key)
});
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch { return { signatures: [invalidSignature()] }; }
}
const body = decoder.decode(decodePart(entity.body, entity.headers['content-transfer-encoding']));
const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0];
if (!armored) return { signatures: [] };
try {
const message = await openpgp.readCleartextMessage({ cleartextMessage: armored });
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch { return { signatures: [invalidSignature()] }; }
} catch (error) {
return { failed: true, code: error.code || 'VERIFY_ERROR', message: error.message || 'Could not verify this message.' };
}
}
const api = { const api = {
platform: 'android', platform: 'android',
async list() { return (await store()).keys.map(publicInfo); }, async list() { return (await store()).keys.map(publicInfo); },
@@ -440,6 +551,7 @@ export function createAndroidPgp({ EpMail, getAccount }) {
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)) } : null };
}, },
decryptMessage, decryptMessage,
verifyMessage,
async getSettings() { const data = await store(); return { cacheMinutes }; }, async getSettings() { const data = await store(); return { cacheMinutes }; },
async setSettings({ cacheMinutes: value }) { async setSettings({ cacheMinutes: value }) {
const number = Number(value); const number = Number(value);
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE='ep-mail-v18'; const CACHE='ep-mail-v19';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting()))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));
+160
View File
@@ -0,0 +1,160 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const vm = require('node:vm');
const esbuild = require('esbuild');
const openpgp = require('openpgp');
const { simpleParser } = require('mailparser');
const { webcrypto } = require('node:crypto');
global.crypto ||= webcrypto;
global.document ||= { addEventListener() {} };
const bundled = esbuild.buildSync({
entryPoints: [path.join(__dirname, '..', 'scripts', 'android-pgp.js')],
bundle: true,
platform: 'browser',
format: 'iife',
globalName: 'AndroidPgpInteropBundle',
write: false
}).outputFiles[0].text;
vm.runInThisContext(bundled);
const { createAndroidPgp } = global.AndroidPgpInteropBundle;
const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe']
.filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0);
const skip = gpgPath ? false : 'GnuPG is not installed';
const PASSPHRASE = 'Android GnuPG test passphrase';
function makeEndpoint(account) {
const vault = { keys: [], contacts: [], settings: {} };
let messageSource = null;
const EpMail = {
async pgpLoadStore() { return JSON.parse(JSON.stringify(vault)); },
async pgpSaveStore({ store }) { Object.assign(vault, JSON.parse(JSON.stringify(store))); return { ok: true }; },
async pgpGetMessageSource() { return messageSource; }
};
return {
api: createAndroidPgp({ EpMail, getAccount: async () => account }),
setMessage(rawBase64) { messageSource = { rawBase64 }; }
};
}
function setupGpg() {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-android-gnupg-'));
const gpg = (args, input) => {
const result = spawnSync(gpgPath, [
'--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback',
'--passphrase', PASSPHRASE, '--trust-model', 'always', ...args
], { input });
if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`);
return { out: result.stdout, err: result.stderr.toString() };
};
gpg(['--quick-generate-key', 'Gina Gnu <gina@example.test>', 'ed25519', 'cert', 'never']);
const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(
gpg(['--list-keys', '--with-colons', 'gina@example.test']).out.toString()
)?.[1];
if (!fingerprint) throw new Error('Could not find the generated GnuPG test key fingerprint.');
gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']);
gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']);
return { home, fingerprint, gpg };
}
function encryptedMime(from, to, armor) {
const boundary = 'android-gnupg-encrypted';
return Buffer.from([
`From: ${from}`,
`To: ${to}`,
'Subject: Android GnuPG interoperability',
'MIME-Version: 1.0',
`Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`,
'',
`--${boundary}`,
'Content-Type: application/pgp-encrypted',
'',
'Version: 1',
`--${boundary}`,
'Content-Type: application/octet-stream; name="encrypted.asc"',
'',
armor.trim(),
`--${boundary}--`,
''
].join('\r\n'));
}
test('Android OpenPGP PGP/MIME interoperates with GnuPG for send, read, and signature verification', { skip }, async () => {
const { home, fingerprint, gpg } = setupGpg();
try {
const android = makeEndpoint({ email: 'android@example.test', displayName: 'Android User', signature: '' });
const own = await android.api.generate({
name: 'Android User', email: 'android@example.test', passphrase: 'android key test passphrase'
});
const gpgPublic = gpg(['--armor', '--export', 'gina@example.test']).out.toString();
await android.api.addContact({ armoredKey: gpgPublic });
gpg(['--import'], Buffer.from(await android.api.exportPublic(own.key.fingerprint)));
const outgoing = await android.api.buildOutgoing({
to: 'Gina Gnu <gina@example.test>',
cc: '',
subject: 'Android to GnuPG',
text: 'Encrypted and signed from the Android OpenPGP module',
messageId: '<android-to-gnupg@example.test>',
pgp: { encrypt: true, sign: true, passphrase: 'android key test passphrase' },
attachments: []
});
const outboundText = Buffer.from(outgoing.rawBase64, 'base64').toString('utf8');
const outboundArmor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(outboundText)?.[0];
assert.ok(outboundArmor, 'Android output should contain an armored encrypted message');
const decrypted = gpg(['--decrypt'], Buffer.from(outboundArmor));
assert.match((await simpleParser(decrypted.out)).text, /Encrypted and signed from the Android OpenPGP module/);
assert.match(decrypted.err, /Good signature from/);
const incomingInner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nSigned and encrypted by GnuPG\r\n');
const incomingArmor = gpg([
'--armor', '--encrypt', '--sign', '--local-user', 'gina@example.test', '--recipient', 'android@example.test'
], incomingInner).out.toString();
android.setMessage(encryptedMime('Gina Gnu <gina@example.test>', 'android@example.test', incomingArmor).toString('base64'));
const opened = await android.api.decryptMessage({ folder: 'Inbox', uid: 11, passphrase: 'android key test passphrase' });
assert.equal(opened.ok, true, opened.message);
assert.deepEqual(opened.body, ['Signed and encrypted by GnuPG']);
assert.equal(opened.signatures[0].status, 'valid');
assert.equal(opened.signatures[0].matchesSender, true);
const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nGnuPG detached signed body';
const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.test'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim();
const signedBoundary = 'android-gnupg-signed';
const signedMime = Buffer.from([
'From: Gina Gnu <gina@example.test>',
'To: android@example.test',
'MIME-Version: 1.0',
`Content-Type: multipart/signed; protocol="application/pgp-signature"; boundary="${signedBoundary}"`,
'',
`--${signedBoundary}`,
signedPart,
`--${signedBoundary}`,
'Content-Type: application/pgp-signature',
'',
detached,
`--${signedBoundary}--`,
''
].join('\r\n'));
android.setMessage(signedMime.toString('base64'));
const signedMimeResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 12 });
assert.equal(signedMimeResult.signatures[0].status, 'valid');
assert.equal(signedMimeResult.signatures[0].matchesSender, true);
const clearSigned = gpg(['--clearsign', '--local-user', 'gina@example.test'], Buffer.from('GnuPG clear-signed body\n')).out.toString();
const clearSource = Buffer.from(
`From: Gina Gnu <gina@example.test>\r\nTo: android@example.test\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${clearSigned}\r\n`
);
android.setMessage(clearSource.toString('base64'));
const clearResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 13 });
assert.equal(clearResult.signatures[0].status, 'valid');
assert.equal(clearResult.signatures[0].matchesSender, true);
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
});
+93 -1
View File
@@ -4,6 +4,7 @@ const path = require('node:path');
const vm = require('node:vm'); const vm = require('node:vm');
const esbuild = require('esbuild'); const esbuild = require('esbuild');
const { webcrypto } = require('node:crypto'); const { webcrypto } = require('node:crypto');
const openpgp = require('openpgp');
global.crypto ||= webcrypto; global.crypto ||= webcrypto;
global.document ||= { addEventListener() {} }; global.document ||= { addEventListener() {} };
@@ -37,15 +38,20 @@ function makeEndpoint(account) {
test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => { test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' }); const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' }); const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const thirdParty = makeEndpoint({ email: 'charlie@example.test', displayName: 'Charlie', signature: '' });
const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' }); const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' }); const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
const charlie = await thirdParty.api.generate({ name: 'Charlie', email: 'charlie@example.test', passphrase: 'charlie test passphrase' });
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) }); await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) }); await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) });
const built = await sender.api.buildOutgoing({ const built = await sender.api.buildOutgoing({
to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android', to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' }, messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
attachments: [{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') }] attachments: [
{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') },
{ filename: 'charlie.asc', contentType: 'application/pgp-keys', contentBase64: Buffer.from(await thirdParty.api.exportPublic(charlie.key.fingerprint)).toString('base64') }
]
}); });
assert.ok(built.rawBase64); assert.ok(built.rawBase64);
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8'); const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
@@ -62,6 +68,8 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke
assert.deepEqual(opened.body, ['hello from Android']); assert.deepEqual(opened.body, ['hello from Android']);
assert.equal(opened.attachments[0].filename, 'note.txt'); assert.equal(opened.attachments[0].filename, 'note.txt');
assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment'); assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment');
assert.equal(opened.attachedKeys[0].fingerprint, charlie.key.fingerprint);
assert.deepEqual(opened.attachedKeys[0].emails, ['charlie@example.test']);
assert.equal(opened.signatures[0].status, 'valid'); assert.equal(opened.signatures[0].status, 'valid');
await recipient.api.setSettings({ cacheMinutes: 0 }); await recipient.api.setSettings({ cacheMinutes: 0 });
assert.equal((await recipient.api.getSettings()).cacheMinutes, 0); assert.equal((await recipient.api.getSettings()).cacheMinutes, 0);
@@ -75,3 +83,87 @@ test('Android OpenPGP refuses encryption when any recipient key is missing', asy
to: 'nobody@example.test', text: 'must not escape as plaintext', pgp: { encrypt: true }, attachments: [] to: 'nobody@example.test', text: 'must not escape as plaintext', pgp: { encrypt: true }, attachments: []
}), error => error.code === 'NO_RECIPIENT_KEY'); }), error => error.code === 'NO_RECIPIENT_KEY');
}); });
test('Android verifies PGP/MIME signed-only and clear-signed mail', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) });
const signedMime = await sender.api.buildOutgoing({
to: 'Bob <bob@example.test>', cc: '', subject: 'Signed note', text: 'signed MIME body',
pgp: { encrypt: false, sign: true, passphrase: 'alice test passphrase' }, attachments: []
});
recipient.setMessage({ rawBase64: signedMime.rawBase64 });
const mimeResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 8 });
assert.equal(mimeResult.signatures[0].status, 'valid');
assert.equal(mimeResult.signatures[0].matchesSender, true);
const protectedPrivateKey = await sender.api.exportPrivate(created.key.fingerprint, 'alice test passphrase');
const signingKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: protectedPrivateKey }),
passphrase: 'alice test passphrase'
});
const cleartext = await openpgp.createCleartextMessage({ text: 'clear-signed body' });
const clearSigned = await openpgp.sign({ message: cleartext, signingKeys: signingKey });
const raw = [
'From: Alice <alice@example.test>',
'To: Bob <bob@example.test>',
'Subject: Clear-signed note',
'Content-Type: text/plain; charset=utf-8',
'',
clearSigned,
''
].join('\r\n');
recipient.setMessage({ rawBase64: Buffer.from(raw).toString('base64') });
const clearResult = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 9 });
assert.equal(clearResult.signatures[0].status, 'valid');
assert.equal(clearResult.signatures[0].matchesSender, true);
});
test('Android marks a damaged PGP/MIME signature invalid', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) });
const signed = await sender.api.buildOutgoing({
to: 'bob@example.test', subject: 'Signed', text: 'change me',
pgp: { sign: true, passphrase: 'alice test passphrase' }, attachments: []
});
const raw = Buffer.from(signed.rawBase64, 'base64').toString('utf8');
const armor = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(raw)?.[0];
const signatureLine = armor?.split(/\r?\n/).find(line => /^[A-Za-z0-9+/]{20,}$/.test(line));
assert.ok(signatureLine, 'signed MIME output should contain an armored signature');
const tampered = raw.replace(signatureLine, `${signatureLine[0] === 'A' ? 'B' : 'A'}${signatureLine.slice(1)}`);
recipient.setMessage({ rawBase64: Buffer.from(tampered).toString('base64') });
const result = await recipient.api.verifyMessage({ folder: 'Inbox', uid: 10 });
assert.equal(result.signatures[0].status, 'invalid');
});
test('Android rejects tampered, malformed, and oversized encrypted input', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
const built = await sender.api.buildOutgoing({
to: 'bob@example.test', subject: 'Encrypted test', text: 'tamper test',
pgp: { encrypt: true }, attachments: []
});
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
const armor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(raw)?.[0];
assert.ok(armor);
const lines = armor.split(/\r?\n/);
const armorLineIndex = lines.findIndex(line => /^[A-Za-z0-9+/]{20,}$/.test(line));
assert.notEqual(armorLineIndex, -1);
lines[armorLineIndex] = `${lines[armorLineIndex][0] === 'A' ? 'B' : 'A'}${lines[armorLineIndex].slice(1)}`;
recipient.setMessage({ rawBase64: Buffer.from(raw.replace(armor, lines.join('\r\n'))).toString('base64') });
assert.equal((await recipient.api.decryptMessage({ uid: 20, passphrase: 'bob test passphrase' })).code, 'CORRUPT');
recipient.setMessage({ rawBase64: Buffer.from(
'From: Alice <alice@example.test>\r\nContent-Type: multipart/encrypted; boundary="broken"\r\n\r\nnot a valid PGP payload'
).toString('base64') });
assert.equal((await recipient.api.decryptMessage({ uid: 21, passphrase: 'bob test passphrase' })).code, 'CORRUPT');
recipient.setMessage({ rawBase64: 'A'.repeat(35_000_000) });
assert.equal((await recipient.api.decryptMessage({ uid: 22, passphrase: 'bob test passphrase' })).code, 'TOO_LARGE');
});
+23
View File
@@ -10,12 +10,14 @@ const app = fs.readFileSync(path.join(root, 'app.js'), 'utf8');
const transport = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailTransport.kt'), 'utf8'); const transport = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailTransport.kt'), 'utf8');
const mainActivity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8'); const mainActivity = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'MainActivity.java'), 'utf8');
const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8'); const plugin = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'EpMailPlugin.kt'), 'utf8');
const vault = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidAccountVault.kt'), 'utf8');
const androidMailService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8'); const androidMailService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidMailService.kt'), 'utf8');
const androidPgpPolicy = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpPolicy.kt'), 'utf8'); const androidPgpPolicy = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpPolicy.kt'), 'utf8');
const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpConfirmationGate.kt'), 'utf8'); const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpConfirmationGate.kt'), 'utf8');
const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8'); const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8'); const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8');
const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8'); const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8');
const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8')); const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
@@ -66,6 +68,15 @@ test('Android app lock is native-enforced and requires a secure device credentia
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/); assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
assert.match(mainActivity, /createConfirmDeviceCredentialIntent/); assert.match(mainActivity, /createConfirmDeviceCredentialIntent/);
assert.match(mainActivity, /android\.R\.id\.content/); assert.match(mainActivity, /android\.R\.id\.content/);
assert.match(mainActivity, /settings\.setAllowFileAccess\(false\)/);
assert.match(mainActivity, /settings\.setAllowContentAccess\(false\)/);
assert.match(mainActivity, /setJavaScriptCanOpenWindowsAutomatically\(false\)/);
assert.match(mainActivity, /MIXED_CONTENT_NEVER_ALLOW/);
assert.match(mainActivity, /setWebContentsDebuggingEnabled\(BuildConfig\.DEBUG\)/);
assert.match(mainActivity, /addFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
assert.match(mainActivity, /clearFlags\(WindowManager\.LayoutParams\.FLAG_SECURE\)/);
assert.match(mainActivity, /createVaultRecoveryOverlay/);
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
assert.match(androidBridge, /getAppLockSettings/); assert.match(androidBridge, /getAppLockSettings/);
assert.match(androidBridge, /setAppLockEnabled/); assert.match(androidBridge, /setAppLockEnabled/);
assert.match(productivity, /Lock when leaving ep-mail/); assert.match(productivity, /Lock when leaving ep-mail/);
@@ -88,6 +99,10 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data',
assert.match(androidPgp, /curve25519Legacy/); assert.match(androidPgp, /curve25519Legacy/);
assert.match(androidPgp, /multipart\/encrypted/); assert.match(androidPgp, /multipart\/encrypted/);
assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/); assert.match(androidPgp, /MAX_MESSAGE_BYTES = 25 \* 1024 \* 1024/);
assert.match(androidPgp, /async function verifyMessage/);
assert.match(androidPgp, /readCleartextMessage/);
assert.match(androidPgp, /readSignature/);
assert.match(pgpMailUi, /message\.signed/);
assert.match(androidBridge, /buildOutgoing\(message\)/); assert.match(androidBridge, /buildOutgoing\(message\)/);
assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/); assert.match(androidBridge, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/);
assert.match(androidMailService, /validateOpenPgpMime\(message\)/); assert.match(androidMailService, /validateOpenPgpMime\(message\)/);
@@ -95,3 +110,11 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data',
assert.match(androidMailService, /"send" -> send\(account, data\)/); assert.match(androidMailService, /"send" -> send\(account, data\)/);
assert.match(androidMailService, /private fun isEncryptedMessage/); assert.match(androidMailService, /private fun isEncryptedMessage/);
}); });
test('Android vault refuses to replace a missing key when encrypted data exists', () => {
assert.match(vault, /shouldCreateKey\(hasEncryptedData\)/);
assert.match(vault, /MISSING_KEY_MESSAGE/);
assert.match(mainActivity, /AndroidAccountVault\.INSTANCE\.read\(\)/);
assert.match(mainActivity, /Saved data could not be opened/);
assert.match(mainActivity, /ACTION_APPLICATION_DETAILS_SETTINGS/);
});
+1
View File
@@ -80,6 +80,7 @@ test('account and snooze UI consume the explicit mail API instead of selected le
const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8'); const shortcutsUi = fs.readFileSync(path.join(root, 'shortcuts.js'), 'utf8');
const productivityUi = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8'); const productivityUi = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
assert.match(accountUi, /window\.epMailFeatures\.mail/); assert.match(accountUi, /window\.epMailFeatures\.mail/);
assert.match(accountUi, /Downloaded attachment files and OpenPGP keys are kept/);
assert.match(attachmentUi, /^\(\(\) => \{/); assert.match(attachmentUi, /^\(\(\) => \{/);
assert.match(snoozeUi, /window\.epMailFeatures\.mail/); assert.match(snoozeUi, /window\.epMailFeatures\.mail/);
assert.match(snoozeUi, /^\(\(\) => \{/); assert.match(snoozeUi, /^\(\(\) => \{/);
+1 -1
View File
@@ -21,7 +21,7 @@ async function openAccountManager(){
const editButton=event.target.closest('[data-edit-account]'); const editButton=event.target.closest('[data-edit-account]');
if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return} if(editButton){const account=accounts.find(item=>item.id===editButton.dataset.editAccount);if(account)accountMailUi.openMailAccount(account);return}
const removeButton=event.target.closest('[data-remove-account]'); const removeButton=event.target.closest('[data-remove-account]');
if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return} if(removeButton){const email=removeButton.closest('.account-row').querySelector('strong').textContent;if(!confirm(`Remove ${email} from this device?\n\nIts cached mail, drafts and pending sends will be removed. Downloaded attachment files and OpenPGP keys are kept; delete those separately if you want to remove them too.`))return;removeButton.disabled=true;try{const result=await window.daybreakMail.removeAccount(removeButton.dataset.removeAccount);const active=result.accounts.find(account=>account.id===result.activeId)||null;accountMailUi.connectedAccount=active;if(active){accountMailUi.updateAccountCard(active);close();accountMailUi.state.activeFolder='Inbox';accountMailUi.setPageOffset(0);await accountMailUi.syncMailbox(false,{offset:0})}else{accountMailUi.updateAccountCard({email:'Connect a mailbox',imapHost:''});accountMailUi.state.messages.splice(0,accountMailUi.state.messages.length);accountMailUi.renderList();accountMailUi.select('#reader-pane').innerHTML=accountMailUi.emptyReader();accountMailUi.toast('Mail account removed');openAccountManager()}}catch(error){accountMailUi.toast(error.message||'Could not remove the account');removeButton.disabled=false}return}
}; };
}catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')} }catch(error){accountMailUi.toast(error.message||'Could not load mail accounts')}
} }
+38 -14
View File
@@ -70,12 +70,18 @@ function pgpRenderReaderState(message) {
if (!header) return; if (!header) return;
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove()); reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
let html = ''; let html = '';
if (message.encrypted && !message.pgpDecrypted) { if (message.encrypted && !message.pgpDecrypted) {
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`; html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
} else if (message.encrypted) { } else if (message.encrypted) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true); html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.pgpSignatures) { } else if (message.signed && Array.isArray(message.pgpSignatures)) {
html = pgpSignatureHtml(message.pgpSignatures, false); html = pgpSignatureHtml(message.pgpSignatures, false);
} else if (message.signed && message.pgpVerifyFailed) {
html = `<section class="pgp-status pgp-warn" role="status"><strong>Could not check the OpenPGP signature</strong><span>${escapePgpMailUi(message.pgpVerifyFailed)}</span></section>`;
} else if (message.signed) {
html = '<section class="pgp-status pgp-warn" role="status"><strong>Checking OpenPGP signature…</strong><span>Do not rely on this message until verification completes.</span></section>';
} else if (message.pgpSignatures) {
html = pgpSignatureHtml(message.pgpSignatures, false);
} }
const keys = message.pgpResult?.attachedKeys || []; const keys = message.pgpResult?.attachedKeys || [];
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join('')); header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${escapePgpMailUi(key.emails.join(', ') || 'unknown address')} · ${escapePgpMailUi(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
@@ -86,7 +92,7 @@ function pgpRenderReaderState(message) {
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true); if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
} }
async function pgpUnlockMessage(message, interactive) { async function pgpUnlockMessage(message, interactive) {
let passphrase = null; let passphrase = null;
for (let attempt = 0; attempt < 3; attempt += 1) { for (let attempt = 0; attempt < 3; attempt += 1) {
let result; let result;
@@ -114,18 +120,36 @@ async function pgpUnlockMessage(message, interactive) {
if (text) text.textContent = result.message; if (text) text.textContent = result.message;
else toastPgpMailUi(result.message); else toastPgpMailUi(result.message);
return; return;
} }
} }
async function pgpVerifyMessage(message) {
try {
const result = await pgpApi().verifyMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid });
if (result.failed) message.pgpVerifyFailed = result.message || 'The signature could not be checked.';
else {
message.pgpSignatures = result.signatures || [];
message.pgpVerifyFailed = null;
}
} catch (error) {
message.pgpVerifyFailed = error.message || 'The signature could not be checked.';
}
if (pgpMailUi.state.activeMessage === message.id) pgpRenderReaderState(message);
}
pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) { pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
baseOpenMessage(id); baseOpenMessage(id);
const message = pgpMailUi.state.messages.find(item => item.id === id); const message = pgpMailUi.state.messages.find(item => item.id === id);
if (!message || !pgpApi()) return; if (!message || !pgpApi()) return;
pgpRenderReaderState(message); pgpRenderReaderState(message);
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) { if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
message.pgpAutoTried = true; message.pgpAutoTried = true;
void pgpUnlockMessage(message, false); void pgpUnlockMessage(message, false);
} }
if (!message.encrypted && message.signed && typeof pgpApi().verifyMessage === 'function' && !message.pgpVerifyTried) {
message.pgpVerifyTried = true;
void pgpVerifyMessage(message);
}
}); });
// Compose: encrypt/sign options. // Compose: encrypt/sign options.
+196 -26
View File
@@ -5738,6 +5738,7 @@
super(e2, t2); super(e2, t2);
} }
}; };
var ka = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var Ea = class { var Ea = class {
constructor(e2) { constructor(e2) {
this.packets = e2 || new Gs(); this.packets = e2 || new Gs();
@@ -5753,6 +5754,22 @@
return this.packets.map(((e2) => e2.issuerKeyID)); return this.packets.map(((e2) => e2.issuerKeyID));
} }
}; };
async function va({ armoredSignature: e2, binarySignature: t2, config: r2, ...n2 }) {
r2 = { ...F, ...r2 };
let i2 = e2 || t2;
if (!i2) throw Error("readSignature: must pass options object containing `armoredSignature` or `binarySignature`");
if (e2 && !N.isString(e2)) throw Error("readSignature: options.armoredSignature must be a string");
if (t2 && !N.isUint8Array(t2)) throw Error("readSignature: options.binarySignature must be a Uint8Array");
const s2 = Object.keys(n2);
if (s2.length > 0) throw Error("Unknown option: " + s2.join(", "));
if (e2) {
const { type: e3, data: t3 } = await $(i2);
if (e3 !== R.armor.signature) throw Error("Armored text not of type signature");
i2 = t3;
}
const a2 = await Gs.fromBinary(i2, ka, r2);
return new Ea(a2);
}
async function Ia(e2, t2) { async function Ia(e2, t2) {
const r2 = new wa(e2.date, t2); const r2 = new wa(e2.date, t2);
return r2.packets = null, r2.algorithm = R.write(R.publicKey, e2.algorithm), await r2.generate(e2.rsaBits, e2.curve), await r2.computeFingerprintAndKeyID(), r2; return r2.packets = null, r2.algorithm = R.write(R.publicKey, e2.algorithm), await r2.generate(e2.rsaBits, e2.curve), await r2.computeFingerprintAndKeyID(), r2;
@@ -6874,6 +6891,7 @@
const f2 = new no(h2); const f2 = new no(h2);
return f2.fromStream = c2, f2; return f2.fromStream = c2, f2;
} }
var co = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var uo = class _uo { var uo = class _uo {
constructor(e2, t2) { constructor(e2, t2) {
if (this.text = N.removeTrailingSpaces(e2).replace(/\r?\n/g, "\r\n"), t2 && !(t2 instanceof Ea)) throw Error("Invalid signature input"); if (this.text = N.removeTrailingSpaces(e2).replace(/\r?\n/g, "\r\n"), t2 && !(t2 instanceof Ea)) throw Error("Invalid signature input");
@@ -6903,6 +6921,38 @@
return ee(R.armor.signed, r2, void 0, void 0, void 0, t2, e2); return ee(R.armor.signed, r2, void 0, void 0, void 0, t2, e2);
} }
}; };
async function ho({ cleartextMessage: e2, config: t2, ...r2 }) {
if (t2 = { ...F, ...t2 }, !e2) throw Error("readCleartextMessage: must pass options object containing `cleartextMessage`");
if (!N.isString(e2)) throw Error("readCleartextMessage: options.cleartextMessage must be a string");
const n2 = Object.keys(r2);
if (n2.length > 0) throw Error("Unknown option: " + n2.join(", "));
const i2 = await $(e2);
if (i2.type !== R.armor.signed) throw Error("No cleartext signed message.");
const s2 = await Gs.fromBinary(i2.data, co, t2);
!(function(e3, t3) {
const r3 = function(e4) {
const r4 = (e5) => (t4) => e5.hashAlgorithm === t4;
for (let n4 = 0; n4 < t3.length; n4++) if (t3[n4].constructor.tag === R.packet.signature && !e4.some(r4(t3[n4]))) return false;
return true;
}, n3 = [];
if (e3.forEach(((e4) => {
const t4 = e4.match(/^Hash: (.+)$/);
if (!t4) throw Error('Only "Hash" header allowed in cleartext signed message');
{
const e5 = t4[1].replace(/\s/g, "").split(",").map(((e6) => {
try {
return R.write(R.hash, e6.toLowerCase());
} catch {
throw Error("Unknown hash algorithm in armor header: " + e6.toLowerCase());
}
}));
n3.push(...e5);
}
})), n3.length && !r3(n3)) throw Error("Hash algorithm mismatch in armor header and signature");
})(i2.headers, s2);
const a2 = new Ea(s2);
return new uo(i2.text, a2);
}
async function lo({ userIDs: e2 = [], passphrase: t2, type: r2, curve: n2, rsaBits: i2 = 4096, keyExpirationTime: s2 = 0, date: a2 = /* @__PURE__ */ new Date(), subkeys: o2 = [{}], format: c2 = "armored", signatureNotations: u2 = [], config: h2, ...f2 }) { async function lo({ userIDs: e2 = [], passphrase: t2, type: r2, curve: n2, rsaBits: i2 = 4096, keyExpirationTime: s2 = 0, date: a2 = /* @__PURE__ */ new Date(), subkeys: o2 = [{}], format: c2 = "armored", signatureNotations: u2 = [], config: h2, ...f2 }) {
Do(h2 = { ...F, ...h2 }), r2 || n2 ? (r2 = r2 || "ecc", n2 = n2 || "curve25519Legacy") : (r2 = h2.v6Keys ? "curve25519" : "ecc", n2 = "curve25519Legacy"), e2 = Uo(e2), u2 = Uo(u2); Do(h2 = { ...F, ...h2 }), r2 || n2 ? (r2 = r2 || "ecc", n2 = n2 || "curve25519Legacy") : (r2 = h2.v6Keys ? "curve25519" : "ecc", n2 = "curve25519Legacy"), e2 = Uo(e2), u2 = Uo(u2);
const l2 = Object.keys(f2); const l2 = Object.keys(f2);
@@ -7011,6 +7061,23 @@
throw N.wrapError("Error signing message", e3); throw N.wrapError("Error signing message", e3);
} }
} }
async function ko({ message: e2, verificationKeys: t2, expectSigned: r2 = false, format: n2 = "utf8", signature: i2 = null, date: s2 = /* @__PURE__ */ new Date(), config: a2, ...o2 }) {
if (Do(a2 = { ...F, ...a2 }), So(e2), t2 = Uo(t2), o2.publicKeys) throw Error("The `publicKeys` option has been removed from openpgp.verify, pass `verificationKeys` instead");
const c2 = Object.keys(o2);
if (c2.length > 0) throw Error("Unknown option: " + c2.join(", "));
if (e2 instanceof uo && "binary" === n2) throw Error("Can't return cleartext message data as binary");
if (e2 instanceof uo && i2) throw Error("Can't verify detached cleartext signature");
try {
const o3 = {};
if (o3.signatures = i2 ? await e2.verifyDetached(i2, t2, s2, a2) : await e2.verify(t2, s2, a2), o3.data = "binary" === n2 ? e2.getLiteralData() : e2.getText(), e2.fromStream && !i2 && xo(o3, .../* @__PURE__ */ new Set([e2, e2.unwrapCompressed()])), r2) {
if (0 === o3.signatures.length) throw Error("Message is not signed");
o3.data = A([o3.data, P((async () => (await N.anyPromise(o3.signatures.map(((e3) => e3.verified))), "binary" === n2 ? new Uint8Array() : "")))]);
}
return o3.data = await Po(o3.data), o3;
} catch (e3) {
throw N.wrapError("Error verifying signed message", e3);
}
}
function Bo(e2) { function Bo(e2) {
if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message"); if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message");
} }
@@ -9896,6 +9963,25 @@
visit(bytes); visit(bytes);
return result; return result;
} }
async function attachedPublicKeys(attachments) {
const found = [];
for (const file of attachments || []) {
const type = String(file.contentType || "").toLowerCase();
if (type !== "application/pgp-keys" && !/\.asc$/i.test(file.filename || "")) continue;
if (!file.contentBase64 || Number(file.size) > MAX_KEY_LENGTH || file.contentBase64.length > MAX_KEY_LENGTH * 2) continue;
try {
const binary = atob(file.contentBase64);
const armoredKey = decoder.decode(Uint8Array.from(binary, (char) => char.charCodeAt(0))).trim();
if (!/-----BEGIN PGP PUBLIC KEY BLOCK-----/.test(armoredKey) || /-----BEGIN PGP PRIVATE KEY BLOCK-----/.test(armoredKey) || armoredKey.length > MAX_KEY_LENGTH) continue;
const key = await Ja({ armoredKey });
await key.getPrimaryUser();
found.push({ armoredKey: key.armor(), fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
if (found.length === 5) break;
} catch {
}
}
return found;
}
function randomBoundary() { function randomBoundary() {
const bytes = crypto.getRandomValues(new Uint8Array(18)); const bytes = crypto.getRandomValues(new Uint8Array(18));
return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`; return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`;
@@ -9961,6 +10047,72 @@ ${parts.join("")}`;
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768)); for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
return btoa(binary); return btoa(binary);
} }
function bytesToLatin1(bytes) {
let text = "";
for (let index = 0; index < bytes.length; index += 32768) {
text += String.fromCharCode(...bytes.subarray(index, index + 32768));
}
return text;
}
function splitSignedMime(source, boundary) {
if (!boundary || boundary.length > 200) return null;
const text = bytesToLatin1(source);
const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, "g");
const marks = [...text.matchAll(delimiter)];
if (marks.length < 3) return null;
const contentAfter = (mark) => {
const lineEnd = text.indexOf("\n", mark.index + mark[0].length);
return lineEnd < 0 ? text.length : lineEnd + 1;
};
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, "\r\n");
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!signature) return null;
return { signed: Uint8Array.from(signed, (char) => char.charCodeAt(0) & 255), signature };
}
function senderFrom(headers) {
const value = String(headers.from || "");
return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || "").toLowerCase();
}
function invalidSignature() {
return {
status: "invalid",
keyId: "",
fingerprint: null,
trust: null,
email: null,
matchesSender: false,
keyChanged: false
};
}
async function signatureStatuses(signatures, verification, sender) {
const results = [];
for (const signature of signatures || []) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = verification.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === keyId));
let status = "valid";
try {
await signature.verified;
} catch {
status = known ? "invalid" : "unknown-key";
}
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const matchesSender = Boolean(sender && keyEmails.includes(sender));
const changed = Boolean(sender && verification.some((candidate) => !candidate.entry.own && candidate.entry.emails?.includes(sender) && candidate.entry.fingerprint !== known?.entry.fingerprint));
results.push({
status,
keyId,
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {}
});
}
return results;
}
function createAndroidPgp({ EpMail: EpMail2, getAccount }) { function createAndroidPgp({ EpMail: EpMail2, getAccount }) {
let storePromise; let storePromise;
const passphrases = /* @__PURE__ */ new Map(); const passphrases = /* @__PURE__ */ new Map();
@@ -10229,31 +10381,8 @@ ${body}`);
return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." }; return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." };
} }
const content = parseInnerMime(decrypted.data); const content = parseInnerMime(decrypted.data);
const signatures = []; const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
for (const item of decrypted.signatures || []) { const attachedKeys = await attachedPublicKeys(content.attachments);
const known = verify.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
let status = "valid";
try {
await item.verified;
} catch {
status = known ? "invalid" : "unknown-key";
}
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || "";
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || "").toLowerCase();
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const changed = Boolean(sender && data.contacts.some((entry) => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
const matchesSender = Boolean(sender && keyEmails.includes(sender));
signatures.push({
status,
keyId: item.keyID.toHex().toUpperCase(),
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {}
});
}
return { return {
ok: true, ok: true,
body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [],
@@ -10263,12 +10392,52 @@ ${body}`);
attachment: content.attachments[0]?.filename || null, attachment: content.attachments[0]?.filename || null,
size: content.attachments[0]?.size || "", size: content.attachments[0]?.size || "",
signatures, signatures,
attachedKeys: [] attachedKeys
}; };
} catch (error) { } catch (error) {
return { failed: true, code: error.code || "ERROR", message: error.message || "Could not decrypt this message." }; return { failed: true, code: error.code || "ERROR", message: error.message || "Could not decrypt this message." };
} }
} }
async function verifyMessage({ folder = "Inbox", uid }) {
try {
const source = await EpMail2.pgpGetMessageSource({ folder, uid });
const raw = Uint8Array.from(atob(source.rawBase64), (char) => char.charCodeAt(0));
if (raw.byteLength > MAX_MESSAGE_BYTES) {
return { failed: true, code: "TOO_LARGE", message: "This signed message is too large to verify." };
}
const entity = splitEntity(raw);
const contentType = entity.headers["content-type"] || "";
const sender = senderFrom(entity.headers);
const data = await store();
const verification = await verificationKeys(data);
if (/^multipart\/signed/i.test(contentType) && parameter(contentType, "protocol").toLowerCase() === "application/pgp-signature") {
const parts = splitSignedMime(raw, parameter(contentType, "boundary"));
if (!parts) return { signatures: [invalidSignature()] };
try {
const result = await ko({
message: await oo({ binary: parts.signed }),
signature: await va({ armoredSignature: parts.signature }),
verificationKeys: verification.map((item) => item.key)
});
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch {
return { signatures: [invalidSignature()] };
}
}
const body = decoder.decode(decodePart(entity.body, entity.headers["content-transfer-encoding"]));
const armored = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(body)?.[0];
if (!armored) return { signatures: [] };
try {
const message = await ho({ cleartextMessage: armored });
const result = await ko({ message, verificationKeys: verification.map((item) => item.key) });
return { signatures: await signatureStatuses(result.signatures, verification, sender) };
} catch {
return { signatures: [invalidSignature()] };
}
} catch (error) {
return { failed: true, code: error.code || "VERIFY_ERROR", message: error.message || "Could not verify this message." };
}
}
const api = { const api = {
platform: "android", platform: "android",
async list() { async list() {
@@ -10413,6 +10582,7 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
}; };
}, },
decryptMessage, decryptMessage,
verifyMessage,
async getSettings() { async getSettings() {
const data = await store(); const data = await store();
return { cacheMinutes }; return { cacheMinutes };
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE='ep-mail-v18'; const CACHE='ep-mail-v19';
const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg']; const FILES=['./','./index.html','./styles.css','./branding.css','./renderer-state.js','./mail-content-security.js','./renderer-mail-api.js','./app.js','./platform-bridge-loader.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting()))); self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES)).then(()=>self.skipWaiting())));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim()))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k)))).then(()=>self.clients.claim())));