Compare commits

..
3 Commits
33 changed files with 3716 additions and 1869 deletions
+18 -17
View File
@@ -7,18 +7,18 @@ Related: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md), [SECURITY_REVIEW.md](./SECU
## Implementation progress (2026-11-03)
- **Phase 0 — Baseline:** The merged release manifest and core WebView/network settings have now been reviewed and hardened. TLS certificate integration tests, the complete plugin audit, and a production-signed APK review remain open, so the Phase 0 release gate is not closed.
- **Phase 1 — Local data/privacy:** Notification privacy, immediate background app locking, `FLAG_SECURE` while locked, account-removal disclosure, and a fail-closed missing-key recovery screen are implemented. Vault lifecycle, complete deletion semantics, and app-lock lifecycle/biometric follow-up remain open.
- **Phase 2 — Android OpenPGP:** Experimental test implementation is present. It is not security-reviewed or release-complete.
- **Phase 3 — WebView/bridge:** Important protections are implemented; complete bridge review and device/content testing remain open.
- **Phase 1 — Local data/privacy:** Notification privacy, configurable app locking, `FLAG_SECURE` from backgrounding, account-removal disclosure, explicit full local-data deletion, and fail-closed missing-key recovery are implemented. Vault lifecycle and automated device/lifecycle tests remain open.
- **Phase 2 — Android OpenPGP:** The experimental implementation now includes optional authentication-bound biometric/device-credential release of PGP passphrases, with passphrase fallback and invalidation recovery. It is not security-reviewed or release-complete.
- **Phase 3 — WebView/bridge:** CSP, navigation, sanitizer, and plugin-surface regression checks are automated; complete bridge review and device/content testing remain open.
- **Phase 4 — Assurance:** Open; independent review, release assurance, and vulnerability/maintenance work remain.
Tracking legend: `[x]` implemented for the stated item; `[~]` partially implemented, with the remaining work stated beside it; `[ ]` not yet complete. A checked implementation item does **not** mean its phase's exit criteria or release gate have passed.
OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, and on-demand PGP/MIME or inline-encrypted-message decryption. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sending when keys exist or encryption was requested. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**.
OpenPGP.js 6.3.2 is bundled for Android testing. The test implementation stores passphrase-protected keys and public contacts in the existing Keystore-encrypted vault; supports key generation/import/export, contact trust controls, PGP/MIME encrypt/sign, on-demand PGP/MIME or inline-encrypted-message decryption, and verification of signed-only PGP/MIME and clear-signed messages. Encrypted sends are converted to ciphertext before native sending or offline queueing; decrypted content is held in renderer memory only. Native prompts cover trust elevation, key replacement, and plaintext sends when keys exist or encryption was requested; every renderer-produced raw MIME send also requires a native confirmation because the native layer cannot cryptographically verify its encryption. Key-server lookup is disabled, and PGP/MIME messages are capped at 25 MiB. This work was implemented to enable testing before the independent review gate was satisfied; it is **not approved for sensitive or production use**.
**Validation evidence:** DAV URL, attachment-name, notification privacy, Android OpenPGP policy decisions, one-shot confirmation callbacks, and the missing-vault-key policy have Android unit tests. The app lock was exercised on an emulator with a device PIN, including background lock/unlock; with the lock active, emulator screenshots were fully obscured, and unlocking/turning the setting off restored the app. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were exercised on an emulator; trust cancellation left trust unchanged, trust confirmation persisted, and plaintext cancellation returned `PLAINTEXT_CANCELLED`. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Current validation: 153 Node tests and 21 Android unit tests pass; the Android debug build and release-manifest task succeed. Device testing of vault-corruption/key-loss recovery, invalid-certificate integration tests, production-signed APK review, and automated instrumentation of the actual confirmation dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android.
**Validation evidence:** DAV URL, attachment-name, notification privacy, app-lock delay policy, app-owned Downloads selection, Android OpenPGP policy decisions, unverified-recipient confirmation, raw-MIME native warning policy, one-shot confirmation callbacks, bounded preview reads, and the missing-vault-key policy have Android unit tests. The latest run passed all 162 Node tests and all 26 Android unit tests; debug APK assembly and the release-manifest processing task also succeeded. The Android PGP module's Node-harness tests cover encrypted-message flows, passphrase-verified biometric unlock, invalidation error propagation, and manual passphrase recovery; they do not exercise Android Keystore prompts or OS-level invalidation. The app lock was previously exercised on an emulator with a device PIN, including background lock/unlock and screenshot obscuring; the new delay choices still need device lifecycle testing. OpenPGP key generation/storage and native trust/plaintext confirmation dialogs were previously exercised on an emulator; actual dialog automation remains open. The Android OpenPGP module also has automated GnuPG interoperability tests in a Node harness, but those are not device-level mail tests. The V0.5.11 worktree release-variant merged manifest was inspected; the hardened debug app loaded `https://localhost` and the Capacitor bridge in an emulator at a 411 px viewport. Device testing of vault-corruption/key-loss recovery, biometric enrollment invalidation, invalid-certificate integration, production-signed APK review, and automated instrumentation of native dialogs remain open. This does not constitute live-provider mail testing or GnuPG/Thunderbird interoperability testing on Android.
**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric design; invalid-certificate integration tests; production-signed APK/manifest review; app-lock recovery polish; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain.
**Release blockers:** independent human cryptography/security review; instrumented tests of actual native confirmation/biometric dialogs and policy-bypass attempts; full signed/inline and hostile-input parity; Android/GnuPG/Thunderbird interoperability; Keystore lifecycle/recovery and biometric invalidation tests; invalid-certificate integration tests; production-signed APK/manifest review; app-lock process-recreation testing; and compatibility review/remediation of the three moderate `npm audit --omit=dev` advisories in `ip-address` and the `nodemailer`/`mailparser` dependency chain.
## Goals and limits
@@ -51,31 +51,32 @@ These are implementation observations, not proof that all paths are safe. In par
### Phase 1 — Local data and privacy controls (P0)
- [~] The combined account/cache/draft/outbox store uses AES-GCM with an Android Keystore key. If the key alias is missing while encrypted data remains, the app now refuses to generate a replacement key and shows a recovery screen; it does not reset or expose the data. Add device tests for missing/invalidated keys, corrupted ciphertext, reinstall/migration handling, and the recovery instructions; verify no plaintext fallback for all stored data.
- [~] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation now says downloaded attachment files and global OpenPGP keys are retained. Decide/test whether a separate app-data wipe should remove app-created Downloads and PGP keys; account removal intentionally leaves those user data intact.
- [x] Removing an account removes its encrypted account record, including that account's cache, drafts, outbox, snoozes, and rules. The confirmation says downloaded attachment files and global OpenPGP keys are retained.
- [~] A separate native-confirmed full-data wipe removes vault contents, account and PGP Keystore keys, app-owned Downloads attachments, WebView data, service-worker registrations/caches, and renderer local settings. It is distinct from account removal; Android storage-failure and end-to-end deletion tests remain open.
- [x] Notification details are opt-in, persisted in the encrypted vault, and redacted from lock-screen previews; snooze notifications follow the privacy setting.
- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` while locked to hide task-switcher content and block screenshots; emulator smoke testing confirmed screenshots are obscured. Background sync continues and the setting is off unless enabled. Delayed lock, automated lifecycle/process-recreation tests, biometric UX, and recovery polish remain open.
- [~] A native app lock covers the WebView on background/resume, uses the device credential, and sets `FLAG_SECURE` as soon as the app leaves the foreground. Users may choose immediate, 30-second, 1-minute, or 5-minute locking; the default is immediate. Background sync continues and the setting is off unless enabled. Emulator testing of the new delays, automated lifecycle/process-recreation tests, and recovery polish remain open.
- [x] Background sync is separate from the UI lock. Further verification of which credentials/key material are available to background workers remains part of the vault lifecycle review.
**Exit criteria:** storage migration and failure tests; no plaintext fallback; app-lock/session tests across lifecycle events; notification privacy tests on supported Android versions; data removal tests.
### 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.
- [~] 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.
- [~] 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.
- [~] 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.
- [~] 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.
- [~] 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 in that store. Optional PGP passphrase release is separately encrypted by an authentication-bound Android Keystore key; biometric/device-credential invalidation clears the wrapper and falls back to the original passphrase. Device-level invalidation/recovery tests and automated at-rest checks remain open.
- [x] Optional biometric/device-credential release of PGP key access is available per key; the default remains passphrase-only, and background sync does not use PGP private keys.
- [~] The Android UI/bridge supports key generation, paste-based import, export, deletion, revocation export, contacts, fingerprints, trust, and public keys offered as message attachments (never imported silently). Trust elevation and replacement are guarded; encryption to keys not fingerprint-verified now requires an explicit per-send confirmation showing the recipient and full fingerprint. Automated native cancel/confirm regression tests remain open.
- [~] PGP/MIME encryption/signing, PGP/MIME and inline-encrypted-message decryption, attachments, encrypted Sent copies, ciphertext-before-queueing, signed-only PGP/MIME and clear-signed verification, and attached-public-key offers are implemented with Android-module tests. Tests cover Android-module/GnuPG interoperability in a Node harness, plus tampered, malformed, and oversized encrypted input. Device-level Thunderbird/GnuPG interoperability, native outbox/process-death tests, and remaining parity cases are open.
- [~] Native prompts guard trust elevation, key replacement, and plaintext sending when a key is available or encryption was requested; every raw MIME send now requires native confirmation because the native layer cannot cryptographically verify renderer-produced encryption. The native send path also checks PGP/MIME structure. Emulator smoke tests cover trust accept/cancel and plaintext cancel; policy and confirmation-gate unit tests cover prompt decisions and one-shot accept/cancel handling. Instrumented tests of the actual dialog UI, bypass attempts, stale-key cases, and queue policy remain open.
- [x] Key-server lookup and publication are disabled in the initial Android test implementation.
**Exit criteria:** parity tests for desktop message formats and trust rules; Android-specific tests for cancel/confirm paths, tampering, malformed/oversized messages, key replacement, offline queueing, process death, and passphrase expiry; independent human review before release.
### Phase 3 — WebView, native bridge, and content hardening (P1)
- [~] Mail HTML is sanitized, remote images are blocked until per-message approval, and CSP restrictions are in place. Verify the generated release assets/CSP against the reviewed source on supported devices.
- [~] Mail HTML is sanitized, remote images are blocked until per-message approval, and CSP restrictions are in place. Source-level CSP checks are automated; verify generated release assets and behavior on supported devices.
- [x] External URLs are constrained and require user confirmation before opening outside the WebView; unsafe schemes are rejected.
- [~] Broad unused filesystem/navigation capabilities have been removed, but a complete review of every Capacitor plugin/method and permission remains open.
- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open.
- [~] Broad unused filesystem/navigation capabilities have been removed. Automated checks cover CSP, manifest permissions, external URL constraints, DAV redirects, and selected bridge methods; a complete method-by-method plugin review remains open.
- [~] Attachment names, DAV values, PGP MIME, and several mail-content boundaries have validation/tests. Text/image previews use bounded stream reads, while attachment downloads stream to app storage. More hostile-input, DOM-injection, oversized-data, and UI spoofing cases remain open.
**Exit criteria:** automated CSP/navigation/bridge tests, sanitizer regressions, and a manual WebView inspection on the minimum and target Android versions.
+3 -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] Exercise native trust-change and plaintext-send confirmations on an emulator, including cancellation.
- [x] Add Android unit tests for trust-elevation, key-replacement, and plaintext-send confirmation decisions.
- [ ] Android release gate: instrumented native-dialog UI and bypass tests, full parity/interoperability tests, independent human cryptography/security review, and signed release review.
- [ ] Android follow-up: biometric unlock, full vault lifecycle/recovery, signed/inline verification parity, and dependency advisory remediation.
- [x] Add Android-module tests for signed-only PGP/MIME, clear-signed verification, attached public-key offers, and GnuPG interoperability in a Node harness.
- [ ] 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 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
- [x] Phase 6: documentation and release.
+1
View File
@@ -80,6 +80,7 @@ dependencies {
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation 'androidx.biometric:biometric:1.1.0'
implementation project(':capacitor-android')
implementation 'com.sun.mail:android-mail:1.6.7'
implementation 'com.sun.mail:android-activation:1.6.7'
@@ -68,6 +68,8 @@ internal object AndroidAccountVault {
fun appLockEnabled(): Boolean = read().optBoolean("appLockEnabled", false)
fun appLockDelaySeconds(): Int = read().optInt("appLockDelaySeconds", 0)
@Synchronized
fun setAppLockEnabled(enabled: Boolean): Boolean {
val store = read().put("appLockEnabled", enabled)
@@ -75,14 +77,69 @@ internal object AndroidAccountVault {
return enabled
}
@Synchronized
fun setAppLockDelaySeconds(seconds: Int): Int {
AndroidAppLockPolicy.requireValidDelay(seconds)
val store = read().put("appLockDelaySeconds", seconds)
write(store)
return seconds
}
fun pgpStore(): JSONObject = read().optJSONObject("pgpStore")?.let { JSONObject(it.toString()) }
?: JSONObject().put("keys", JSONArray()).put("contacts", JSONArray()).put("settings", JSONObject())
@Synchronized
fun savePgpStore(candidate: JSONObject) {
validatePgpStore(candidate)
val store = read().put("pgpStore", JSONObject(candidate.toString()))
val store = read()
val previousKeys = store.optJSONObject("pgpStore")?.optJSONArray("keys") ?: JSONArray()
val nextFingerprints = (0 until (candidate.optJSONArray("keys")?.length() ?: 0))
.mapNotNull { candidate.optJSONArray("keys")?.optJSONObject(it)?.optString("fingerprint") }
.map { it.uppercase(Locale.ROOT) }
.toSet()
val removedFingerprints = (0 until previousKeys.length())
.mapNotNull { previousKeys.optJSONObject(it)?.optString("fingerprint") }
.filter { it.uppercase(Locale.ROOT) !in nextFingerprints }
val biometricUnlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject()
removedFingerprints.forEach { biometricUnlocks.remove(it.uppercase(Locale.ROOT)) }
store.put("pgpBiometricUnlocks", biometricUnlocks)
store.put("pgpStore", JSONObject(candidate.toString()))
write(store)
removedFingerprints.forEach(AndroidPgpBiometricUnlock::deleteKey)
}
@Synchronized
fun pgpBiometricUnlock(fingerprint: String): String? =
read().optJSONObject("pgpBiometricUnlocks")?.optString(fingerprint.uppercase(Locale.ROOT))
?.takeIf(String::isNotBlank)
fun hasPgpBiometricUnlock(fingerprint: String): Boolean =
pgpBiometricUnlock(fingerprint) != null
@Synchronized
fun setPgpBiometricUnlock(fingerprint: String, ciphertext: String?) {
require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) {
"The OpenPGP fingerprint is invalid."
}
val store = read()
val unlocks = store.optJSONObject("pgpBiometricUnlocks") ?: JSONObject()
val key = fingerprint.uppercase(Locale.ROOT)
if (ciphertext.isNullOrBlank()) unlocks.remove(key)
else {
require(ciphertext.length <= 16_384) { "Biometric key unlock data is too large." }
unlocks.put(key, ciphertext)
}
store.put("pgpBiometricUnlocks", unlocks)
write(store)
}
@Synchronized
fun wipe() {
val prefs = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
check(prefs.edit().clear().commit()) { "Could not delete encrypted local data." }
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
if (keyStore.containsAlias(KEY_ALIAS)) keyStore.deleteEntry(KEY_ALIAS)
AndroidPgpBiometricUnlock.deleteAllKeys()
}
private fun validatePgpStore(candidate: JSONObject) {
@@ -0,0 +1,11 @@
package studio.daybreak.mail
internal object AndroidAppLockPolicy {
val allowedDelaySeconds = setOf(0, 30, 60, 300)
fun requireValidDelay(seconds: Int) {
require(seconds in allowedDelaySeconds) {
"Choose a supported app-lock delay."
}
}
}
@@ -0,0 +1,7 @@
package studio.daybreak.mail
internal object AndroidDownloadPolicy {
fun isAppOwnedDownload(ownerPackage: String?, relativePath: String?, packageName: String): Boolean =
ownerPackage == packageName &&
relativePath?.trimEnd('/') == "Download"
}
@@ -2,6 +2,7 @@ package studio.daybreak.mail
import android.content.ContentValues
import android.content.Context
import android.content.ContentUris
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
@@ -13,6 +14,7 @@ import org.json.JSONObject
import java.io.File
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
@@ -43,6 +45,52 @@ import javax.mail.internet.MimeUtility
internal object AndroidMailService {
data class SyncResult(val payload: JSONObject, val newCount: Int)
fun deleteSavedAttachments(context: Context) {
if (Build.VERSION.SDK_INT >= 29) {
val columns = arrayOf(
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.OWNER_PACKAGE_NAME,
MediaStore.MediaColumns.RELATIVE_PATH
)
val cursor = context.contentResolver.query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
columns,
"${MediaStore.MediaColumns.RELATIVE_PATH} = ?",
arrayOf("${Environment.DIRECTORY_DOWNLOADS}/"),
null
) ?: throw IllegalStateException("Could not inspect saved attachments in Downloads.")
cursor.use {
val idColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)
val ownerColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.OWNER_PACKAGE_NAME)
val pathColumn = it.getColumnIndexOrThrow(MediaStore.MediaColumns.RELATIVE_PATH)
while (it.moveToNext()) {
if (!AndroidDownloadPolicy.isAppOwnedDownload(
it.getString(ownerColumn),
it.getString(pathColumn),
context.packageName
)) continue
val uri = ContentUris.withAppendedId(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
it.getLong(idColumn)
)
context.contentResolver.delete(uri, null, null)
}
}
} else {
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) ?: return
val files = directory.listFiles()
?: throw IllegalStateException("Could not inspect saved attachments in Downloads.")
for (file in files) {
if (file.isFile && !file.delete()) {
throw IllegalStateException("Could not delete an app-saved attachment from Downloads.")
}
}
if (directory.exists() && !directory.delete()) {
throw IllegalStateException("Could not remove the app's Downloads folder.")
}
}
}
fun connect(account: JSONObject): JSONObject = withStore(account) { session, store ->
val inbox = store.getFolder("INBOX")
check(inbox.exists()) { "The inbox could not be found." }
@@ -440,7 +488,7 @@ internal object AndroidMailService {
val filename = input.optString("filename")
val part = findAttachment(message, filename)
?: throw IllegalStateException("No attachment was found in this message.")
saveAttachmentBytes(context, filename.ifBlank { "attachment" }, part.contentType, part.inputStream.readBytes())
saveAttachmentStream(context, filename.ifBlank { "attachment" }, part.contentType, part.inputStream)
} finally {
folder.close(false)
}
@@ -461,7 +509,7 @@ internal object AndroidMailService {
val none = JSONObject().put("kind", "none")
.put("reason", "No preview is available for this file type. Download it to open it.")
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
val bytes = part.inputStream.use { it.readBytes() }
val bytes = part.inputStream.use { BoundedInputReader.read(it, 5 * 1048576 + 1) }
if (bytes.size > 5 * 1048576) {
none.put("reason", "This image is too large to preview. Download it instead.")
} else {
@@ -470,7 +518,7 @@ internal object AndroidMailService {
)
}
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
val bytes = part.inputStream.use { it.readBytes() }
val bytes = part.inputStream.use { BoundedInputReader.read(it, 100001) }
JSONObject().put("kind", "text")
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
.put("truncated", bytes.size > 100000)
@@ -669,6 +717,7 @@ internal object AndroidMailService {
collectParts(message, body, htmlBodies, attachments, links)
val bodyText = body.joinToString("\n\n").trim().take(8000)
val encrypted = isEncryptedMessage(message) || bodyText.contains("-----BEGIN PGP MESSAGE-----")
val signed = isSignedMessage(message) || bodyText.contains("-----BEGIN PGP SIGNED MESSAGE-----")
val visibleBody = if (encrypted) "This message is encrypted. Unlock it with your OpenPGP key to read it." else bodyText
val snippet = (if (encrypted) "Encrypted message" else visibleBody.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date()
@@ -694,6 +743,7 @@ internal object AndroidMailService {
.put("subject", subject)
.put("snippet", snippet)
.put("encrypted", encrypted)
.put("signed", signed)
.put("time", DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()).format(date))
.put("date", DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault()).format(date))
.put("timestamp", date.time)
@@ -724,6 +774,15 @@ internal object AndroidMailService {
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> =
(0 until attachments.length()).map { attachments.getJSONObject(it) }
@@ -734,7 +793,9 @@ internal object AndroidMailService {
attachments: JSONArray,
links: MutableSet<String>
) {
if (part.isMimeType("application/pgp-signature") || part.isMimeType("application/pgp-encrypted")) return
val filename = decode(part.fileName)
if (part.isMimeType("application/octet-stream") && filename.equals("encrypted.asc", true)) return
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
val name = filename.ifBlank { "attachment" }
val size = part.size.coerceAtLeast(0)
@@ -774,6 +835,10 @@ internal object AndroidMailService {
}
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
return saveAttachmentStream(context, filename, contentType, ByteArrayInputStream(bytes))
}
private fun saveAttachmentStream(context: Context, filename: String, contentType: String, input: InputStream): JSONObject {
val safeFilename = AttachmentNamePolicy.sanitize(filename)
val mimeType = contentType.substringBefore(';').ifBlank {
MimeTypeMap.getSingleton().getMimeTypeFromExtension(safeFilename.substringAfterLast('.', "")) ?: "application/octet-stream"
@@ -786,14 +851,41 @@ internal object AndroidMailService {
}
val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
?: throw IllegalStateException("Could not create the attachment in Downloads.")
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
try {
val output = context.contentResolver.openOutputStream(uri)
?: throw IllegalStateException("Could not write the attachment.")
input.use { source -> output.use { source.copyTo(it) } }
} catch (error: Exception) {
try {
input.close()
} catch (cleanupError: Exception) {
error.addSuppressed(cleanupError)
}
try {
context.contentResolver.delete(uri, null, null)
} catch (cleanupError: Exception) {
error.addSuppressed(cleanupError)
}
throw error
}
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", safeFilename)
}
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
?: throw IllegalStateException("Downloads storage is not available.")
val file = File(directory, safeFilename)
file.writeBytes(bytes)
try {
file.outputStream().use { output -> input.use { it.copyTo(output) } }
} catch (error: Exception) {
try {
input.close()
} catch (cleanupError: Exception) {
error.addSuppressed(cleanupError)
}
if (file.exists() && !file.delete()) error.addSuppressed(
IllegalStateException("Could not remove the incomplete attachment from Downloads.")
)
throw error
}
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", safeFilename)
}
@@ -0,0 +1,166 @@
package studio.daybreak.mail
import android.content.Context
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import android.util.Base64
import androidx.biometric.BiometricManager
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
internal class PgpBiometricUnlockException(
val errorCode: String,
message: String,
cause: Throwable? = null
) : IllegalStateException(message, cause)
internal object AndroidPgpBiometricUnlock {
private const val ALIAS_PREFIX = "ep-mail-pgp-unlock-"
private const val GCM_TAG_BITS = 128
private const val IV_BYTES = 12
fun requireAvailable(context: Context) {
val authenticators = allowedAuthenticators()
val result = BiometricManager.from(context).canAuthenticate(authenticators)
require(result == BiometricManager.BIOMETRIC_SUCCESS) {
"Set up a strong biometric or device screen lock before enabling biometric key unlock."
}
}
fun encryptCipher(context: Context, fingerprint: String): Cipher {
requireAvailable(context)
try {
return createEncryptCipher(context, fingerprint)
} catch (_: KeyPermanentlyInvalidatedException) {
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
deleteKey(fingerprint)
return createEncryptCipher(context, fingerprint)
}
}
private fun createEncryptCipher(context: Context, fingerprint: String): Cipher {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, secretKey(context, fingerprint))
return cipher
}
fun decryptCipher(context: Context, fingerprint: String, ciphertext: String): Cipher {
val payload = try {
Base64.decode(ciphertext, Base64.NO_WRAP)
} catch (_: IllegalArgumentException) {
throw PgpBiometricUnlockException("BIOMETRIC_CORRUPT", "Biometric key unlock data is damaged. Enter the key passphrase and set it up again.")
}
require(payload.size > IV_BYTES) {
"Biometric key unlock data is damaged. Enter the key passphrase and set it up again."
}
val key = try {
secretKey(context, fingerprint, create = false)
} catch (_: KeyPermanentlyInvalidatedException) {
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
} catch (_: Exception) {
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric key unlock is unavailable. Enter the key passphrase and set it up again.")
}
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
try {
cipher.init(
Cipher.DECRYPT_MODE,
key,
GCMParameterSpec(GCM_TAG_BITS, payload.copyOfRange(0, IV_BYTES))
)
} catch (_: KeyPermanentlyInvalidatedException) {
throw PgpBiometricUnlockException("BIOMETRIC_INVALIDATED", "Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again.")
}
return cipher
}
fun seal(passphrase: String, cipher: Cipher): String {
require(passphrase.length in 1..4096) { "The key passphrase is empty or too long for biometric unlock." }
val plaintext = passphrase.toByteArray(Charsets.UTF_8)
val encrypted = try {
cipher.doFinal(plaintext)
} finally {
plaintext.fill(0)
}
return Base64.encodeToString(cipher.iv + encrypted, Base64.NO_WRAP)
}
fun open(ciphertext: String, cipher: Cipher): String {
val payload = Base64.decode(ciphertext, Base64.NO_WRAP)
val plaintext = cipher.doFinal(payload.copyOfRange(IV_BYTES, payload.size))
return String(plaintext, Charsets.UTF_8).also { plaintext.fill(0) }
}
fun deleteKey(fingerprint: String) {
val alias = alias(fingerprint)
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
if (keyStore.containsAlias(alias)) keyStore.deleteEntry(alias)
}
fun deleteAllKeys() {
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val aliases = keyStore.aliases()
while (aliases.hasMoreElements()) {
val name = aliases.nextElement()
if (name.startsWith(ALIAS_PREFIX)) keyStore.deleteEntry(name)
}
}
private fun secretKey(context: Context, fingerprint: String, create: Boolean = true): SecretKey {
val alias = alias(fingerprint)
val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
try {
(keyStore.getKey(alias, null) as? SecretKey)?.let { return it }
} catch (error: KeyPermanentlyInvalidatedException) {
throw error
} catch (error: Exception) {
throw IllegalStateException("Biometric key unlock is unavailable. Enter the key passphrase and set it up again.", error)
}
if (!create) {
throw PgpBiometricUnlockException(
"BIOMETRIC_INVALIDATED",
"Biometric enrollment or device security changed. Enter the key passphrase and set up biometric unlock again."
)
}
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
val spec = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.setRandomizedEncryptionRequired(true)
.setUserAuthenticationRequired(true)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
spec.setUserAuthenticationParameters(
0,
KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL
)
} else {
spec.setUserAuthenticationValidityDurationSeconds(-1)
spec.setInvalidatedByBiometricEnrollment(true)
}
generator.init(spec.build())
return generator.generateKey()
}
private fun allowedAuthenticators(): Int =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
BiometricManager.Authenticators.BIOMETRIC_STRONG or
BiometricManager.Authenticators.DEVICE_CREDENTIAL
} else {
BiometricManager.Authenticators.BIOMETRIC_STRONG
}
private fun alias(fingerprint: String): String {
require(Regex("^[0-9A-Fa-f]{40,64}$").matches(fingerprint)) {
"The OpenPGP fingerprint is invalid."
}
return ALIAS_PREFIX + fingerprint.uppercase()
}
}
@@ -76,6 +76,10 @@ internal object AndroidPgpPolicy {
"The message body and attachments will be readable by the mail provider and anyone who receives it. Send plaintext anyway?"
}
fun unverifiedRawMimeWarning(): String =
"Android cannot verify that this raw MIME message is actually encrypted. It may contain readable message content, including inside a deceptive OpenPGP wrapper. " +
"Signing alone does not encrypt a message. Continue only if you independently verified the MIME contents and intend to send them."
private fun safeLabel(values: List<String>): String =
values.joinToString(", ").replace(Regex("[\\r\\n\\u0000]"), " ").take(300).ifBlank { "this contact" }
@@ -0,0 +1,19 @@
package studio.daybreak.mail
import java.io.ByteArrayOutputStream
import java.io.InputStream
internal object BoundedInputReader {
fun read(input: InputStream, maxBytes: Int): ByteArray {
require(maxBytes > 0) { "A positive byte limit is required." }
val output = ByteArrayOutputStream(minOf(maxBytes, 8192))
val buffer = ByteArray(8192)
while (output.size() < maxBytes) {
val count = input.read(buffer, 0, minOf(buffer.size, maxBytes - output.size()))
if (count < 0) break
if (count == 0) continue
output.write(buffer, 0, count)
}
return output.toByteArray()
}
}
@@ -7,6 +7,7 @@ import android.content.IntentFilter
import android.net.Uri
import android.os.Build
import android.app.AlertDialog
import androidx.biometric.BiometricPrompt
import com.getcapacitor.JSObject
import com.getcapacitor.Plugin
import com.getcapacitor.PluginCall
@@ -17,10 +18,12 @@ import java.util.UUID
import org.json.JSONArray
import org.json.JSONObject
import javax.mail.internet.InternetAddress
import javax.crypto.Cipher
@CapacitorPlugin(name = "EpMail")
class EpMailPlugin : Plugin() {
private var syncReceiver: BroadcastReceiver? = null
private var wipeDialogShowing = false
override fun load() {
AndroidAccountVault.initialize(context)
@@ -93,6 +96,7 @@ class EpMailPlugin : Plugin() {
val keyguard = context.getSystemService(Context.KEYGUARD_SERVICE) as android.app.KeyguardManager
call.resolve(JSObject()
.put("enabled", AndroidAccountVault.appLockEnabled())
.put("lockDelaySeconds", AndroidAccountVault.appLockDelaySeconds())
.put("deviceSecure", keyguard.isDeviceSecure))
} catch (error: Exception) {
call.reject(error.message ?: "Could not read app-lock settings.")
@@ -116,6 +120,17 @@ class EpMailPlugin : Plugin() {
}
}
@PluginMethod
fun setAppLockDelay(call: PluginCall) {
try {
val seconds = call.getInt("seconds")
?: throw IllegalArgumentException("Choose when ep-mail should lock after leaving it.")
call.resolve(JSObject().put("lockDelaySeconds", AndroidAccountVault.setAppLockDelaySeconds(seconds)))
} catch (error: Exception) {
call.reject(error.message ?: "Could not save the app-lock delay.")
}
}
@PluginMethod
fun pgpLoadStore(call: PluginCall) {
try {
@@ -155,6 +170,130 @@ class EpMailPlugin : Plugin() {
}
}
@PluginMethod
fun setPgpBiometricUnlock(call: PluginCall) {
try {
val fingerprint = call.getString("fingerprint")
?: throw IllegalArgumentException("Choose an OpenPGP key.")
val passphrase = call.getString("passphrase")
?: throw IllegalArgumentException("Enter the key passphrase first.")
require(passphrase.length in 1..4096) { "The key passphrase is empty or too long for biometric unlock." }
require(AndroidAccountVault.pgpStore().optJSONArray("keys")?.let { keys ->
(0 until keys.length()).any { keys.optJSONObject(it)?.optString("fingerprint") == fingerprint }
} == true) { "That OpenPGP key is no longer available." }
val cipher = AndroidPgpBiometricUnlock.encryptCipher(context, fingerprint)
authenticatePgpCipher(call, cipher) { authenticated ->
try {
AndroidAccountVault.setPgpBiometricUnlock(
fingerprint,
AndroidPgpBiometricUnlock.seal(passphrase, authenticated)
)
call.resolve(JSObject().put("enabled", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not enable biometric key unlock.")
}
}
} catch (error: Exception) {
call.reject(error.message ?: "Could not enable biometric key unlock.")
}
}
@PluginMethod
fun getPgpBiometricPassphrase(call: PluginCall) {
try {
val fingerprint = call.getString("fingerprint")
?: throw IllegalArgumentException("Choose an OpenPGP key.")
val ciphertext = AndroidAccountVault.pgpBiometricUnlock(fingerprint)
if (ciphertext == null) {
call.resolve(JSObject().put("enabled", false))
return
}
val cipher = AndroidPgpBiometricUnlock.decryptCipher(context, fingerprint, ciphertext)
authenticatePgpCipher(call, cipher) { authenticated ->
try {
call.resolve(JSObject()
.put("enabled", true)
.put("passphrase", AndroidPgpBiometricUnlock.open(ciphertext, authenticated)))
} catch (error: Exception) {
call.reject(error.message ?: "Could not unlock the OpenPGP key.")
}
}
} catch (error: PgpBiometricUnlockException) {
if (error.errorCode == "BIOMETRIC_INVALIDATED") {
try {
call.getString("fingerprint")?.let { fingerprint ->
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
AndroidPgpBiometricUnlock.deleteKey(fingerprint)
}
} catch (cleanupError: Exception) {
call.reject(cleanupError.message ?: "Biometric unlock expired and could not be cleared.")
return
}
}
call.reject(error.message ?: "Biometric key unlock is unavailable.", error.errorCode)
} catch (error: Exception) {
call.reject(error.message ?: "Could not unlock the OpenPGP key.")
}
}
@PluginMethod
fun removePgpBiometricUnlock(call: PluginCall) {
try {
val fingerprint = call.getString("fingerprint")
?: throw IllegalArgumentException("Choose an OpenPGP key.")
AndroidAccountVault.setPgpBiometricUnlock(fingerprint, null)
AndroidPgpBiometricUnlock.deleteKey(fingerprint)
call.resolve(JSObject().put("enabled", false))
} catch (error: Exception) {
call.reject(error.message ?: "Could not remove biometric key unlock.")
}
}
@PluginMethod
fun pgpBiometricUnlockEnabled(call: PluginCall) {
try {
val fingerprint = call.getString("fingerprint")
?: throw IllegalArgumentException("Choose an OpenPGP key.")
call.resolve(JSObject().put("enabled", AndroidAccountVault.hasPgpBiometricUnlock(fingerprint)))
} catch (error: Exception) {
call.reject(error.message ?: "Could not read biometric key-unlock settings.")
}
}
private fun authenticatePgpCipher(call: PluginCall, cipher: Cipher, onAuthenticated: (Cipher) -> Unit) {
val host = activity as? MainActivity
if (host == null) {
call.reject("Biometric key unlock is not available in this activity.")
return
}
host.runOnUiThread {
try {
host.authenticatePgpCipher(cipher, object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
val authenticated = result.cryptoObject?.cipher
if (authenticated == null) {
call.reject("Android could not unlock the OpenPGP key.")
return
}
onAuthenticated(authenticated)
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
val cancelled = errorCode == BiometricPrompt.ERROR_USER_CANCELED ||
errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON ||
errorCode == BiometricPrompt.ERROR_CANCELED
call.reject(
errString.toString(),
if (cancelled) "BIOMETRIC_CANCELLED" else "BIOMETRIC_FAILED"
)
}
})
} catch (error: Exception) {
call.reject(error.message ?: "Could not start biometric key unlock.")
}
}
}
private fun pgpStoreChangeWarning(previous: JSONObject, candidate: JSONObject): String? {
val oldContacts = previous.optJSONArray("contacts") ?: JSONArray()
val newContacts = candidate.optJSONArray("contacts") ?: JSONArray()
@@ -263,6 +402,41 @@ class EpMailPlugin : Plugin() {
}
}
@PluginMethod
fun deleteAllLocalData(call: PluginCall) {
if (wipeDialogShowing) {
call.reject("A local-data deletion is already awaiting confirmation.")
return
}
wipeDialogShowing = true
AlertDialog.Builder(activity)
.setTitle("Delete all local data?")
.setMessage(
"This permanently deletes every saved mail and DAV account, downloaded and cached mail, drafts, queued sends, local settings, OpenPGP keys and contacts, and attachments saved by ep-mail to Downloads. Encrypted mail cannot be recovered without a separate key backup."
)
.setNegativeButton("Cancel") { _, _ ->
wipeDialogShowing = false
call.resolve(JSObject().put("deleted", false))
}
.setPositiveButton("Delete all data") { _, _ ->
wipeDialogShowing = false
try {
MailIdleService.stop(context)
AndroidMailService.deleteSavedAttachments(context)
AndroidAccountVault.wipe()
(activity as? MainActivity)?.clearLocalWebData()
call.resolve(JSObject().put("deleted", true))
} catch (error: Exception) {
call.reject(error.message ?: "Could not delete all local data.")
}
}
.setOnCancelListener {
wipeDialogShowing = false
call.resolve(JSObject().put("deleted", false))
}
.show()
}
@PluginMethod
fun connect(call: PluginCall) {
try {
@@ -464,10 +638,11 @@ class EpMailPlugin : Plugin() {
sendPrepared(call, input)
return
}
val rawMime = input.optString("rawBase64").isNotBlank()
showPgpConfirmation(
title = "Send without OpenPGP encryption?",
title = if (rawMime) "Send unverified MIME?" else "Send without OpenPGP encryption?",
message = warning,
confirmLabel = "Send plaintext",
confirmLabel = if (rawMime) "Send anyway" else "Send plaintext",
onConfirmed = { sendPrepared(call, input) },
onCancelled = {
call.resolve(JSObject().put("failed", true).put("code", "PLAINTEXT_CANCELLED").put("message", "Plaintext send cancelled."))
@@ -493,7 +668,7 @@ class EpMailPlugin : Plugin() {
}
private fun plaintextSendWarning(input: JSONObject): String? {
if (input.optString("rawBase64").isNotBlank()) return null
if (input.optString("rawBase64").isNotBlank()) return AndroidPgpPolicy.unverifiedRawMimeWarning()
val recipients = (listOf(input.optString("to"), input.optString("cc"))
.filter(String::isNotBlank)
.flatMap { InternetAddress.parse(it, true).mapNotNull { address -> (address as? InternetAddress)?.address?.lowercase(Locale.ROOT) } })
@@ -9,17 +9,25 @@ import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebStorage;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import com.getcapacitor.BridgeActivity;
import javax.crypto.Cipher;
public class MainActivity extends BridgeActivity {
private static final int UNLOCK_REQUEST_CODE = 705;
@@ -28,8 +36,18 @@ public class MainActivity extends BridgeActivity {
private Button appLockButton;
private boolean appLocked;
private boolean awaitingUnlockResult;
private boolean pgpAuthInProgress;
private boolean pgpAuthPaused;
private long pgpAuthPauseAt;
private boolean activityResumed;
private boolean vaultRecoveryRequired;
private final Handler appLockHandler = new Handler(Looper.getMainLooper());
private final Runnable delayedAppLock = () -> {
if (!activityResumed && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
};
private final Runnable lockAfterPgpAuth = () -> {
if (!activityResumed && pgpAuthPaused && !vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
};
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -56,6 +74,10 @@ public class MainActivity extends BridgeActivity {
super.onResume();
if (vaultRecoveryRequired) return;
activityResumed = true;
appLockHandler.removeCallbacks(delayedAppLock);
appLockHandler.removeCallbacks(lockAfterPgpAuth);
pgpAuthPaused = false;
if (!appLocked) getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
if (isAppLockEnabled() && appLocked) {
lockWebView();
configureUnlockButton();
@@ -65,7 +87,19 @@ public class MainActivity extends BridgeActivity {
@Override
public void onPause() {
activityResumed = false;
if (!vaultRecoveryRequired && isAppLockEnabled()) lockWebView();
if (!vaultRecoveryRequired && isAppLockEnabled() && !pgpAuthInProgress) {
int delaySeconds = appLockDelaySeconds();
if (delaySeconds == 0) {
lockWebView();
} else {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
appLockHandler.postDelayed(delayedAppLock, delaySeconds * 1000L);
}
} else if (!vaultRecoveryRequired && isAppLockEnabled() && pgpAuthInProgress) {
pgpAuthPaused = true;
pgpAuthPauseAt = SystemClock.elapsedRealtime();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
super.onPause();
}
@@ -78,8 +112,18 @@ public class MainActivity extends BridgeActivity {
else updateAppLockMessage("Unlock with your Android screen lock to view mail.");
}
@Override
public void onDestroy() {
appLockHandler.removeCallbacks(delayedAppLock);
appLockHandler.removeCallbacks(lockAfterPgpAuth);
super.onDestroy();
}
public void onAppLockSettingChanged(boolean enabled) {
runOnUiThread(() -> {
appLockHandler.removeCallbacks(delayedAppLock);
appLockHandler.removeCallbacks(lockAfterPgpAuth);
pgpAuthPaused = false;
if (!enabled) {
awaitingUnlockResult = false;
unlockWebView(false);
@@ -91,6 +135,77 @@ public class MainActivity extends BridgeActivity {
});
}
private int appLockDelaySeconds() {
try {
int delay = AndroidAccountVault.INSTANCE.appLockDelaySeconds();
AndroidAppLockPolicy.INSTANCE.requireValidDelay(delay);
return delay;
} catch (Exception ignored) {
return 0;
}
}
public void authenticatePgpCipher(Cipher cipher, BiometricPrompt.AuthenticationCallback callback) {
int authenticators = BiometricManager.Authenticators.BIOMETRIC_STRONG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
authenticators |= BiometricManager.Authenticators.DEVICE_CREDENTIAL;
}
BiometricPrompt.PromptInfo.Builder prompt = new BiometricPrompt.PromptInfo.Builder()
.setTitle("Unlock OpenPGP key")
.setSubtitle("Confirm to release this key's passphrase")
.setAllowedAuthenticators(authenticators)
.setConfirmationRequired(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
prompt.setNegativeButtonText("Cancel");
}
BiometricPrompt biometricPrompt = new BiometricPrompt(
this,
ContextCompat.getMainExecutor(this),
new BiometricPrompt.AuthenticationCallback() {
@Override
public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result) {
finishPgpAuthentication();
callback.onAuthenticationSucceeded(result);
}
@Override
public void onAuthenticationFailed() {
callback.onAuthenticationFailed();
}
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
finishPgpAuthentication();
callback.onAuthenticationError(errorCode, errString);
}
}
);
pgpAuthInProgress = true;
try {
biometricPrompt.authenticate(
prompt.build(),
new BiometricPrompt.CryptoObject(cipher)
);
} catch (RuntimeException error) {
pgpAuthInProgress = false;
throw error;
}
}
private void finishPgpAuthentication() {
pgpAuthInProgress = false;
if (!pgpAuthPaused) return;
long elapsed = SystemClock.elapsedRealtime() - pgpAuthPauseAt;
long remaining = Math.max(1000L, appLockDelaySeconds() * 1000L - elapsed);
appLockHandler.postDelayed(lockAfterPgpAuth, remaining);
}
public void clearLocalWebData() {
if (getBridge() == null || getBridge().getWebView() == null) return;
getBridge().getWebView().clearCache(true);
WebStorage.getInstance().deleteAllData();
}
private boolean isAppLockEnabled() {
try {
return AndroidAccountVault.INSTANCE.appLockEnabled();
@@ -0,0 +1,14 @@
package studio.daybreak.mail
import org.junit.Assert.assertThrows
import org.junit.Test
class AndroidAppLockPolicyTest {
@Test
fun acceptsOnlySupportedAppLockDelays() {
AndroidAppLockPolicy.allowedDelaySeconds.forEach(AndroidAppLockPolicy::requireValidDelay)
assertThrows(IllegalArgumentException::class.java) {
AndroidAppLockPolicy.requireValidDelay(45)
}
}
}
@@ -0,0 +1,15 @@
package studio.daybreak.mail
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class AndroidDownloadPolicyTest {
@Test
fun onlySelectsDownloadsCreatedByThisApplication() {
assertTrue(AndroidDownloadPolicy.isAppOwnedDownload("studio.daybreak.mail", "Download/", "studio.daybreak.mail"))
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload("other.app", "Download/", "studio.daybreak.mail"))
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload(null, "Download/", "studio.daybreak.mail"))
assertFalse(AndroidDownloadPolicy.isAppOwnedDownload("studio.daybreak.mail", "Documents/", "studio.daybreak.mail"))
}
}
@@ -78,6 +78,15 @@ class AndroidPgpPolicyTest {
assertFalse(warning.contains("Fingerprint:"))
}
@Test
fun rawMimeRequiresNativeConfirmationBecauseEncryptionCannotBeVerified() {
val warning = AndroidPgpPolicy.unverifiedRawMimeWarning()
assertTrue(warning.contains("cannot verify"))
assertTrue(warning.contains("deceptive OpenPGP wrapper"))
assertTrue(warning.contains("Signing alone does not encrypt"))
}
private fun contact(fingerprint: String, email: String, trust: String) =
AndroidPgpPolicy.ContactKey(fingerprint, listOf(email), trust)
}
@@ -0,0 +1,23 @@
package studio.daybreak.mail
import java.io.ByteArrayInputStream
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
class BoundedInputReaderTest {
@Test
fun readsOnlyUpToTheRequestedLimit() {
val input = ByteArrayInputStream(byteArrayOf(1, 2, 3, 4, 5))
assertArrayEquals(byteArrayOf(1, 2, 3), BoundedInputReader.read(input, 3))
assertEquals(2, input.available())
}
@Test
fun readsShortStreamsToEnd() {
assertArrayEquals(
byteArrayOf(1, 2),
BoundedInputReader.read(ByteArrayInputStream(byteArrayOf(1, 2)), 5)
)
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
"version": "0.5.11",
"version": "0.5.14",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
"version": "0.5.11",
"version": "0.5.14",
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ep-mail",
"version": "0.5.11",
"version": "0.5.14",
"private": true,
"description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
+33 -4
View File
@@ -74,6 +74,12 @@ function pgpRenderReaderState(message) {
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) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.signed && Array.isArray(message.pgpSignatures)) {
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);
}
@@ -104,9 +110,14 @@ async function pgpUnlockMessage(message, interactive) {
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
return;
}
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') {
if (!interactive) { pgpRenderReaderState(message); return; }
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
const prompt = result.code === 'BAD_PASSPHRASE'
? 'That passphrase was incorrect. Try again.'
: result.code === 'BIOMETRIC_INVALIDATED'
? `${result.message} Enter the passphrase to continue.`
: `Enter the passphrase for ${result.email || 'your key'}.`;
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
if (passphrase === null) return;
continue;
}
@@ -117,6 +128,20 @@ async function pgpUnlockMessage(message, interactive) {
}
}
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) {
baseOpenMessage(id);
const message = pgpMailUi.state.messages.find(item => item.id === id);
@@ -126,6 +151,10 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
message.pgpAutoTried = true;
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.
@@ -155,7 +184,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
if (!selectPgpMailUi('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
else {
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
hint.textContent = status.recipients.some(item => item.trust !== 'verified') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
if (!touched && !encrypt.checked) encrypt.checked = true;
}
} catch { hint.textContent = ''; }
@@ -192,7 +221,7 @@ async function prepareSend(to, cc) {
let passphrase = null;
if (sign) {
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
if (!status.signer.unlocked) {
if (!status.signer.unlocked && !status.signer.biometricUnlockEnabled) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false;
}
+37 -1
View File
@@ -35,7 +35,7 @@ function openEncryptionKeys() {
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Optional biometric unlock stores the passphrase in a Keystore key requiring user authentication. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
<h3 class="pgp-heading">Change a key passphrase</h3>
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
@@ -138,6 +138,42 @@ function openEncryptionKeys() {
}
};
row.append(changePassphrase);
if (androidPgp) {
const biometric = document.createElement('button');
biometric.className = 'discard';
biometric.textContent = 'Checking biometric unlock…';
biometric.disabled = true;
row.append(biometric);
window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => {
if (!biometric.isConnected) return;
biometric.dataset.enabled = String(enabled);
biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…';
biometric.disabled = false;
}).catch(error => {
if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.');
});
biometric.onclick = async () => {
biometric.disabled = true;
try {
if (biometric.dataset.enabled === 'true') {
if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return;
await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint);
status('Biometric unlock disabled.');
} else {
const passphrase = needPassphrase();
if (!passphrase) return;
await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase });
passphraseField().value = '';
status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.');
}
await render();
} catch (error) {
status(error.message || 'Could not update biometric key unlock.');
} finally {
biometric.disabled = false;
}
};
}
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
actions.push(['Delete', async () => {
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
+255 -30
View File
@@ -5738,6 +5738,7 @@
super(e2, t2);
}
};
var ka = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var Ea = class {
constructor(e2) {
this.packets = e2 || new Gs();
@@ -5753,6 +5754,22 @@
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) {
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;
@@ -6874,6 +6891,7 @@
const f2 = new no(h2);
return f2.fromStream = c2, f2;
}
var co = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var uo = class _uo {
constructor(e2, t2) {
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);
}
};
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 }) {
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);
@@ -7011,6 +7061,23 @@
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) {
if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message");
}
@@ -9896,6 +9963,25 @@
visit(bytes);
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() {
const bytes = crypto.getRandomValues(new Uint8Array(18));
return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`;
@@ -9961,7 +10047,73 @@ ${parts.join("")}`;
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
return btoa(binary);
}
function createAndroidPgp({ EpMail: EpMail2, getAccount }) {
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, confirm = globalThis.confirm }) {
let storePromise;
const passphrases = /* @__PURE__ */ new Map();
let cacheMinutes = 10;
@@ -10088,20 +10240,30 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
async function unlock(fingerprint, passphrase) {
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
if (!entry) throw new Error("That key was not found.");
const secret = passphrase || await biometricPassphrase(fingerprint);
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email || "your key"}.`), { code: "PASSPHRASE_REQUIRED" });
return unlockWithPassphrase(entry, secret);
}
async function unlockWithPassphrase(entry, passphrase) {
try {
return await po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase });
} catch {
throw new Error("The passphrase is incorrect.");
}
}
async function biometricPassphrase(fingerprint) {
if (typeof EpMail2.getPgpBiometricPassphrase !== "function") return null;
const result = await EpMail2.getPgpBiometricPassphrase({ fingerprint });
return result?.enabled && typeof result.passphrase === "string" ? result.passphrase : null;
}
async function signerFor(account, passphrase) {
const data = await store();
const entry = data.keys.find((item) => item.email.toLowerCase() === String(account.email).toLowerCase());
if (!entry) throw Object.assign(new Error("Create or import an encryption key for this address first."), { code: "NO_SIGNING_KEY" });
const secret = passphrase || cached(entry.fingerprint);
const secret = passphrase || cached(entry.fingerprint) || await biometricPassphrase(entry.fingerprint);
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email} to sign this message.`), { code: "PASSPHRASE_REQUIRED", fingerprint: entry.fingerprint, email: entry.email });
try {
const key = await unlock(entry.fingerprint, secret);
const key = await unlockWithPassphrase(entry, secret);
cache(entry.fingerprint, secret);
return { key, entry };
} catch {
@@ -10125,6 +10287,21 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
if (pgp.encrypt && recipientKeys.missing.length) {
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(", ")}.`), { code: "NO_RECIPIENT_KEY", missing: recipientKeys.missing });
}
const unverifiedKeys = recipientKeys.keys.filter((item) => item.trust !== "verified");
if (pgp.encrypt && unverifiedKeys.length) {
const details = unverifiedKeys.map(
(item) => `${item.address}
${item.fingerprint.match(/.{1,4}/g).join(" ")} (${item.trust})`
).join("\n\n");
const warning = `These recipient keys have not been verified by fingerprint:
${details}
If a key is incorrect, its owner may be able to read this message. Compare each fingerprint with its owner through another channel before sending. Send encrypted mail to these unverified keys anyway?`;
if (typeof confirm !== "function" || !confirm(warning)) {
throw Object.assign(new Error("Sending to unverified recipient keys was cancelled."), { code: "UNVERIFIED_RECIPIENT_KEY" });
}
}
let inner = mimeInner(`${String(message.text || "").slice(0, 5e5)}${account.signature ? `
${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
@@ -10212,6 +10389,7 @@ ${body}`);
selected = candidates.find((entry) => cached(entry.fingerprint)) || selected;
secret = cached(selected.fingerprint);
}
if (!secret) secret = await biometricPassphrase(selected.fingerprint);
if (!secret) return { failed: true, code: "PASSPHRASE_REQUIRED", fingerprint: selected.fingerprint, email: selected.email, message: "Enter your key passphrase to read this message." };
let privateKey;
try {
@@ -10229,31 +10407,8 @@ ${body}`);
return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." };
}
const content = parseInnerMime(decrypted.data);
const signatures = [];
for (const item of decrypted.signatures || []) {
const known = verify.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
let status = "valid";
try {
await item.verified;
} catch {
status = known ? "invalid" : "unknown-key";
}
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || "";
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || "").toLowerCase();
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const changed = Boolean(sender && data.contacts.some((entry) => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
const matchesSender = Boolean(sender && keyEmails.includes(sender));
signatures.push({
status,
keyId: item.keyID.toHex().toUpperCase(),
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {}
});
}
const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
const attachedKeys = await attachedPublicKeys(content.attachments);
return {
ok: true,
body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [],
@@ -10263,12 +10418,52 @@ ${body}`);
attachment: content.attachments[0]?.filename || null,
size: content.attachments[0]?.size || "",
signatures,
attachedKeys: []
attachedKeys
};
} catch (error) {
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 = {
platform: "android",
async list() {
@@ -10367,6 +10562,23 @@ ${body}`);
clear(fingerprint);
return { removed: true };
},
async enableBiometricUnlock({ fingerprint, passphrase }) {
if (typeof EpMail2.setPgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
if (!entry) throw new Error("That key was not found.");
if (!passphrase) throw new Error("Enter the key passphrase first.");
await unlockWithPassphrase(entry, passphrase);
return EpMail2.setPgpBiometricUnlock({ fingerprint, passphrase });
},
async biometricUnlockEnabled(fingerprint) {
if (typeof EpMail2.pgpBiometricUnlockEnabled !== "function") return false;
return Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled);
},
async disableBiometricUnlock(fingerprint) {
if (typeof EpMail2.removePgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
clear(fingerprint);
return EpMail2.removePgpBiometricUnlock({ fingerprint });
},
async contacts() {
return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt }));
},
@@ -10406,13 +10618,24 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
const { keys, missing } = await resolveRecipients(addresses);
const account = await getAccount();
const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null;
let biometricUnlockEnabled = false;
if (entry && typeof EpMail2.pgpBiometricUnlockEnabled === "function") {
biometricUnlockEnabled = Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled);
}
return {
recipients: keys.map((item) => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
missing,
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null
signer: entry ? {
fingerprint: entry.fingerprint,
email: entry.email,
name: entry.name,
unlocked: Boolean(cached(entry.fingerprint)),
biometricUnlockEnabled
} : null
};
},
decryptMessage,
verifyMessage,
async getSettings() {
const data = await store();
return { cacheMinutes };
@@ -10467,6 +10690,8 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
getAppLockSettings: () => EpMail.getAppLockSettings(),
setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }),
setAppLockDelay: (seconds) => EpMail.setAppLockDelay({ seconds }),
deleteAllLocalData: () => EpMail.deleteAllLocalData(),
getAccount: () => EpMail.getAccount(),
listAccounts: () => EpMail.listAccounts(),
selectAccount: (id) => EpMail.selectAccount({ id }),
+8 -5
View File
@@ -33,18 +33,21 @@ async function openPreferences() {
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled?window.daybreakMail:null;
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled&&window.daybreakMail?.setAppLockDelay?window.daybreakMail:null;
const localDataBridge=window.daybreakMail?.deleteAllLocalData?window.daybreakMail:null;
let notificationPrivacy={showDetails:false};
let appLockSettings={enabled:false,deviceSecure:false};
let appLockSettings={enabled:false,deviceSecure:false,lockDelaySeconds:0};
if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}}
if(appLockBridge){try{appLockSettings=await appLockBridge.getAppLockSettings()}catch(error){toastProductivityUi(error.message||'Could not load app-lock settings');return}}
const notificationSetting=notificationBridge?`<label class="compose-line"><span>Show sender and subject in notifications</span><input id="show-notification-details" type="checkbox"${notificationPrivacy.showDetails?' checked':''}></label><p class="account-note">Off by default. Android still hides private details from lock-screen previews.</p>`:'';
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><p class="account-note">Requires a secure Android screen lock. Mail sync continues in the background; unlock with your device PIN, pattern, or password when you return.</p>`:'';
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><label class="compose-line"><span>Lock delay</span><select class="settings-select" id="app-lock-delay"><option value="0"${appLockSettings.lockDelaySeconds===0?' selected':''}>Immediately</option><option value="30"${appLockSettings.lockDelaySeconds===30?' selected':''}>30 seconds</option><option value="60"${appLockSettings.lockDelaySeconds===60?' selected':''}>1 minute</option><option value="300"${appLockSettings.lockDelaySeconds===300?' selected':''}>5 minutes</option></select></label><p class="account-note">Requires a secure Android screen lock. Screenshots are hidden as soon as you leave; mail sync continues in the background.</p>`:'';
const localDataSetting=localDataBridge?`<h3 class="pgp-heading">Local data</h3><p class="account-note">Delete saved accounts, cached mail, drafts, queued sends, OpenPGP keys, app settings, and attachments saved by ep-mail to Downloads.</p><button class="discard" id="delete-all-local-data">Delete all local data…</button>`:'';
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}${localDataSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
const close=()=>root.innerHTML='';
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge)await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked);productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}};
selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge){await appLockBridge.setAppLockDelay(Number(selectProductivityUi('#app-lock-delay').value));await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked)}productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}};
if(localDataBridge)selectProductivityUi('#delete-all-local-data').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await localDataBridge.deleteAllLocalData();if(!result?.deleted){button.disabled=false;return}if('serviceWorker'in navigator){const registrations=await navigator.serviceWorker.getRegistrations();await Promise.all(registrations.map(registration=>registration.unregister()))}if('caches'in window){const names=await caches.keys();await Promise.all(names.map(name=>caches.delete(name)))}localStorage.clear();window.location.reload()}catch(error){button.disabled=false;toastProductivityUi(error.message||'Native data was deleted, but browser data cleanup did not finish. Restart ep-mail to complete cleanup.')}};
selectProductivityUi('#theme-select').focus();
}
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
+2
View File
@@ -10,6 +10,8 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
setNotificationDetails: enabled => EpMail.setNotificationDetails({ enabled }),
getAppLockSettings: () => EpMail.getAppLockSettings(),
setAppLockEnabled: enabled => EpMail.setAppLockEnabled({ enabled }),
setAppLockDelay: seconds => EpMail.setAppLockDelay({ seconds }),
deleteAllLocalData: () => EpMail.deleteAllLocalData(),
getAccount: () => EpMail.getAccount(),
listAccounts: () => EpMail.listAccounts(),
selectAccount: id => EpMail.selectAccount({ id }),
+174 -19
View File
@@ -118,6 +118,26 @@ function parseInnerMime(bytes) {
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() {
const bytes = crypto.getRandomValues(new Uint8Array(18));
return `=_ep-${Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('')}`;
@@ -171,7 +191,71 @@ function toBase64(bytes) {
return btoa(binary);
}
export function createAndroidPgp({ EpMail, getAccount }) {
function bytesToLatin1(bytes) {
let text = '';
for (let index = 0; index < bytes.length; index += 0x8000) {
text += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return text;
}
function splitSignedMime(source, boundary) {
if (!boundary || boundary.length > 200) return null;
const text = bytesToLatin1(source);
const escaped = boundary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
const marks = [...text.matchAll(delimiter)];
if (marks.length < 3) return null;
const contentAfter = mark => {
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
return lineEnd < 0 ? text.length : lineEnd + 1;
};
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n');
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
const signature = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
if (!signature) return null;
return { signed: Uint8Array.from(signed, char => char.charCodeAt(0) & 255), signature };
}
function senderFrom(headers) {
const value = String(headers.from || '');
return (/<([^<>]+)>/.exec(value)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(value)?.[0] || '').toLowerCase();
}
function invalidSignature() {
return { status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null,
matchesSender: false, keyChanged: false };
}
async function signatureStatuses(signatures, verification, sender) {
const results = [];
for (const signature of signatures || []) {
const keyId = signature.keyID.toHex().toUpperCase();
const known = verification.find(candidate => candidate.key.getKeys()
.some(key => key.getKeyID().toHex().toUpperCase() === keyId));
let status = 'valid';
try { await signature.verified; }
catch { status = known ? 'invalid' : 'unknown-key'; }
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const matchesSender = Boolean(sender && keyEmails.includes(sender));
const changed = Boolean(sender && verification.some(candidate =>
!candidate.entry.own && candidate.entry.emails?.includes(sender) &&
candidate.entry.fingerprint !== known?.entry.fingerprint));
results.push({
status,
keyId,
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {})
});
}
return results;
}
export function createAndroidPgp({ EpMail, getAccount, confirm = globalThis.confirm }) {
let storePromise;
const passphrases = new Map();
let cacheMinutes = 10;
@@ -251,16 +335,26 @@ export function createAndroidPgp({ EpMail, getAccount }) {
async function unlock(fingerprint, passphrase) {
const entry = (await store()).keys.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
const secret = passphrase || await biometricPassphrase(fingerprint);
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email || 'your key'}.`), { code: 'PASSPHRASE_REQUIRED' });
return unlockWithPassphrase(entry, secret);
}
async function unlockWithPassphrase(entry, passphrase) {
try { return await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: entry.privateKey }), passphrase }); }
catch { throw new Error('The passphrase is incorrect.'); }
}
async function biometricPassphrase(fingerprint) {
if (typeof EpMail.getPgpBiometricPassphrase !== 'function') return null;
const result = await EpMail.getPgpBiometricPassphrase({ fingerprint });
return result?.enabled && typeof result.passphrase === 'string' ? result.passphrase : null;
}
async function signerFor(account, passphrase) {
const data = await store();
const entry = data.keys.find(item => item.email.toLowerCase() === String(account.email).toLowerCase());
if (!entry) throw Object.assign(new Error('Create or import an encryption key for this address first.'), { code: 'NO_SIGNING_KEY' });
const secret = passphrase || cached(entry.fingerprint);
const secret = passphrase || cached(entry.fingerprint) || await biometricPassphrase(entry.fingerprint);
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email} to sign this message.`), { code: 'PASSPHRASE_REQUIRED', fingerprint: entry.fingerprint, email: entry.email });
try { const key = await unlock(entry.fingerprint, secret); cache(entry.fingerprint, secret); return { key, entry }; }
try { const key = await unlockWithPassphrase(entry, secret); cache(entry.fingerprint, secret); return { key, entry }; }
catch { clear(entry.fingerprint); throw Object.assign(new Error('The passphrase is incorrect.'), { code: 'BAD_PASSPHRASE', fingerprint: entry.fingerprint, email: entry.email }); }
}
async function buildOutgoing(message) {
@@ -279,6 +373,16 @@ export function createAndroidPgp({ EpMail, getAccount }) {
if (pgp.encrypt && recipientKeys.missing.length) {
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(', ')}.`), { code: 'NO_RECIPIENT_KEY', missing: recipientKeys.missing });
}
const unverifiedKeys = recipientKeys.keys.filter(item => item.trust !== 'verified');
if (pgp.encrypt && unverifiedKeys.length) {
const details = unverifiedKeys.map(item =>
`${item.address}\n${item.fingerprint.match(/.{1,4}/g).join(' ')} (${item.trust})`
).join('\n\n');
const warning = `These recipient keys have not been verified by fingerprint:\n\n${details}\n\nIf a key is incorrect, its owner may be able to read this message. Compare each fingerprint with its owner through another channel before sending. Send encrypted mail to these unverified keys anyway?`;
if (typeof confirm !== 'function' || !confirm(warning)) {
throw Object.assign(new Error('Sending to unverified recipient keys was cancelled.'), { code: 'UNVERIFIED_RECIPIENT_KEY' });
}
}
let inner = mimeInner(`${String(message.text || '').slice(0, 500000)}${account.signature ? `\n\n${String(account.signature).slice(0, 5000)}` : ''}`, message.attachments || []);
const headers = [
`From: ${formatAddress(from)}`,
@@ -341,6 +445,7 @@ export function createAndroidPgp({ EpMail, getAccount }) {
selected = candidates.find(entry => cached(entry.fingerprint)) || selected;
secret = cached(selected.fingerprint);
}
if (!secret) secret = await biometricPassphrase(selected.fingerprint);
if (!secret) return { failed: true, code: 'PASSPHRASE_REQUIRED', fingerprint: selected.fingerprint, email: selected.email, message: 'Enter your key passphrase to read this message.' };
let privateKey;
try { privateKey = await unlock(selected.fingerprint, secret); }
@@ -351,28 +456,55 @@ export function createAndroidPgp({ EpMail, getAccount }) {
try { decrypted = await openpgp.decrypt({ message, decryptionKeys: privateKey, verificationKeys: verify.map(item => item.key), format: 'binary' }); }
catch { return { failed: true, code: 'CORRUPT', message: 'The message could not be decrypted. It may be damaged or altered.' }; }
const content = parseInnerMime(decrypted.data);
const signatures = [];
for (const item of decrypted.signatures || []) {
const known = verify.find(candidate => candidate.key.getKeys().some(key => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
let status = 'valid';
try { await item.verified; } catch { status = known ? 'invalid' : 'unknown-key'; }
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || '';
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || '').toLowerCase();
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const changed = Boolean(sender && data.contacts.some(entry => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
const matchesSender = Boolean(sender && keyEmails.includes(sender));
signatures.push({ status, keyId: item.keyID.toHex().toUpperCase(), fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null, email: keyEmails[0] || null, matchesSender, keyChanged: changed,
...(status === 'valid' && known && sender && !matchesSender ? { mismatch: true } : {}) });
}
const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
const attachedKeys = await attachedPublicKeys(content.attachments);
return { ok: true, body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [], html: content.html,
links: [], attachments: content.attachments, attachment: content.attachments[0]?.filename || null,
size: content.attachments[0]?.size || '', signatures, attachedKeys: [] };
size: content.attachments[0]?.size || '', signatures, attachedKeys };
} catch (error) {
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 = {
platform: 'android',
async list() { return (await store()).keys.map(publicInfo); },
@@ -418,6 +550,23 @@ export function createAndroidPgp({ EpMail, getAccount }) {
entry.privateKey = protectedKey.armor(); await persist(data); clear(fingerprint); return { changed: true };
},
async remove(fingerprint, passphrase) { const data = await store(); const entry = data.keys.find(item => item.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); await unlock(fingerprint, passphrase); data.keys = data.keys.filter(item => item.fingerprint !== fingerprint); await persist(data); clear(fingerprint); return { removed: true }; },
async enableBiometricUnlock({ fingerprint, passphrase }) {
if (typeof EpMail.setPgpBiometricUnlock !== 'function') throw new Error('Biometric key unlock is not available on this device.');
const entry = (await store()).keys.find(item => item.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
if (!passphrase) throw new Error('Enter the key passphrase first.');
await unlockWithPassphrase(entry, passphrase);
return EpMail.setPgpBiometricUnlock({ fingerprint, passphrase });
},
async biometricUnlockEnabled(fingerprint) {
if (typeof EpMail.pgpBiometricUnlockEnabled !== 'function') return false;
return Boolean((await EpMail.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled);
},
async disableBiometricUnlock(fingerprint) {
if (typeof EpMail.removePgpBiometricUnlock !== 'function') throw new Error('Biometric key unlock is not available on this device.');
clear(fingerprint);
return EpMail.removePgpBiometricUnlock({ fingerprint });
},
async contacts() { return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt })); },
async addContact(input = {}) {
const armoredKey = input.armoredKey || prompt('Paste an ASCII-armored OpenPGP public key (up to 200 KB):') || '';
@@ -436,10 +585,16 @@ export function createAndroidPgp({ EpMail, getAccount }) {
const { keys, missing } = await resolveRecipients(addresses);
const account = await getAccount();
const entry = sign ? (await store()).keys.find(item => item.email.toLowerCase() === String(account?.email || '').toLowerCase()) : null;
let biometricUnlockEnabled = false;
if (entry && typeof EpMail.pgpBiometricUnlockEnabled === 'function') {
biometricUnlockEnabled = Boolean((await EpMail.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled);
}
return { recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })), missing,
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null };
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name,
unlocked: Boolean(cached(entry.fingerprint)), biometricUnlockEnabled } : null };
},
decryptMessage,
verifyMessage,
async getSettings() { const data = await store(); return { cacheMinutes }; },
async setSettings({ cacheMinutes: 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'];
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())));
+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, confirm: () => true }),
setMessage(rawBase64) { messageSource = { rawBase64 }; }
};
}
function setupGpg() {
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-android-gnupg-'));
const gpg = (args, input) => {
const result = spawnSync(gpgPath, [
'--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback',
'--passphrase', PASSPHRASE, '--trust-model', 'always', ...args
], { input });
if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`);
return { out: result.stdout, err: result.stderr.toString() };
};
gpg(['--quick-generate-key', 'Gina Gnu <gina@example.test>', 'ed25519', 'cert', 'never']);
const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(
gpg(['--list-keys', '--with-colons', 'gina@example.test']).out.toString()
)?.[1];
if (!fingerprint) throw new Error('Could not find the generated GnuPG test key fingerprint.');
gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']);
gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']);
return { home, fingerprint, gpg };
}
function encryptedMime(from, to, armor) {
const boundary = 'android-gnupg-encrypted';
return Buffer.from([
`From: ${from}`,
`To: ${to}`,
'Subject: Android GnuPG interoperability',
'MIME-Version: 1.0',
`Content-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${boundary}"`,
'',
`--${boundary}`,
'Content-Type: application/pgp-encrypted',
'',
'Version: 1',
`--${boundary}`,
'Content-Type: application/octet-stream; name="encrypted.asc"',
'',
armor.trim(),
`--${boundary}--`,
''
].join('\r\n'));
}
test('Android OpenPGP PGP/MIME interoperates with GnuPG for send, read, and signature verification', { skip }, async () => {
const { home, fingerprint, gpg } = setupGpg();
try {
const android = makeEndpoint({ email: 'android@example.test', displayName: 'Android User', signature: '' });
const own = await android.api.generate({
name: 'Android User', email: 'android@example.test', passphrase: 'android key test passphrase'
});
const gpgPublic = gpg(['--armor', '--export', 'gina@example.test']).out.toString();
await android.api.addContact({ armoredKey: gpgPublic });
gpg(['--import'], Buffer.from(await android.api.exportPublic(own.key.fingerprint)));
const outgoing = await android.api.buildOutgoing({
to: 'Gina Gnu <gina@example.test>',
cc: '',
subject: 'Android to GnuPG',
text: 'Encrypted and signed from the Android OpenPGP module',
messageId: '<android-to-gnupg@example.test>',
pgp: { encrypt: true, sign: true, passphrase: 'android key test passphrase' },
attachments: []
});
const outboundText = Buffer.from(outgoing.rawBase64, 'base64').toString('utf8');
const outboundArmor = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(outboundText)?.[0];
assert.ok(outboundArmor, 'Android output should contain an armored encrypted message');
const decrypted = gpg(['--decrypt'], Buffer.from(outboundArmor));
assert.match((await simpleParser(decrypted.out)).text, /Encrypted and signed from the Android OpenPGP module/);
assert.match(decrypted.err, /Good signature from/);
const incomingInner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nSigned and encrypted by GnuPG\r\n');
const incomingArmor = gpg([
'--armor', '--encrypt', '--sign', '--local-user', 'gina@example.test', '--recipient', 'android@example.test'
], incomingInner).out.toString();
android.setMessage(encryptedMime('Gina Gnu <gina@example.test>', 'android@example.test', incomingArmor).toString('base64'));
const opened = await android.api.decryptMessage({ folder: 'Inbox', uid: 11, passphrase: 'android key test passphrase' });
assert.equal(opened.ok, true, opened.message);
assert.deepEqual(opened.body, ['Signed and encrypted by GnuPG']);
assert.equal(opened.signatures[0].status, 'valid');
assert.equal(opened.signatures[0].matchesSender, true);
const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nGnuPG detached signed body';
const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.test'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim();
const signedBoundary = 'android-gnupg-signed';
const signedMime = Buffer.from([
'From: Gina Gnu <gina@example.test>',
'To: android@example.test',
'MIME-Version: 1.0',
`Content-Type: multipart/signed; protocol="application/pgp-signature"; boundary="${signedBoundary}"`,
'',
`--${signedBoundary}`,
signedPart,
`--${signedBoundary}`,
'Content-Type: application/pgp-signature',
'',
detached,
`--${signedBoundary}--`,
''
].join('\r\n'));
android.setMessage(signedMime.toString('base64'));
const signedMimeResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 12 });
assert.equal(signedMimeResult.signatures[0].status, 'valid');
assert.equal(signedMimeResult.signatures[0].matchesSender, true);
const clearSigned = gpg(['--clearsign', '--local-user', 'gina@example.test'], Buffer.from('GnuPG clear-signed body\n')).out.toString();
const clearSource = Buffer.from(
`From: Gina Gnu <gina@example.test>\r\nTo: android@example.test\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n${clearSigned}\r\n`
);
android.setMessage(clearSource.toString('base64'));
const clearResult = await android.api.verifyMessage({ folder: 'Inbox', uid: 13 });
assert.equal(clearResult.signatures[0].status, 'valid');
assert.equal(clearResult.signatures[0].matchesSender, true);
} finally {
fs.rmSync(home, { recursive: true, force: true });
}
});
+166 -3
View File
@@ -4,6 +4,7 @@ const path = require('node:path');
const vm = require('node:vm');
const esbuild = require('esbuild');
const { webcrypto } = require('node:crypto');
const openpgp = require('openpgp');
global.crypto ||= webcrypto;
global.document ||= { addEventListener() {} };
@@ -19,7 +20,7 @@ const bundled = esbuild.buildSync({
vm.runInThisContext(bundled);
const { createAndroidPgp } = global.AndroidPgpBundle;
function makeEndpoint(account) {
function makeEndpoint(account, { confirm = () => true } = {}) {
const vault = { keys: [], contacts: [], settings: {} };
let messageSource = null;
const EpMail = {
@@ -28,7 +29,8 @@ function makeEndpoint(account) {
async pgpGetMessageSource() { return messageSource; }
};
return {
api: createAndroidPgp({ EpMail, getAccount: async () => account }),
api: createAndroidPgp({ EpMail, getAccount: async () => account, confirm }),
EpMail,
setMessage(value) { messageSource = value; },
vault
};
@@ -37,15 +39,20 @@ function makeEndpoint(account) {
test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient key', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const 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 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 recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) });
const built = await sender.api.buildOutgoing({
to: 'Bob <bob@example.test>', cc: '', subject: 'Secret note', text: 'hello from Android',
messageId: '<test-message@example.test>', pgp: { encrypt: true, sign: true, passphrase: 'alice test passphrase' },
attachments: [{ filename: 'note.txt', contentType: 'text/plain', contentBase64: Buffer.from('private attachment').toString('base64') }]
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);
const raw = Buffer.from(built.rawBase64, 'base64').toString('utf8');
@@ -62,6 +69,8 @@ test('Android OpenPGP encrypts MIME attachments and decrypts with a recipient ke
assert.deepEqual(opened.body, ['hello from Android']);
assert.equal(opened.attachments[0].filename, 'note.txt');
assert.equal(Buffer.from(opened.attachments[0].contentBase64, 'base64').toString(), 'private attachment');
assert.equal(opened.attachedKeys[0].fingerprint, charlie.key.fingerprint);
assert.deepEqual(opened.attachedKeys[0].emails, ['charlie@example.test']);
assert.equal(opened.signatures[0].status, 'valid');
await recipient.api.setSettings({ cacheMinutes: 0 });
assert.equal((await recipient.api.getSettings()).cacheMinutes, 0);
@@ -75,3 +84,157 @@ 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: []
}), error => error.code === 'NO_RECIPIENT_KEY');
});
test('Android OpenPGP requires explicit fingerprint confirmation for unverified recipient keys', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' }, {
confirm: warning => {
assert.match(warning, /bob@example\.test/);
assert.match(warning, /[A-F0-9]{4}(?: [A-F0-9]{4}){9}/);
assert.match(warning, /not been verified by fingerprint/);
assert.match(warning, /Compare each fingerprint with its owner through another channel/);
return false;
}
});
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
await assert.rejects(sender.api.buildOutgoing({
to: 'bob@example.test', text: 'do not send to an unverified key',
pgp: { encrypt: true }, attachments: []
}), error => error.code === 'UNVERIFIED_RECIPIENT_KEY');
});
test('Android verifies PGP/MIME signed-only and clear-signed mail', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const created = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(created.key.fingerprint) });
const signedMime = await sender.api.buildOutgoing({
to: 'Bob <bob@example.test>', cc: '', subject: 'Signed note', text: 'signed MIME body',
pgp: { encrypt: false, sign: true, passphrase: 'alice test passphrase' }, attachments: []
});
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');
});
test('Android biometric unlock remains optional and releases only a passphrase-verified PGP key', async () => {
const sender = makeEndpoint({ email: 'alice@example.test', displayName: 'Alice', signature: '' });
const recipient = makeEndpoint({ email: 'bob@example.test', displayName: 'Bob', signature: '' });
const alice = await sender.api.generate({ name: 'Alice', email: 'alice@example.test', passphrase: 'alice test passphrase' });
const bob = await recipient.api.generate({ name: 'Bob', email: 'bob@example.test', passphrase: 'bob test passphrase' });
await sender.api.addContact({ armoredKey: await recipient.api.exportPublic(bob.key.fingerprint) });
await recipient.api.addContact({ armoredKey: await sender.api.exportPublic(alice.key.fingerprint) });
let protectedPassphrase = null;
recipient.EpMail.setPgpBiometricUnlock = async ({ fingerprint, passphrase }) => {
assert.equal(fingerprint, bob.key.fingerprint);
protectedPassphrase = passphrase;
return { enabled: true };
};
recipient.EpMail.getPgpBiometricPassphrase = async ({ fingerprint }) => ({
enabled: fingerprint === bob.key.fingerprint && protectedPassphrase !== null,
passphrase: protectedPassphrase
});
recipient.EpMail.pgpBiometricUnlockEnabled = async () => ({ enabled: protectedPassphrase !== null });
await assert.rejects(
recipient.api.enableBiometricUnlock({ fingerprint: bob.key.fingerprint, passphrase: 'incorrect passphrase' }),
/incorrect/
);
assert.equal(protectedPassphrase, null);
await recipient.api.enableBiometricUnlock({ fingerprint: bob.key.fingerprint, passphrase: 'bob test passphrase' });
assert.equal((await recipient.api.checkSend({ to: 'bob@example.test', sign: true })).signer.biometricUnlockEnabled, true);
const built = await sender.api.buildOutgoing({
to: 'bob@example.test', subject: 'Biometric unlock test', text: 'protected body',
pgp: { encrypt: true }, attachments: []
});
recipient.setMessage({ rawBase64: built.rawBase64 });
const opened = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 23 });
assert.equal(opened.ok, true, opened.message);
assert.deepEqual(opened.body, ['protected body']);
assert.equal(Object.hasOwn(recipient.vault.keys[0], 'passphrase'), false);
assert.equal(Object.hasOwn(recipient.vault, 'passphrase'), false);
await recipient.api.setSettings({ cacheMinutes: 0 });
recipient.EpMail.getPgpBiometricPassphrase = async () => {
throw Object.assign(new Error('Biometric enrollment changed.'), { code: 'BIOMETRIC_INVALIDATED' });
};
const invalidated = await recipient.api.decryptMessage({ folder: 'Inbox', uid: 23 });
assert.equal(invalidated.code, 'BIOMETRIC_INVALIDATED');
const recovered = await recipient.api.decryptMessage({
folder: 'Inbox', uid: 23, passphrase: 'bob test passphrase'
});
assert.equal(recovered.ok, true, recovered.message);
});
+71
View File
@@ -17,8 +17,14 @@ const androidPgpConfirmationGate = fs.readFileSync(path.join(root, 'android', 'a
const productivity = fs.readFileSync(path.join(root, 'productivity.js'), 'utf8');
const androidBridge = fs.readFileSync(path.join(root, 'scripts', 'android-bridge.js'), 'utf8');
const androidPgp = fs.readFileSync(path.join(root, 'scripts', 'android-pgp.js'), 'utf8');
const pgpMailUi = fs.readFileSync(path.join(root, 'pgp-mail-ui.js'), 'utf8');
const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8'));
const index = fs.readFileSync(path.join(root, 'index.html'), 'utf8');
const manifest = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'AndroidManifest.xml'), 'utf8');
const davService = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidDavService.kt'), 'utf8');
const biometricUnlock = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'AndroidPgpBiometricUnlock.kt'), 'utf8');
const boundedInputReader = fs.readFileSync(path.join(root, 'android', 'app', 'src', 'main', 'java', 'studio', 'daybreak', 'mail', 'BoundedInputReader.kt'), 'utf8');
test('mobile layout removes desktop minimum width and provides a compact reader flow', () => {
assert.match(styles, /min-width:320px/);
@@ -78,7 +84,64 @@ test('Android app lock is native-enforced and requires a secure device credentia
assert.match(mainActivity, /setJavaScriptEnabled\(false\)/);
assert.match(androidBridge, /getAppLockSettings/);
assert.match(androidBridge, /setAppLockEnabled/);
assert.match(androidBridge, /setAppLockDelay/);
assert.match(productivity, /Lock when leaving ep-mail/);
assert.match(productivity, /app-lock-delay/);
assert.match(mainActivity, /postDelayed\(delayedAppLock/);
assert.match(mainActivity, /FLAG_SECURE/);
});
test('Android biometric PGP unlock keeps secrets behind an authentication-bound Keystore key', () => {
assert.match(plugin, /fun setPgpBiometricUnlock/);
assert.match(plugin, /fun getPgpBiometricPassphrase/);
assert.match(plugin, /fun removePgpBiometricUnlock/);
assert.match(plugin, /fun pgpBiometricUnlockEnabled/);
assert.match(mainActivity, /authenticatePgpCipher/);
assert.match(mainActivity, /pgpAuthInProgress/);
assert.match(biometricUnlock, /setUserAuthenticationRequired\(true\)/);
assert.match(biometricUnlock, /setUserAuthenticationParameters/);
assert.match(vault, /pgpBiometricUnlocks/);
assert.match(vault, /removedFingerprints\.forEach/);
assert.match(androidPgp, /enableBiometricUnlock/);
assert.match(androidPgp, /getPgpBiometricPassphrase/);
assert.match(pgpMailUi, /BIOMETRIC_INVALIDATED/);
});
test('Android full local-data deletion is explicit, scoped, and clears stored web data', () => {
assert.match(productivity, /Delete all local data/);
assert.match(androidBridge, /deleteAllLocalData/);
assert.match(plugin, /fun deleteAllLocalData/);
assert.match(plugin, /setPositiveButton\("Delete all data"\)/);
assert.match(vault, /fun wipe\(\)/);
assert.match(androidMailService, /fun deleteSavedAttachments/);
assert.match(androidMailService, /isAppOwnedDownload/);
assert.match(androidMailService, /BoundedInputReader\.read\(it, 5 \* 1048576 \+ 1\)/);
assert.match(androidMailService, /BoundedInputReader\.read\(it, 100001\)/);
assert.match(androidMailService, /saveAttachmentStream/);
assert.match(boundedInputReader, /while \(output\.size\(\) < maxBytes\)/);
assert.match(mainActivity, /clearLocalWebData/);
assert.match(productivity, /getRegistrations\(\)/);
assert.match(productivity, /caches\.delete\(name\)/);
});
test('Android WebView CSP, manifest, navigation, and DAV transport stay constrained', () => {
const csp = /http-equiv="Content-Security-Policy" content="([^"]+)"/i.exec(index)?.[1] || '';
assert.match(csp, /default-src 'self'/);
assert.match(csp, /script-src 'self'/);
assert.match(csp, /connect-src 'none'/);
assert.match(csp, /frame-src 'none'/);
assert.match(csp, /object-src 'none'/);
assert.match(csp, /base-uri 'none'/);
assert.match(csp, /form-action 'none'/);
assert.doesNotMatch(csp, /script-src[^;]*unsafe-inline/i);
assert.match(manifest, /android:allowBackup="false"/);
assert.match(manifest, /android:usesCleartextTraffic="false"/);
assert.doesNotMatch(manifest, /READ_EXTERNAL_STORAGE|WRITE_EXTERNAL_STORAGE|MANAGE_EXTERNAL_STORAGE|REQUEST_INSTALL_PACKAGES/);
assert.match(plugin, /Only standard web links can be opened from mail/);
assert.match(plugin, /uri\.scheme\?\.lowercase\(Locale\.ROOT\) !in setOf\("http", "https"\)/);
assert.match(davService, /followRedirects\(false\)/);
assert.match(davService, /followSslRedirects\(false\)/);
assert.match(davService, /DavUrlPolicy\.requireSameOrigin/);
});
test('Android OpenPGP uses the encrypted vault and queues only built MIME data', () => {
@@ -87,6 +150,8 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data',
assert.match(plugin, /fun pgpGetMessageSource/);
assert.match(plugin, /pgpStoreChangeWarning/);
assert.match(plugin, /plaintextSendWarning/);
assert.match(plugin, /AndroidPgpPolicy\.unverifiedRawMimeWarning\(\)/);
assert.match(plugin, /title = if \(rawMime\) "Send unverified MIME\?"/);
assert.match(plugin, /Send plaintext/);
assert.match(plugin, /showPgpConfirmation\(/);
assert.match(plugin, /onCancelled = \{ call\.reject\("OpenPGP key change cancelled\."\) \}/);
@@ -95,9 +160,15 @@ test('Android OpenPGP uses the encrypted vault and queues only built MIME data',
assert.match(androidPgpConfirmationGate, /compareAndSet\(false, true\)/);
assert.match(androidPgpPolicy, /fun storeChangeWarning/);
assert.match(androidPgpPolicy, /fun plaintextSendWarning/);
assert.match(androidPgpPolicy, /fun unverifiedRawMimeWarning/);
assert.match(androidPgp, /curve25519Legacy/);
assert.match(androidPgp, /These recipient keys have not been verified by fingerprint/);
assert.match(androidPgp, /multipart\/encrypted/);
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, /rawBase64, envelope: \{ from, to \}, text: '', attachments: \[\]/);
assert.match(androidMailService, /validateOpenPgpMime\(message\)/);
+33 -4
View File
@@ -74,6 +74,12 @@ function pgpRenderReaderState(message) {
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) {
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
} else if (message.signed && Array.isArray(message.pgpSignatures)) {
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);
}
@@ -104,9 +110,14 @@ async function pgpUnlockMessage(message, interactive) {
if (pgpMailUi.state.activeMessage === message.id) pgpMailUi.openMessage(message.id);
return;
}
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE' || result.code === 'BIOMETRIC_INVALIDATED') {
if (!interactive) { pgpRenderReaderState(message); return; }
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
const prompt = result.code === 'BAD_PASSPHRASE'
? 'That passphrase was incorrect. Try again.'
: result.code === 'BIOMETRIC_INVALIDATED'
? `${result.message} Enter the passphrase to continue.`
: `Enter the passphrase for ${result.email || 'your key'}.`;
passphrase = await pgpAskPassphrase('Unlock encrypted message', prompt);
if (passphrase === null) return;
continue;
}
@@ -117,6 +128,20 @@ async function pgpUnlockMessage(message, interactive) {
}
}
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) {
baseOpenMessage(id);
const message = pgpMailUi.state.messages.find(item => item.id === id);
@@ -126,6 +151,10 @@ pgpMailUi.wrapOpenMessage(baseOpenMessage => function (id) {
message.pgpAutoTried = true;
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.
@@ -155,7 +184,7 @@ pgpMailUi.wrapShowCompose(baseShowCompose => function (reply, forward = false) {
if (!selectPgpMailUi('#pgp-hint')) return;
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
else {
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
hint.textContent = status.recipients.some(item => item.trust !== 'verified') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
if (!touched && !encrypt.checked) encrypt.checked = true;
}
} catch { hint.textContent = ''; }
@@ -192,7 +221,7 @@ async function prepareSend(to, cc) {
let passphrase = null;
if (sign) {
if (!status.signer) { toastPgpMailUi('Create or import an encryption key for your address before signing'); return false; }
if (!status.signer.unlocked) {
if (!status.signer.unlocked && !status.signer.biometricUnlockEnabled) {
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
if (passphrase === null) return false;
}
+37 -1
View File
@@ -35,7 +35,7 @@ function openEncryptionKeys() {
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>`;
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
<p class="account-note">${androidPgp ? 'EXPERIMENTAL ANDROID TESTING — not independently security reviewed. Private keys remain passphrase-protected inside the encrypted Android vault. Optional biometric unlock stores the passphrase in a Keystore key requiring user authentication. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.' : 'OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered.'} Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
<h3 class="pgp-heading">Change a key passphrase</h3>
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
@@ -138,6 +138,42 @@ function openEncryptionKeys() {
}
};
row.append(changePassphrase);
if (androidPgp) {
const biometric = document.createElement('button');
biometric.className = 'discard';
biometric.textContent = 'Checking biometric unlock…';
biometric.disabled = true;
row.append(biometric);
window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => {
if (!biometric.isConnected) return;
biometric.dataset.enabled = String(enabled);
biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…';
biometric.disabled = false;
}).catch(error => {
if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.');
});
biometric.onclick = async () => {
biometric.disabled = true;
try {
if (biometric.dataset.enabled === 'true') {
if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return;
await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint);
status('Biometric unlock disabled.');
} else {
const passphrase = needPassphrase();
if (!passphrase) return;
await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase });
passphraseField().value = '';
status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.');
}
await render();
} catch (error) {
status(error.message || 'Could not update biometric key unlock.');
} finally {
biometric.disabled = false;
}
};
}
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
actions.push(['Delete', async () => {
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
+255 -30
View File
@@ -5738,6 +5738,7 @@
super(e2, t2);
}
};
var ka = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var Ea = class {
constructor(e2) {
this.packets = e2 || new Gs();
@@ -5753,6 +5754,22 @@
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) {
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;
@@ -6874,6 +6891,7 @@
const f2 = new no(h2);
return f2.fromStream = c2, f2;
}
var co = /* @__PURE__ */ N.constructAllowedPackets([Ns]);
var uo = class _uo {
constructor(e2, t2) {
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);
}
};
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 }) {
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);
@@ -7011,6 +7061,23 @@
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) {
if (!(e2 instanceof no)) throw Error("Parameter [message] needs to be of type Message");
}
@@ -9896,6 +9963,25 @@
visit(bytes);
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() {
const bytes = crypto.getRandomValues(new Uint8Array(18));
return `=_ep-${Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join("")}`;
@@ -9961,7 +10047,73 @@ ${parts.join("")}`;
for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
return btoa(binary);
}
function createAndroidPgp({ EpMail: EpMail2, getAccount }) {
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, confirm = globalThis.confirm }) {
let storePromise;
const passphrases = /* @__PURE__ */ new Map();
let cacheMinutes = 10;
@@ -10088,20 +10240,30 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
async function unlock(fingerprint, passphrase) {
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
if (!entry) throw new Error("That key was not found.");
const secret = passphrase || await biometricPassphrase(fingerprint);
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email || "your key"}.`), { code: "PASSPHRASE_REQUIRED" });
return unlockWithPassphrase(entry, secret);
}
async function unlockWithPassphrase(entry, passphrase) {
try {
return await po({ privateKey: await Wa({ armoredKey: entry.privateKey }), passphrase });
} catch {
throw new Error("The passphrase is incorrect.");
}
}
async function biometricPassphrase(fingerprint) {
if (typeof EpMail2.getPgpBiometricPassphrase !== "function") return null;
const result = await EpMail2.getPgpBiometricPassphrase({ fingerprint });
return result?.enabled && typeof result.passphrase === "string" ? result.passphrase : null;
}
async function signerFor(account, passphrase) {
const data = await store();
const entry = data.keys.find((item) => item.email.toLowerCase() === String(account.email).toLowerCase());
if (!entry) throw Object.assign(new Error("Create or import an encryption key for this address first."), { code: "NO_SIGNING_KEY" });
const secret = passphrase || cached(entry.fingerprint);
const secret = passphrase || cached(entry.fingerprint) || await biometricPassphrase(entry.fingerprint);
if (!secret) throw Object.assign(new Error(`Enter the passphrase for ${entry.email} to sign this message.`), { code: "PASSPHRASE_REQUIRED", fingerprint: entry.fingerprint, email: entry.email });
try {
const key = await unlock(entry.fingerprint, secret);
const key = await unlockWithPassphrase(entry, secret);
cache(entry.fingerprint, secret);
return { key, entry };
} catch {
@@ -10125,6 +10287,21 @@ Add the new key as an unverified key? Compare fingerprints with the owner before
if (pgp.encrypt && recipientKeys.missing.length) {
throw Object.assign(new Error(`No public key for ${recipientKeys.missing.join(", ")}.`), { code: "NO_RECIPIENT_KEY", missing: recipientKeys.missing });
}
const unverifiedKeys = recipientKeys.keys.filter((item) => item.trust !== "verified");
if (pgp.encrypt && unverifiedKeys.length) {
const details = unverifiedKeys.map(
(item) => `${item.address}
${item.fingerprint.match(/.{1,4}/g).join(" ")} (${item.trust})`
).join("\n\n");
const warning = `These recipient keys have not been verified by fingerprint:
${details}
If a key is incorrect, its owner may be able to read this message. Compare each fingerprint with its owner through another channel before sending. Send encrypted mail to these unverified keys anyway?`;
if (typeof confirm !== "function" || !confirm(warning)) {
throw Object.assign(new Error("Sending to unverified recipient keys was cancelled."), { code: "UNVERIFIED_RECIPIENT_KEY" });
}
}
let inner = mimeInner(`${String(message.text || "").slice(0, 5e5)}${account.signature ? `
${String(account.signature).slice(0, 5e3)}` : ""}`, message.attachments || []);
@@ -10212,6 +10389,7 @@ ${body}`);
selected = candidates.find((entry) => cached(entry.fingerprint)) || selected;
secret = cached(selected.fingerprint);
}
if (!secret) secret = await biometricPassphrase(selected.fingerprint);
if (!secret) return { failed: true, code: "PASSPHRASE_REQUIRED", fingerprint: selected.fingerprint, email: selected.email, message: "Enter your key passphrase to read this message." };
let privateKey;
try {
@@ -10229,31 +10407,8 @@ ${body}`);
return { failed: true, code: "CORRUPT", message: "The message could not be decrypted. It may be damaged or altered." };
}
const content = parseInnerMime(decrypted.data);
const signatures = [];
for (const item of decrypted.signatures || []) {
const known = verify.find((candidate) => candidate.key.getKeys().some((key) => key.getKeyID().toHex().toUpperCase() === item.keyID.toHex().toUpperCase()));
let status = "valid";
try {
await item.verified;
} catch {
status = known ? "invalid" : "unknown-key";
}
const from = /^From:\s*(.*)$/im.exec(text)?.[1] || "";
const sender = (/<([^<>]+)>/.exec(from)?.[1] || /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i.exec(from)?.[0] || "").toLowerCase();
const keyEmails = known?.entry.emails || (known?.entry.email ? [known.entry.email.toLowerCase()] : []);
const changed = Boolean(sender && data.contacts.some((entry) => entry.emails.includes(sender) && entry.fingerprint !== known?.entry.fingerprint));
const matchesSender = Boolean(sender && keyEmails.includes(sender));
signatures.push({
status,
keyId: item.keyID.toHex().toUpperCase(),
fingerprint: known?.entry.fingerprint || null,
trust: known?.entry.trust || null,
email: keyEmails[0] || null,
matchesSender,
keyChanged: changed,
...status === "valid" && known && sender && !matchesSender ? { mismatch: true } : {}
});
}
const signatures = await signatureStatuses(decrypted.signatures, verify, senderFrom(splitEntity(raw).headers));
const attachedKeys = await attachedPublicKeys(content.attachments);
return {
ok: true,
body: content.body ? content.body.split(/\n\s*\n/).filter(Boolean) : [],
@@ -10263,12 +10418,52 @@ ${body}`);
attachment: content.attachments[0]?.filename || null,
size: content.attachments[0]?.size || "",
signatures,
attachedKeys: []
attachedKeys
};
} catch (error) {
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 = {
platform: "android",
async list() {
@@ -10367,6 +10562,23 @@ ${body}`);
clear(fingerprint);
return { removed: true };
},
async enableBiometricUnlock({ fingerprint, passphrase }) {
if (typeof EpMail2.setPgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
const entry = (await store()).keys.find((item) => item.fingerprint === fingerprint);
if (!entry) throw new Error("That key was not found.");
if (!passphrase) throw new Error("Enter the key passphrase first.");
await unlockWithPassphrase(entry, passphrase);
return EpMail2.setPgpBiometricUnlock({ fingerprint, passphrase });
},
async biometricUnlockEnabled(fingerprint) {
if (typeof EpMail2.pgpBiometricUnlockEnabled !== "function") return false;
return Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint }))?.enabled);
},
async disableBiometricUnlock(fingerprint) {
if (typeof EpMail2.removePgpBiometricUnlock !== "function") throw new Error("Biometric key unlock is not available on this device.");
clear(fingerprint);
return EpMail2.removePgpBiometricUnlock({ fingerprint });
},
async contacts() {
return (await store()).contacts.map(({ fingerprint, name, emails, trust, source, addedAt }) => ({ fingerprint, name, emails, trust, source, addedAt }));
},
@@ -10406,13 +10618,24 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
const { keys, missing } = await resolveRecipients(addresses);
const account = await getAccount();
const entry = sign ? (await store()).keys.find((item) => item.email.toLowerCase() === String(account?.email || "").toLowerCase()) : null;
let biometricUnlockEnabled = false;
if (entry && typeof EpMail2.pgpBiometricUnlockEnabled === "function") {
biometricUnlockEnabled = Boolean((await EpMail2.pgpBiometricUnlockEnabled({ fingerprint: entry.fingerprint }))?.enabled);
}
return {
recipients: keys.map((item) => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
missing,
signer: entry ? { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: Boolean(cached(entry.fingerprint)) } : null
signer: entry ? {
fingerprint: entry.fingerprint,
email: entry.email,
name: entry.name,
unlocked: Boolean(cached(entry.fingerprint)),
biometricUnlockEnabled
} : null
};
},
decryptMessage,
verifyMessage,
async getSettings() {
const data = await store();
return { cacheMinutes };
@@ -10467,6 +10690,8 @@ Only continue if you checked this fingerprint with the owner.`)) throw new Error
setNotificationDetails: (enabled) => EpMail.setNotificationDetails({ enabled }),
getAppLockSettings: () => EpMail.getAppLockSettings(),
setAppLockEnabled: (enabled) => EpMail.setAppLockEnabled({ enabled }),
setAppLockDelay: (seconds) => EpMail.setAppLockDelay({ seconds }),
deleteAllLocalData: () => EpMail.deleteAllLocalData(),
getAccount: () => EpMail.getAccount(),
listAccounts: () => EpMail.listAccounts(),
selectAccount: (id) => EpMail.selectAccount({ id }),
+8 -5
View File
@@ -33,18 +33,21 @@ async function openPreferences() {
const selectedTheme=localStorage.getItem('daybreak-theme')||'ep-wasteland';
const options=themes.map(([value,label])=>`<option value="${value}"${value===selectedTheme?' selected':''}>${label}</option>`).join('');
const notificationBridge=window.daybreakMail?.getNotificationPrivacy&&window.daybreakMail?.setNotificationDetails?window.daybreakMail:null;
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled?window.daybreakMail:null;
const appLockBridge=window.daybreakMail?.getAppLockSettings&&window.daybreakMail?.setAppLockEnabled&&window.daybreakMail?.setAppLockDelay?window.daybreakMail:null;
const localDataBridge=window.daybreakMail?.deleteAllLocalData?window.daybreakMail:null;
let notificationPrivacy={showDetails:false};
let appLockSettings={enabled:false,deviceSecure:false};
let appLockSettings={enabled:false,deviceSecure:false,lockDelaySeconds:0};
if(notificationBridge){try{notificationPrivacy=await notificationBridge.getNotificationPrivacy()}catch(error){toastProductivityUi(error.message||'Could not load notification privacy settings');return}}
if(appLockBridge){try{appLockSettings=await appLockBridge.getAppLockSettings()}catch(error){toastProductivityUi(error.message||'Could not load app-lock settings');return}}
const notificationSetting=notificationBridge?`<label class="compose-line"><span>Show sender and subject in notifications</span><input id="show-notification-details" type="checkbox"${notificationPrivacy.showDetails?' checked':''}></label><p class="account-note">Off by default. Android still hides private details from lock-screen previews.</p>`:'';
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><p class="account-note">Requires a secure Android screen lock. Mail sync continues in the background; unlock with your device PIN, pattern, or password when you return.</p>`:'';
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
const appLockSetting=appLockBridge?`<label class="compose-line"><span>Lock when leaving ep-mail</span><input id="app-lock-enabled" type="checkbox"${appLockSettings.enabled?' checked':''}></label><label class="compose-line"><span>Lock delay</span><select class="settings-select" id="app-lock-delay"><option value="0"${appLockSettings.lockDelaySeconds===0?' selected':''}>Immediately</option><option value="30"${appLockSettings.lockDelaySeconds===30?' selected':''}>30 seconds</option><option value="60"${appLockSettings.lockDelaySeconds===60?' selected':''}>1 minute</option><option value="300"${appLockSettings.lockDelaySeconds===300?' selected':''}>5 minutes</option></select></label><p class="account-note">Requires a secure Android screen lock. Screenshots are hidden as soon as you leave; mail sync continues in the background.</p>`:'';
const localDataSetting=localDataBridge?`<h3 class="pgp-heading">Local data</h3><p class="account-note">Delete saved accounts, cached mail, drafts, queued sends, OpenPGP keys, app settings, and attachments saved by ep-mail to Downloads.</p><button class="discard" id="delete-all-local-data">Delete all local data…</button>`:'';
root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>Settings</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Theme</span><select class="settings-select" id="theme-select">${options}</select></label><p class="account-note">Your selected theme is saved and applied whenever ep-mail starts.</p>${notificationSetting}${appLockSetting}${localDataSetting}</div><div class="compose-footer"><button class="discard modal-close">Cancel</button><button class="send-button" id="save-appearance">Save settings</button></div></div></div>`;
const close=()=>root.innerHTML='';
selectAllProductivityUi('.modal-close').forEach(button=>button.onclick=close);
selectProductivityUi('.modal-overlay').onclick=event=>{if(event.target.classList.contains('modal-overlay'))close()};
selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge)await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked);productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}};
selectProductivityUi('#save-appearance').onclick=async()=>{const button=selectProductivityUi('#save-appearance');button.disabled=true;try{if(notificationBridge)await notificationBridge.setNotificationDetails(selectProductivityUi('#show-notification-details').checked);if(appLockBridge){await appLockBridge.setAppLockDelay(Number(selectProductivityUi('#app-lock-delay').value));await appLockBridge.setAppLockEnabled(selectProductivityUi('#app-lock-enabled').checked)}productivityMailUi.applyTheme(selectProductivityUi('#theme-select').value);close();toastProductivityUi('Settings saved')}catch(error){button.disabled=false;toastProductivityUi(error.message||'Could not save settings')}};
if(localDataBridge)selectProductivityUi('#delete-all-local-data').onclick=async event=>{const button=event.currentTarget;button.disabled=true;try{const result=await localDataBridge.deleteAllLocalData();if(!result?.deleted){button.disabled=false;return}if('serviceWorker'in navigator){const registrations=await navigator.serviceWorker.getRegistrations();await Promise.all(registrations.map(registration=>registration.unregister()))}if('caches'in window){const names=await caches.keys();await Promise.all(names.map(name=>caches.delete(name)))}localStorage.clear();window.location.reload()}catch(error){button.disabled=false;toastProductivityUi(error.message||'Native data was deleted, but browser data cleanup did not finish. Restart ep-mail to complete cleanup.')}};
selectProductivityUi('#theme-select').focus();
}
function showEvent(dayOrId) { const edit=savedEvents.find(e=>e.id===dayOrId), dateValue=edit?.date || (typeof dayOrId==='string'&&/^\d{4}-\d\d-\d\d$/.test(dayOrId)?dayOrId:`${calendarMonth.getFullYear()}-${String(calendarMonth.getMonth()+1).padStart(2,'0')}-${String(dayOrId||new Date().getDate()).padStart(2,'0')}`); const root=selectProductivityUi('#modal-root'); root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${edit?'Edit event':'Add calendar event'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>Event</span><input id="event-name" maxlength="120" value="${escapeProductivityUi(edit?.title||'')}" placeholder="Give it a name"></label><label class="compose-line"><span>Date</span><input id="event-date" type="date" value="${dateValue}"></label><label class="compose-line"><span>Time</span><input id="event-time" type="time" value="${escapeProductivityUi(edit?.time||'10:00')}"></label><label class="compose-line"><span>With</span><input id="event-people" value="${escapeProductivityUi(edit?.with||'')}" placeholder="Add people"></label><label class="compose-line"><span>Place</span><input id="event-place" value="${escapeProductivityUi(edit?.place||'')}" placeholder="Add a place"></label><label class="compose-line"><span>Notes</span><input id="event-notes" value="${escapeProductivityUi(edit?.notes||'')}" placeholder="Optional notes"></label></div><div class="compose-footer">${edit?'<button class="discard" id="delete-event">Delete event</button>':'<button class="discard modal-close">Cancel</button>'}<button class="send-button" id="save-event">${edit?'Save changes':'Save event'}</button></div></div></div>`; const close=()=>root.innerHTML=''; selectAllProductivityUi('.modal-close').forEach(b=>b.onclick=close); selectProductivityUi('.modal-overlay').onclick=e=>{if(e.target.classList.contains('modal-overlay'))close()}; selectProductivityUi('#save-event').onclick=async()=>{const title=selectProductivityUi('#event-name').value.trim(),date=selectProductivityUi('#event-date').value;if(!title||!date){toastProductivityUi('Add an event name and date');return}const item={...(edit||{}),id:edit?.id||crypto.randomUUID(),title,date,time:selectProductivityUi('#event-time').value,with:selectProductivityUi('#event-people').value.trim(),place:selectProductivityUi('#event-place').value.trim(),notes:selectProductivityUi('#event-notes').value.trim()}; if(window.daybreakMail?.davSaveEvent){try{const remote=await window.daybreakMail.davSaveEvent(item);if(remote)item._dav=remote}catch(error){toastProductivityUi('Saved locally; DAV sync failed: '+error.message)}} if(edit) savedEvents=savedEvents.map(e=>e.id===edit.id?item:e);else savedEvents.push(item);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi(edit?'Event updated':'Event added')}; if(edit) selectProductivityUi('#delete-event').onclick=async()=>{if(edit._dav&&window.daybreakMail?.davDeleteEvent){try{await window.daybreakMail.davDeleteEvent(edit._dav)}catch(error){toastProductivityUi('Could not delete remote event: '+error.message);return}}savedEvents=savedEvents.filter(e=>e.id!==edit.id);productWrite(productKeys.events,savedEvents);close();renderCalendar();toastProductivityUi('Event removed')}; selectProductivityUi('#event-name').focus(); }
+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'];
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())));