Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5059dde07b | ||
|
|
717a2760fa |
-116
@@ -1,116 +0,0 @@
|
||||
# Architecture
|
||||
|
||||
This project has a layered architecture: a desktop Electron shell, a browser-rendered mail interface, platform-specific storage and sync adapters, and a separate Android Capacitor wrapper. The design keeps user state and credentials in the OS keyring, pushes IMAP/SMTP work into the main process, and exposes only a narrow IPC surface to the renderer.
|
||||
|
||||
## 1. Runtime layout
|
||||
|
||||
### Desktop shell
|
||||
|
||||
- `desktop/main.cjs` is the privileged process.
|
||||
- It owns account storage, mail sync, IMAP/SMTP connectivity, DAV sync, and OpenPGP key handling.
|
||||
- It can show native dialogs, notifications, and system prompts.
|
||||
- `desktop/preload.cjs` exposes a minimal API to the renderer through `window.daybreakMail` and `window.pgpPrepareSend`.
|
||||
|
||||
### Renderer UI
|
||||
|
||||
The browser UI is rendered from the web assets in the root and `www/` folders:
|
||||
|
||||
- `index.html` and the shared shell files define the layout and global state.
|
||||
- `app.js`, `mail-ui.js`, `account-ui.js`, `dav-ui.js`, `pgp-ui.js`, and `pgp-mail-ui.js` handle page flow, compose/read views, account setup, and encryption UX.
|
||||
- The renderer is intentionally thin: it requests actions and displays data, but the actual cryptographic and network work stays in the main process.
|
||||
|
||||
### Android client
|
||||
|
||||
The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.config.json`).
|
||||
|
||||
- The same browser UI runs inside the Android app.
|
||||
- Native Android services handle background sync, notification behavior, and secure storage.
|
||||
- The desktop and Android implementations intentionally share the same mail and account model so the feature surface stays aligned.
|
||||
|
||||
## 2. Core responsibilities
|
||||
|
||||
### Mail and account state
|
||||
|
||||
The main process owns the canonical account model and persists it in an encrypted store:
|
||||
|
||||
- `mail-account.enc` stores connected IMAP/SMTP accounts and their settings.
|
||||
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
|
||||
- `pgp-keys.enc` stores OpenPGP keys and trust data.
|
||||
|
||||
All three stores are wrapped with Electron `safeStorage` where available. Linux checks explicitly reject the insecure `basic_text` backend before credentials or keys are persisted.
|
||||
|
||||
### Mail sync pipeline
|
||||
|
||||
The desktop app follows a background sync model:
|
||||
|
||||
1. The renderer asks the main process for a folder sync or inbox refresh.
|
||||
2. The main process opens an IMAP connection and fetches only the requested subset or page.
|
||||
3. Sync results are written back into the account state and sent to the renderer via IPC (`mail:sync-update`).
|
||||
4. Periodic background sync and IDLE watchers reduce polling and keep new-mail notifications timely.
|
||||
|
||||
A generation counter invalidates stale sync jobs when accounts are edited or removed, and concurrent syncs are prevented to avoid overlapping IMAP traffic.
|
||||
|
||||
### Message send path
|
||||
|
||||
The send flow is also centralized in the main process:
|
||||
|
||||
- the renderer calls `mail:send`
|
||||
- the main process resolves the account, checks the sender settings, and applies OpenPGP encryption/signing before sending
|
||||
- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable
|
||||
|
||||
This prevents the renderer from silently bypassing critical security checks or storing plaintext in outbox data.
|
||||
|
||||
## 3. Security boundary
|
||||
|
||||
The current architecture takes a strict trust split:
|
||||
|
||||
- renderer: UI, user interaction, local conveniences
|
||||
- main process: network access, cryptographic operations, permission prompts, OS secure storage
|
||||
|
||||
This boundary is important for encryption and safety checks:
|
||||
|
||||
- OpenPGP key selection and trust updates are confirmed in the main process.
|
||||
- Key-server lookup results never elevate trust; only the public key is sent during a separately confirmed publication.
|
||||
- Send-time downgrade checks happen in the main process rather than only in UI logic.
|
||||
- External links open only after a native confirmation dialog.
|
||||
- Credentials and private keys are stored with the OS keyring, not in plain JSON files.
|
||||
|
||||
## 4. OpenPGP subsystem
|
||||
|
||||
The OpenPGP implementation is split into focused modules:
|
||||
|
||||
- `desktop/pgp-keystore.cjs` stores contacts, trust, key material, and settings.
|
||||
- `desktop/pgp-mail.cjs` handles message detection, decryption, verification, encryption, and signature checks.
|
||||
- `desktop/pgp-keyservers.cjs` implements bounded HTTPS lookup and publication for VKS and HKP-compatible servers.
|
||||
- `desktop/main.cjs` bridges those services into the Electron IPC API.
|
||||
|
||||
This keeps the cryptographic logic separate from the UI and gives the app a single place to enforce trust rules, passphrase checks, and recipient validation.
|
||||
|
||||
Key-server enablement is persisted in encrypted OpenPGP settings; all servers default to disabled, including custom servers already configured by older versions. The main process enforces enabled status for both lookup and publication. A lookup queries all enabled servers, reports partial failures, and merges duplicate fingerprints while retaining source names. The user chooses one enabled server as the publication target. Custom HTTPS endpoints require a native confirmation when added; redirects and oversized responses are rejected. Returned keys are validated and remain untrusted until the user verifies their fingerprints out of band. Publishing sends only public key material and requires a native confirmation naming the destination for each publication.
|
||||
|
||||
## 5. Data flow patterns
|
||||
|
||||
- Account setup and edits flow from the UI into IPC, then into the encrypted main-process storage.
|
||||
- Mail content is fetched by the main process and served to the renderer in a sanitized, parsed form.
|
||||
- Attachments, decrypted bodies, and external links are all checked before user-visible actions are allowed.
|
||||
- Search, folder listing, and draft operations reuse the same account model across both desktop and Android versions.
|
||||
|
||||
## 6. Release and packaging model
|
||||
|
||||
The project packages multiple platforms from the same codebase:
|
||||
|
||||
- `npm run dist:win` for Windows installer/portable builds
|
||||
- `npm run dist:linux` for Linux AppImage and Debian builds
|
||||
- Android builds via Capacitor (`npm run android:apk`)
|
||||
|
||||
The app version is managed through package metadata and the Electron build config in `package.json`.
|
||||
|
||||
## 7. Key architectural principles
|
||||
|
||||
- Keep privileged operations in the main process.
|
||||
- Keep security rules in trusted code rather than the UI.
|
||||
- Store secrets in OS-backed secure storage whenever the platform supports it.
|
||||
- Share the same account and sync model between desktop and Android where possible.
|
||||
- Treat mail encryption and secure key handling as first-class product features, not optional extras.
|
||||
|
||||
This architecture is intentionally built for a mail client that must handle privacy-sensitive data, background sync, and cross-platform parity without exposing the network or crypto stack to the renderer.
|
||||
+3
-17
@@ -15,7 +15,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
|
||||
- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used.
|
||||
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
|
||||
- Out of scope for v1: Autocrypt headers and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
|
||||
- Out of scope for v1: Autocrypt headers, key servers, Web Key Directory.
|
||||
|
||||
## 2. Key handling
|
||||
|
||||
@@ -25,11 +25,11 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4).
|
||||
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk.
|
||||
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
|
||||
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
|
||||
- Deleting or exporting a private key requires the passphrase.
|
||||
|
||||
**Public keys**
|
||||
- Per-account contact keyring: address, fingerprint, trust level, source.
|
||||
- Sources: file import, attached to received mail, key-server lookup, and own key attached to outgoing mail.
|
||||
- Sources: file import, attached to received mail, own key attached to outgoing mail.
|
||||
- Trust: trust on first use, shown with the fingerprint, plus an explicit "verified" state after out-of-band comparison. Warn loudly when a known contact's key changes.
|
||||
|
||||
## 3. User experience
|
||||
@@ -83,17 +83,3 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
- User confusion about trust; keep states simple: unknown, trusted, verified.
|
||||
- Decrypted HTML must not leak through remote content; blocking remote images by default should land first.
|
||||
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
|
||||
|
||||
## 9. Public key servers (desktop)
|
||||
|
||||
The desktop Settings → Encryption keys view can search and publish through:
|
||||
|
||||
- **keys.openpgp.org** using its [VKS API](https://keys.openpgp.org/about/api/). Email lookup only returns keys whose email addresses have been verified. After an upload, ep-mail requests verification for the key's primary email address and reports whether verification is pending or already complete.
|
||||
- **keys.mailvelope.com** using HKP over HTTPS as documented by the [Mailvelope key server](https://github.com/mailvelope/keyserver#hkp-api). The server sends its own email-verification message after accepting a key upload.
|
||||
- **Custom servers** using an explicitly selected HKP or VKS protocol and an HTTPS base URL. Custom server configuration is saved with the encrypted OpenPGP settings.
|
||||
|
||||
All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification.
|
||||
|
||||
Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is not included because Android OpenPGP support is not implemented.
|
||||
|
||||
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
|
||||
|
||||
@@ -8,8 +8,6 @@ The Electron app runs in its own window. With Node.js installed, run `npm instal
|
||||
|
||||
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
||||
|
||||
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
|
||||
|
||||
## Android app
|
||||
|
||||
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
||||
@@ -33,4 +31,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
|
||||
|
||||
## Current scope
|
||||
|
||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`.
|
||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys, stored encrypted by the operating system; you can import contacts' public keys, read encrypted or signed OpenPGP mail, and encrypt or sign outgoing messages from the compose window (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md); Android is not supported yet). Run the tests with `npm test`.
|
||||
|
||||
@@ -41,18 +41,3 @@ No critical or high severity issues were reported.
|
||||
- Run `npm audit` and pin the OpenPGP.js version.
|
||||
- Re-run the GnuPG interoperability tests after dependency updates.
|
||||
- Android has no encryption support yet, so it was not reviewed.
|
||||
|
||||
## Second review pass (2026-10-09)
|
||||
|
||||
Fresh review of the same scope after the first round of fixes. Tests: 20 passed, 0 failed. No code was changed in this pass.
|
||||
|
||||
| # | Severity | File | Issue | Confidence | Status |
|
||||
|---|----------|------|-------|------------|--------|
|
||||
| 3 | 🟡 MEDIUM | `desktop/pgp-keystore.cjs`, `desktop/main.cjs` | `pgp:add-contact` adds a key for an address that already has one without a main-process confirmation. At equal trust the newest key wins recipient selection, so an added key can take over outgoing encryption. The trust dialog does not cover replacement. | 9/10 | Fixed |
|
||||
| 4 | 🟡 MEDIUM | `desktop/main.cjs`, `desktop/preload.cjs` | The send-time downgrade check exists only in the renderer. `mail:send` sends plaintext when `pgp` is omitted, so a compromised renderer can bypass the warning. | 9/10 | Fixed |
|
||||
| 5 | 🟡 MEDIUM | `desktop/main.cjs` | `safeStorage` is used without checking the backend. On Linux the `basic_text` backend uses a hardcoded password, so a copied store would expose account credentials and mail data. PGP private keys stay protected by their own passphrases. | 8/10 | Fixed |
|
||||
|
||||
Applied fixes:
|
||||
- #3: native confirmation showing both fingerprints when a key overlaps existing contacts, and the add-contact flow aborts if the replacement is not confirmed.
|
||||
- #4: the main process checks recipient keys before allowing a plaintext send and shows a trusted confirmation dialog.
|
||||
- #5: Linux now rejects the insecure `basic_text` safeStorage backend and asks the user to switch to a secure system keyring before storing mail or PGP secrets.
|
||||
@@ -2,72 +2,25 @@
|
||||
|
||||
## Product identity
|
||||
|
||||
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation.
|
||||
- [x] Replace the temporary sun/asterisk app mark with the Git and webmail logo, using the EP Daylight and EP Wasteland color variants.
|
||||
- [x] Add Android support for the mail app.
|
||||
- [ ] Add macOS support: configure macOS release targets and build the app on a Mac or hosted macOS runner; sign and notarize releases for distribution.
|
||||
- [x] Show the app version after **ep-mail** in the window title.
|
||||
|
||||
## Mail workflow
|
||||
|
||||
- [x] Snooze messages until a chosen time and show a follow-up reminder when they return.
|
||||
- [ ] Add Undo Send and scheduled sending.
|
||||
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
|
||||
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
|
||||
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
|
||||
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
||||
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
|
||||
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
|
||||
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
|
||||
- [x] Add per-account signatures, notification preferences, and sync settings.
|
||||
- [x] Add the ability to create IMAP folders from the app.
|
||||
- [ ] Block remote images by default and let users load them per message.
|
||||
|
||||
## Mail security
|
||||
|
||||
- [ ] Add support for encrypting and decrypting mail with OpenPGP (PGP/MIME). See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md).
|
||||
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
|
||||
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
|
||||
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
|
||||
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
|
||||
- [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
|
||||
- [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.
|
||||
- [x] Manual interoperability check with Thunderbird.
|
||||
- [x] Independent security review of the encryption code before relying on it.
|
||||
|
||||
## Appearance and settings
|
||||
|
||||
- [ ] Fix the startup color-scheme flash so the selected dark theme is applied before the app window appears.
|
||||
- [x] Make **EP Wasteland** the default theme for new users.
|
||||
- [x] Move theme selection into Settings and save the selection so the chosen theme is applied every time the program starts.
|
||||
- [x] Keep the display name in Account Settings and make it available while adding a mailbox.
|
||||
|
||||
## Account settings
|
||||
|
||||
- [ ] Fix the mailbox space indicator; it is not working.
|
||||
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
||||
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
|
||||
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
|
||||
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
|
||||
- [ ] Add push mail support.
|
||||
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
|
||||
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
|
||||
- [x] Add new mail notifications.
|
||||
- [x] Add an **Edit** button for each connected mail account so its account settings can be changed after setup.
|
||||
- [x] Move CalDAV and CardDAV server configuration into Account Settings, removing the server settings controls from the Calendar and Contacts views.
|
||||
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
|
||||
- [x] Display name must be set per account.
|
||||
- [x] Remove the display name initials from the bottom-left corner.
|
||||
- [x] Add the ability to delete draft mails.
|
||||
- [x] Fix IMAP folder creation, which does not work.
|
||||
- [ ] Give the sidebar (Inbox, Folders, etc.) more room so every item fits on screen: make the box scrollable with a slider, or remove or collapse less-used items.
|
||||
- [ ] Make labels work and add the ability to create more labels.
|
||||
- [x] Fix created IMAP folders not showing in the mail rules folder list; only Inbox, Archive and Trash are shown.
|
||||
- [x] Fix draft mail deletion to work like the Inbox: select multiple drafts and delete the selected drafts at once.
|
||||
- [x] Show created IMAP folders in the same list as Inbox and the other folders, and move the folder list and the add-folder button to the top row above Inbox. Add scrolling to the IMAP folders area.
|
||||
- [x] Add desktop public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKP over HTTPS), and user-defined HTTPS HKP/VKS servers. Servers are disabled until selected; lookup checks all enabled servers, and publishing requires one explicitly selected destination. Discovered keys remain unverified until fingerprint verification.
|
||||
- [ ] Add the ability to attach files to outgoing mails.
|
||||
- [x] Fix security review findings: confirm key replacement in the main process, enforce the plaintext-send check in the main process, and handle the Linux safeStorage basic_text backend. See SECURITY_REVIEW.md.
|
||||
- [x] Add the ability to change the passphrase of an encryption key on desktop.
|
||||
- [ ] Add public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKPS), and user-defined custom key servers.
|
||||
|
||||
+16
-64
@@ -1,78 +1,30 @@
|
||||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'org.jetbrains.kotlin.android'
|
||||
|
||||
def appVersion = new groovy.json.JsonSlurper().parse(file("../../package.json")).version
|
||||
def appVersionParts = appVersion.tokenize('.').collect { it.toInteger() }
|
||||
apply plugin: "com.android.application"
|
||||
apply plugin: "kotlin-android"
|
||||
apply plugin: "com.google.gms.google-services" // Add this line
|
||||
|
||||
android {
|
||||
namespace = "studio.daybreak.mail"
|
||||
compileSdk = rootProject.ext.compileSdkVersion
|
||||
buildFeatures {
|
||||
buildConfig true
|
||||
}
|
||||
packaging {
|
||||
resources {
|
||||
pickFirsts += "META-INF/NOTICE.md"
|
||||
pickFirsts += "META-INF/LICENSE.md"
|
||||
}
|
||||
}
|
||||
compileSdkVersion 30
|
||||
defaultConfig {
|
||||
applicationId "studio.daybreak.mail"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode appVersionParts[0] * 10000 + appVersionParts[1] * 100 + appVersionParts[2]
|
||||
versionName appVersion
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
|
||||
ignoreAssetsPattern = '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
|
||||
}
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 30
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
}
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
|
||||
}
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility JavaVersion.VERSION_21
|
||||
targetCompatibility JavaVersion.VERSION_21
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = '21'
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
flatDir{
|
||||
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation fileTree(include: ['*.jar'], dir: 'libs')
|
||||
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
|
||||
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
|
||||
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
|
||||
implementation project(':capacitor-android')
|
||||
implementation 'com.sun.mail:android-mail:1.6.7'
|
||||
implementation 'com.sun.mail:android-activation:1.6.7'
|
||||
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
|
||||
implementation 'androidx.work:work-runtime-ktx:2.10.1'
|
||||
testImplementation "junit:junit:$junitVersion"
|
||||
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
|
||||
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
|
||||
implementation project(':capacitor-cordova-android-plugins')
|
||||
}
|
||||
|
||||
apply from: 'capacitor.build.gradle'
|
||||
|
||||
try {
|
||||
def servicesJSON = file('google-services.json')
|
||||
if (servicesJSON.text) {
|
||||
apply plugin: 'com.google.gms.google-services'
|
||||
}
|
||||
} catch(Exception e) {
|
||||
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
|
||||
implementation fileTree(dir: "libs", include: ["*.jar"])
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
|
||||
implementation 'androidx.core:core-ktx:1.6.0'
|
||||
implementation 'androidx.appcompat:appcompat:1.3.1'
|
||||
implementation 'com.google.android.material:material:1.4.0'
|
||||
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
|
||||
implementation 'com.google.firebase:firebase-messaging:23.0.0' // Add this line
|
||||
}
|
||||
|
||||
@@ -1,48 +1,29 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="studio.daybreak.mail">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:allowBackup="true"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/AppTheme">
|
||||
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation|density"
|
||||
android:name=".MainActivity"
|
||||
android:label="@string/title_activity_main"
|
||||
android:theme="@style/AppTheme.NoActionBarLaunch"
|
||||
android:launchMode="singleTask"
|
||||
android:exported="true">
|
||||
|
||||
<activity android:name=".MainActivity">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".MailIdleService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths"></meta-data>
|
||||
</provider>
|
||||
android:name=".MyFirebaseMessagingService"
|
||||
android:exported="false">
|
||||
<intent-filter>
|
||||
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
|
||||
</intent-filter>
|
||||
</service>
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
|
||||
@@ -1,39 +1,8 @@
|
||||
package studio.daybreak.mail
|
||||
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import android.text.Html
|
||||
import android.webkit.MimeTypeMap
|
||||
import com.sun.mail.imap.IMAPFolder
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.text.DateFormat
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.Properties
|
||||
import java.util.UUID
|
||||
import javax.mail.Address
|
||||
import javax.mail.Authenticator
|
||||
import javax.mail.Flags
|
||||
import javax.mail.Folder
|
||||
import javax.mail.Message
|
||||
import javax.mail.Multipart
|
||||
import javax.mail.PasswordAuthentication
|
||||
import javax.mail.Session
|
||||
import javax.mail.Store
|
||||
import javax.mail.Transport
|
||||
import javax.mail.UIDFolder
|
||||
import javax.mail.internet.InternetAddress
|
||||
import javax.mail.internet.MimeBodyPart
|
||||
import javax.mail.internet.MimeMessage
|
||||
import javax.mail.internet.MimeMultipart
|
||||
import javax.mail.internet.MimeUtility
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal object AndroidMailService {
|
||||
data class SyncResult(val payload: JSONObject, val newCount: Int)
|
||||
@@ -45,108 +14,8 @@ internal object AndroidMailService {
|
||||
val count = inbox.messageCount
|
||||
inbox.close(false)
|
||||
val smtpSession = Session.getInstance(smtpProperties(account), credentials(account))
|
||||
val transport = smtpSession.getTransport("smtp")
|
||||
try {
|
||||
transport.connect(
|
||||
account.optString("smtpHost"),
|
||||
account.optInt("smtpPort", 587),
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
} finally {
|
||||
if (transport.isConnected) transport.close()
|
||||
}
|
||||
JSONObject().put("mailbox", "INBOX").put("messages", count)
|
||||
}
|
||||
|
||||
fun sync(account: JSONObject, requestedFolder: String, offset: Int, filters: JSONObject = JSONObject()): JSONObject {
|
||||
if (requestedFolder == "Snoozed") return syncSnoozed(account, offset)
|
||||
return try {
|
||||
withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, requestedFolder)
|
||||
if (folder == null) return@withStore JSONObject()
|
||||
.put("messages", JSONArray()).put("total", 0).put("folder", requestedFolder)
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val total = folder.messageCount
|
||||
val hasSearchFilters = listOf("query", "sender", "subject", "after", "before")
|
||||
.any { filters.optString(it).isNotBlank() } || filters.optBoolean("hasAttachments")
|
||||
if (hasSearchFilters) {
|
||||
val all = JSONArray()
|
||||
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||
if (total > 0) {
|
||||
val start = (total - 4999).coerceAtLeast(1)
|
||||
for (message in folder.getMessages(start, total)) {
|
||||
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
|
||||
if (snoozed.length() > 0 && (0 until snoozed.length()).any { index ->
|
||||
val item = snoozed.optJSONObject(index) ?: return@any false
|
||||
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
|
||||
item.optLong("dueAt") > System.currentTimeMillis()
|
||||
}) continue
|
||||
all.put(messageJson(folder, message, requestedFolder, account))
|
||||
}
|
||||
}
|
||||
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, all)
|
||||
val matches = (0 until all.length()).mapNotNull { all.optJSONObject(it) }
|
||||
.filter { matchesFilters(it, filters) }
|
||||
.sortedByDescending { it.optLong("timestamp") }
|
||||
val start = offset.coerceAtLeast(0)
|
||||
val page = matches.drop(start).take(20)
|
||||
return@withStore JSONObject()
|
||||
.put("messages", JSONArray().apply { page.forEach(::put) })
|
||||
.put("total", matches.size)
|
||||
.put("start", if (matches.isEmpty()) 0 else start + 1)
|
||||
.put("end", start + page.size)
|
||||
.put("folder", requestedFolder)
|
||||
}
|
||||
val end = (total - offset.coerceAtLeast(0)).coerceAtLeast(0)
|
||||
if (end == 0) {
|
||||
return@withStore JSONObject().put("messages", JSONArray()).put("total", total)
|
||||
.put("start", 0).put("end", 0).put("folder", requestedFolder)
|
||||
}
|
||||
val first = (end - 19).coerceAtLeast(1)
|
||||
val result = JSONArray()
|
||||
val batch = folder.getMessages(first, end).reversed()
|
||||
val snoozed = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||
val cached = JSONArray()
|
||||
for (message in batch) {
|
||||
val uid = (folder as? UIDFolder)?.getUID(message) ?: 0L
|
||||
val isSnoozed = (0 until snoozed.length()).any { index ->
|
||||
val item = snoozed.getJSONObject(index)
|
||||
item.optString("folder") == requestedFolder && item.optLong("uid") == uid &&
|
||||
item.optLong("dueAt") > System.currentTimeMillis()
|
||||
}
|
||||
if (isSnoozed) continue
|
||||
val value = messageJson(folder, message, requestedFolder, account)
|
||||
result.put(value)
|
||||
cached.put(value)
|
||||
}
|
||||
AndroidAccountVault.cacheMessages(account.optString("id"), requestedFolder, cached)
|
||||
JSONObject().put("messages", result).put("total", total)
|
||||
.put("start", first).put("end", end).put("folder", requestedFolder)
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
if (!isConnectivityFailure(error)) throw error
|
||||
AndroidAccountVault.cachedFolder(account.optString("id"), requestedFolder, offset, filters)
|
||||
?: throw error
|
||||
}
|
||||
}
|
||||
|
||||
private fun isConnectivityFailure(error: Throwable): Boolean {
|
||||
var current: Throwable? = error
|
||||
while (current != null) {
|
||||
if (current is java.net.UnknownHostException ||
|
||||
current is java.net.ConnectException ||
|
||||
current is java.net.SocketTimeoutException ||
|
||||
current is javax.net.ssl.SSLException) return true
|
||||
val message = current.message.orEmpty().lowercase(Locale.ROOT)
|
||||
if (listOf("network is unreachable", "connection timed out", "connection refused", "unable to resolve host", "socket closed").any(message::contains)) return true
|
||||
current = current.cause
|
||||
}
|
||||
return false
|
||||
// Handle push notifications here.
|
||||
JSONObject()
|
||||
}
|
||||
|
||||
private fun matchesFilters(message: JSONObject, filters: JSONObject): Boolean {
|
||||
@@ -155,21 +24,20 @@ internal object AndroidMailService {
|
||||
val subjectFilter = filters.optString("subject").trim().lowercase(Locale.ROOT)
|
||||
val sender = "${message.optString("sender")} ${message.optString("email")}".lowercase(Locale.ROOT)
|
||||
val subject = message.optString("subject").lowercase(Locale.ROOT)
|
||||
val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")?.toString().orEmpty()}".lowercase(Locale.ROOT)
|
||||
val haystack = "$sender $subject ${message.optString("snippet")} ${message.optJSONArray("body")}".lowercase(Locale.ROOT)
|
||||
val timestamp = message.optLong("timestamp")
|
||||
val after = dateBoundary(filters.optString("after"), false)
|
||||
val before = dateBoundary(filters.optString("before"), true)
|
||||
val attachments = message.optJSONArray("attachments")
|
||||
return (query.isBlank() || query.split(Regex("\\s+")).all(haystack::contains)) &&
|
||||
(senderFilter.isBlank() || sender.contains(senderFilter)) &&
|
||||
(subjectFilter.isBlank() || subject.contains(subjectFilter)) &&
|
||||
(after == null || timestamp >= after) && (before == null || timestamp <= before) &&
|
||||
(!filters.optBoolean("hasAttachments") || (attachments?.length() ?: 0) > 0)
|
||||
return haystack.contains(query) &&
|
||||
(senderFilter.isEmpty() || sender.contains(senderFilter)) &&
|
||||
(subjectFilter.isEmpty() || subject.contains(subjectFilter)) &&
|
||||
(after == null || timestamp >= after) &&
|
||||
(before == null || timestamp <= before)
|
||||
}
|
||||
|
||||
private fun dateBoundary(value: String, endOfDay: Boolean): Long? {
|
||||
if (value.isBlank()) return null
|
||||
val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrNull() ?: return null
|
||||
val parsed = runCatching { SimpleDateFormat("yyyy-MM-dd", Locale.ROOT).parse(value) }.getOrElse { return null }
|
||||
val calendar = Calendar.getInstance().apply { time = parsed }
|
||||
if (endOfDay) {
|
||||
calendar.add(Calendar.DAY_OF_MONTH, 1)
|
||||
@@ -178,36 +46,6 @@ internal object AndroidMailService {
|
||||
return calendar.timeInMillis
|
||||
}
|
||||
|
||||
private fun syncSnoozed(account: JSONObject, offset: Int): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val snoozes = account.optJSONArray("snoozedMessages") ?: JSONArray()
|
||||
val pending = (0 until snoozes.length())
|
||||
.map { snoozes.getJSONObject(it) }
|
||||
.filter { it.optLong("dueAt") > System.currentTimeMillis() }
|
||||
.sortedBy { it.optLong("dueAt") }
|
||||
val page = pending.drop(offset.coerceAtLeast(0)).take(20)
|
||||
val messages = JSONArray()
|
||||
for (snooze in page) {
|
||||
val sourceFolder = snooze.optString("folder", "Inbox")
|
||||
val folder = resolveFolder(store, sourceFolder) ?: continue
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val message = (folder as? UIDFolder)?.getMessageByUID(snooze.optLong("uid")) ?: continue
|
||||
messages.put(messageJson(folder, message, "Snoozed", account, sourceFolder)
|
||||
.put("sourceFolder", sourceFolder)
|
||||
.put("snoozedUntil", snooze.optLong("dueAt")))
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
JSONObject()
|
||||
.put("messages", messages)
|
||||
.put("total", pending.size)
|
||||
.put("start", if (page.isEmpty()) 0 else offset + 1)
|
||||
.put("end", offset + messages.length())
|
||||
.put("folder", "Snoozed")
|
||||
}
|
||||
|
||||
fun updateMessage(account: JSONObject, input: JSONObject): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val uid = input.optLong("uid")
|
||||
@@ -218,165 +56,8 @@ internal object AndroidMailService {
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
var expungeDeleted = false
|
||||
source.open(Folder.READ_WRITE)
|
||||
try {
|
||||
val message = (source as? UIDFolder)?.getMessageByUID(uid)
|
||||
?: throw IllegalStateException("The message is no longer available.")
|
||||
when (action) {
|
||||
"star" -> message.setFlag(Flags.Flag.FLAGGED, input.optBoolean("enabled"))
|
||||
"unread" -> message.setFlag(Flags.Flag.SEEN, !input.optBoolean("enabled"))
|
||||
"archive", "delete", "inbox" -> {
|
||||
val targetName = when (action) {
|
||||
"archive" -> "Archive"
|
||||
"delete" -> "Trash"
|
||||
else -> "Inbox"
|
||||
}
|
||||
val target = resolveFolder(store, targetName) ?: store.getFolder(targetName)
|
||||
if (!target.exists()) target.create(Folder.HOLDS_MESSAGES)
|
||||
if (source.fullName == target.fullName) {
|
||||
if (action == "delete") {
|
||||
expungeDeleted = true
|
||||
message.setFlag(Flags.Flag.DELETED, true)
|
||||
}
|
||||
} else {
|
||||
expungeDeleted = true
|
||||
source.copyMessages(arrayOf(message), target)
|
||||
message.setFlag(Flags.Flag.DELETED, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
source.close(expungeDeleted)
|
||||
}
|
||||
if (action == "archive" || action == "delete" || action == "inbox") {
|
||||
AndroidAccountVault.setSnooze(
|
||||
account.optString("id"),
|
||||
uid,
|
||||
input.optString("folder", "Inbox"),
|
||||
null,
|
||||
""
|
||||
)
|
||||
}
|
||||
JSONObject().put("ok", true)
|
||||
}
|
||||
|
||||
fun send(account: JSONObject, input: JSONObject): JSONObject {
|
||||
val recipient = input.optString("to").trim()
|
||||
require(recipient.isNotEmpty()) { "Add at least one recipient." }
|
||||
val properties = smtpProperties(account)
|
||||
val session = Session.getInstance(properties, credentials(account))
|
||||
val message = MimeMessage(session)
|
||||
message.setFrom(InternetAddress(account.optString("email"), displayName(account), "UTF-8"))
|
||||
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, true))
|
||||
val cc = input.optString("cc").trim()
|
||||
if (cc.isNotEmpty()) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, true))
|
||||
message.subject = input.optString("subject", "(no subject)")
|
||||
val body = input.optString("text")
|
||||
val signature = account.optString("signature").take(5000)
|
||||
message.setText(
|
||||
if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature",
|
||||
"UTF-8"
|
||||
)
|
||||
message.sentDate = Date()
|
||||
message.saveChanges()
|
||||
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
|
||||
|
||||
val transport = session.getTransport("smtp")
|
||||
try {
|
||||
transport.connect(
|
||||
account.optString("smtpHost"),
|
||||
account.optInt("smtpPort", 587),
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
transport.sendMessage(message, message.allRecipients)
|
||||
} finally {
|
||||
if (transport.isConnected) transport.close()
|
||||
}
|
||||
|
||||
var savedToSent = false
|
||||
try {
|
||||
withStore(account) { _, store ->
|
||||
val sent = resolveFolder(store, "Sent") ?: store.getFolder("Sent")
|
||||
if (!sent.exists()) sent.create(Folder.HOLDS_MESSAGES)
|
||||
sent.appendMessages(arrayOf(message))
|
||||
savedToSent = true
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
savedToSent = false
|
||||
}
|
||||
return JSONObject().put("ok", true).put("savedToSent", savedToSent)
|
||||
}
|
||||
|
||||
fun flushOutbox(account: JSONObject) {
|
||||
val accountId = account.optString("id")
|
||||
val queued = AndroidAccountVault.pendingMailOperations(accountId)
|
||||
for (index in 0 until queued.length()) {
|
||||
val operation = queued.optJSONObject(index) ?: continue
|
||||
try {
|
||||
val data = operation.optJSONObject("data") ?: continue
|
||||
when (operation.optString("type")) {
|
||||
"send" -> send(account, data)
|
||||
"action" -> updateMessage(account, data)
|
||||
else -> throw IllegalStateException("Unsupported queued mail operation.")
|
||||
}
|
||||
AndroidAccountVault.removeMailOperation(accountId, operation.optString("id"))
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.w("EpMailOutbox", "Mail operation remains queued for a later retry.", error)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun saveAttachment(context: Context, account: JSONObject, input: JSONObject): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val uid = input.optLong("uid")
|
||||
val message = (folder as? UIDFolder)?.getMessageByUID(uid)
|
||||
?: throw IllegalStateException("The message is no longer available.")
|
||||
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())
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun previewAttachment(account: JSONObject, input: JSONObject): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val message = (folder as? UIDFolder)?.getMessageByUID(input.optLong("uid"))
|
||||
?: throw IllegalStateException("The message is no longer available.")
|
||||
val filename = input.optString("filename")
|
||||
val part = findAttachment(message, filename)
|
||||
?: throw IllegalStateException("No attachment was found in this message.")
|
||||
val mimeType = part.contentType.substringBefore(';').trim().lowercase(Locale.ROOT)
|
||||
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() }
|
||||
if (bytes.size > 5 * 1048576) {
|
||||
none.put("reason", "This image is too large to preview. Download it instead.")
|
||||
} else {
|
||||
JSONObject().put("kind", "image").put(
|
||||
"dataUrl", "data:$mimeType;base64," + android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
|
||||
)
|
||||
}
|
||||
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
|
||||
val bytes = part.inputStream.use { it.readBytes() }
|
||||
JSONObject().put("kind", "text")
|
||||
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
|
||||
.put("truncated", bytes.size > 100000)
|
||||
} else none
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
// Handle push notifications here.
|
||||
JSONObject()
|
||||
}
|
||||
|
||||
fun checkForNewMail(account: JSONObject): Int {
|
||||
@@ -389,155 +70,14 @@ internal object AndroidMailService {
|
||||
?: throw IllegalStateException("The mail server does not support stable message IDs.")
|
||||
val validity = uidFolder.uidValidity
|
||||
val latestUid = (uidFolder.uidNext - 1).coerceAtLeast(0)
|
||||
val oldState = account.optJSONObject("androidInboxSyncState")
|
||||
val lastUid = if (oldState == null || oldState.optLong("uidValidity") != validity) {
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
|
||||
return@withStore 0
|
||||
} else oldState.optLong("lastUid")
|
||||
if (latestUid <= lastUid) return@withStore 0
|
||||
val added = uidFolder.getMessagesByUID(lastUid + 1, UIDFolder.LASTUID)
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), validity, latestUid)
|
||||
applyRules(account, added.mapNotNull { try { uidFolder.getUID(it) } catch (_: Exception) { null } })
|
||||
added.size
|
||||
// Handle push notifications here.
|
||||
0
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun applyRules(account: JSONObject, uids: List<Long>) {
|
||||
val rules = account.optJSONArray("rules") ?: return
|
||||
if (rules.length() == 0 || uids.isEmpty()) return
|
||||
withStore(account) { _, store ->
|
||||
val inbox = resolveFolder(store, "Inbox") ?: return@withStore
|
||||
for (uid in uids.distinct()) {
|
||||
try {
|
||||
inbox.open(Folder.READ_WRITE)
|
||||
try {
|
||||
val message = (inbox as? UIDFolder)?.getMessageByUID(uid) ?: continue
|
||||
val sender = message.from.orEmpty().joinToString(" ") { address ->
|
||||
if (address is InternetAddress) "${address.personal.orEmpty()} ${address.address}" else address.toString()
|
||||
}
|
||||
val subject = message.subject.orEmpty()
|
||||
val matched = (0 until rules.length()).asSequence()
|
||||
.map { rules.getJSONObject(it) }
|
||||
.firstOrNull { rule ->
|
||||
val senderCondition = rule.optString("senderContains")
|
||||
val subjectCondition = rule.optString("subjectContains")
|
||||
(senderCondition.isBlank() || sender.contains(senderCondition, ignoreCase = true)) &&
|
||||
(subjectCondition.isBlank() || subject.contains(subjectCondition, ignoreCase = true))
|
||||
} ?: continue
|
||||
when (matched.optString("action")) {
|
||||
"flag" -> message.setFlag(Flags.Flag.FLAGGED, true)
|
||||
"label" -> AndroidAccountVault.addRuleLabel(
|
||||
account.optString("id"), "Inbox", uid, matched.optString("value")
|
||||
)
|
||||
"archive", "move" -> {
|
||||
val destination = if (matched.optString("action") == "archive") {
|
||||
resolveFolder(store, "Archive") ?: store.getFolder("Archive").also {
|
||||
if (!it.exists()) it.create(Folder.HOLDS_MESSAGES)
|
||||
}
|
||||
} else resolveFolder(store, matched.optString("value"))
|
||||
?: throw IllegalStateException("Rule destination mailbox \"${matched.optString("value")}\" was not found.")
|
||||
if (destination.fullName != inbox.fullName) {
|
||||
inbox.copyMessages(arrayOf(message), destination)
|
||||
message.setFlag(Flags.Flag.DELETED, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
inbox.close(true)
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
android.util.Log.e("EpMailRules", "Could not apply a mail rule to message $uid", error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun watchInbox(
|
||||
account: JSONObject,
|
||||
onNewMail: (Int) -> Unit,
|
||||
shouldStop: () -> Boolean,
|
||||
onConnection: (Store?, Folder?) -> Unit
|
||||
) {
|
||||
val props = imapProperties(account).apply {
|
||||
setProperty("mail.imap.timeout", "0")
|
||||
setProperty("mail.imap.writetimeout", "60000")
|
||||
}
|
||||
val pollingIntervalMs = account.optInt("syncIntervalMinutes", 2)
|
||||
.coerceIn(2, 60) * 60_000L
|
||||
val session = Session.getInstance(props, credentials(account))
|
||||
val store = session.getStore("imap")
|
||||
try {
|
||||
store.connect(
|
||||
account.optString("imapHost"),
|
||||
account.optInt("imapPort", 143),
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
val inbox = store.getFolder("INBOX")
|
||||
inbox.open(Folder.READ_ONLY)
|
||||
var previousCount = inbox.messageCount
|
||||
val uidFolder = inbox as? UIDFolder
|
||||
val uidValidity = uidFolder?.uidValidity ?: 0L
|
||||
val initialUid = uidFolder?.let { (it.uidNext - 1).coerceAtLeast(0) } ?: 0L
|
||||
if (uidValidity > 0) {
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, initialUid)
|
||||
}
|
||||
onConnection(store, inbox)
|
||||
inbox.addMessageCountListener(object : javax.mail.event.MessageCountListener {
|
||||
override fun messagesAdded(event: javax.mail.event.MessageCountEvent) {
|
||||
if (event.type == javax.mail.event.MessageCountEvent.ADDED) {
|
||||
previousCount = maxOf(previousCount, inbox.messageCount)
|
||||
val newestUid = event.messages.maxOfOrNull { message ->
|
||||
try { uidFolder?.getUID(message) ?: 0L } catch (_: Exception) { 0L }
|
||||
} ?: 0L
|
||||
if (uidValidity > 0 && newestUid > 0) {
|
||||
AndroidAccountVault.updateInboxCursor(account.optString("id"), uidValidity, newestUid)
|
||||
}
|
||||
val addedUids = event.messages.mapNotNull { message ->
|
||||
try { uidFolder?.getUID(message) } catch (_: Exception) { null }
|
||||
}
|
||||
Thread({
|
||||
applyRules(account, addedUids)
|
||||
}, "ep-mail-rules-${account.optString("id")}").start()
|
||||
onNewMail(event.messages.size)
|
||||
}
|
||||
}
|
||||
override fun messagesRemoved(event: javax.mail.event.MessageCountEvent) = Unit
|
||||
})
|
||||
try {
|
||||
var supportsIdle = inbox is IMAPFolder
|
||||
while (!shouldStop()) {
|
||||
try {
|
||||
if (supportsIdle && inbox is IMAPFolder) {
|
||||
inbox.idle()
|
||||
} else {
|
||||
Thread.sleep(pollingIntervalMs)
|
||||
val currentCount = inbox.messageCount
|
||||
if (currentCount > previousCount) {
|
||||
val added = checkForNewMail(account)
|
||||
if (added > 0) onNewMail(added)
|
||||
}
|
||||
previousCount = currentCount
|
||||
}
|
||||
} catch (error: Exception) {
|
||||
if (shouldStop()) break
|
||||
if (error !is javax.mail.MethodNotSupportedException &&
|
||||
!error.javaClass.simpleName.contains("UnsupportedCommand")) throw error
|
||||
supportsIdle = false
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
onConnection(null, null)
|
||||
if (inbox.isOpen) inbox.close(false)
|
||||
}
|
||||
} finally {
|
||||
if (store.isConnected) store.close()
|
||||
}
|
||||
}
|
||||
|
||||
fun accountFingerprint(account: JSONObject): String = listOf(
|
||||
account.optString("email"),
|
||||
account.optString("imapHost"),
|
||||
@@ -546,179 +86,7 @@ internal object AndroidMailService {
|
||||
account.optInt("syncIntervalMinutes", 2),
|
||||
account.optString("signature"),
|
||||
account.optJSONArray("rules")?.toString().orEmpty()
|
||||
).joinToString("|").hashCode().toString()
|
||||
|
||||
private fun messageJson(
|
||||
folder: Folder,
|
||||
message: Message,
|
||||
requestedFolder: String,
|
||||
account: JSONObject? = null,
|
||||
labelFolder: String = requestedFolder
|
||||
): JSONObject {
|
||||
val uid = (folder as? UIDFolder)?.getUID(message) ?: message.messageNumber.toLong()
|
||||
val sender = (message.from?.firstOrNull() as? InternetAddress)
|
||||
val senderName = decode(sender?.personal).ifBlank { sender?.address ?: "Unknown sender" }
|
||||
val senderEmail = sender?.address ?: ""
|
||||
val subject = decode(message.subject).ifBlank { "(no subject)" }
|
||||
val body = ArrayList<String>()
|
||||
val attachments = JSONArray()
|
||||
val links = linkedSetOf<String>()
|
||||
collectParts(message, body, attachments, links)
|
||||
val bodyText = body.joinToString("\n\n").trim().take(8000)
|
||||
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
|
||||
val date = message.receivedDate ?: message.sentDate ?: Date()
|
||||
val tags = JSONArray().put(requestedFolder)
|
||||
val ruleLabels = account?.optJSONObject("ruleLabels")?.optJSONArray("$labelFolder:$uid")
|
||||
if (ruleLabels != null) {
|
||||
for (index in 0 until ruleLabels.length()) {
|
||||
val label = ruleLabels.optString(index)
|
||||
if (label.isNotBlank()) tags.put(label)
|
||||
}
|
||||
}
|
||||
val files = attachmentList(attachments)
|
||||
val flags = message.flags
|
||||
val id = uid.toDouble()
|
||||
return JSONObject()
|
||||
.put("id", id)
|
||||
.put("uid", uid)
|
||||
.put("initials", senderName.split(Regex("[\\s@]+")).filter(String::isNotBlank)
|
||||
.mapNotNull { it.firstOrNull()?.toString() }.joinToString("").take(2).uppercase(Locale.getDefault()))
|
||||
.put("color", "#dce6df")
|
||||
.put("sender", senderName)
|
||||
.put("email", senderEmail)
|
||||
.put("subject", subject)
|
||||
.put("snippet", snippet)
|
||||
.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)
|
||||
.put("unread", !flags.contains(Flags.Flag.SEEN))
|
||||
.put("star", flags.contains(Flags.Flag.FLAGGED))
|
||||
.put("tags", tags)
|
||||
.put("sent", requestedFolder == "Sent")
|
||||
.put("archived", requestedFolder == "Archive")
|
||||
.put("deleted", requestedFolder == "Trash")
|
||||
.put("sourceFolder", labelFolder)
|
||||
.put("body", JSONArray().apply {
|
||||
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40)
|
||||
if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
|
||||
})
|
||||
.put("links", JSONArray().apply { links.take(30).forEach(::put) })
|
||||
.put("attachments", attachments)
|
||||
.put("attachment", files.firstOrNull()?.optString("filename") ?: JSONObject.NULL)
|
||||
.put("size", files.firstOrNull()?.optString("size") ?: "")
|
||||
}
|
||||
|
||||
private fun attachmentList(attachments: JSONArray): List<JSONObject> =
|
||||
(0 until attachments.length()).map { attachments.getJSONObject(it) }
|
||||
|
||||
private fun collectParts(part: javax.mail.Part, body: MutableList<String>, attachments: JSONArray, links: MutableSet<String>) {
|
||||
val filename = decode(part.fileName)
|
||||
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
|
||||
val name = filename.ifBlank { "attachment" }
|
||||
val size = part.size.coerceAtLeast(0)
|
||||
attachments.put(JSONObject().put("filename", name).put("size", size))
|
||||
return
|
||||
}
|
||||
val content = try { part.content } catch (_: Exception) { return }
|
||||
when (content) {
|
||||
is String -> if (part.isMimeType("text/plain")) {
|
||||
body.add(content.replace("\r", "").trim())
|
||||
} else if (part.isMimeType("text/html")) {
|
||||
Regex("""<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
|
||||
.findAll(content)
|
||||
.mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&", "&") }
|
||||
.take(30)
|
||||
.forEach(links::add)
|
||||
if (body.isEmpty()) body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim())
|
||||
}
|
||||
is Multipart -> for (index in 0 until content.count) {
|
||||
collectParts(content.getBodyPart(index), body, attachments, links)
|
||||
}
|
||||
is javax.mail.BodyPart -> collectParts(content, body, attachments, links)
|
||||
}
|
||||
}
|
||||
|
||||
private fun findAttachment(part: javax.mail.Part, filename: String): MimeBodyPart? {
|
||||
val name = decode(part.fileName)
|
||||
if ((name == filename || (filename.isBlank() && name.isNotBlank())) && part is MimeBodyPart) return part
|
||||
val content = try { part.content } catch (_: Exception) { return null }
|
||||
if (content is Multipart) {
|
||||
for (index in 0 until content.count) {
|
||||
findAttachment(content.getBodyPart(index), filename)?.let { return it }
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun saveAttachmentBytes(context: Context, filename: String, contentType: String, bytes: ByteArray): JSONObject {
|
||||
val mimeType = contentType.substringBefore(';').ifBlank {
|
||||
MimeTypeMap.getSingleton().getMimeTypeFromExtension(filename.substringAfterLast('.', "")) ?: "application/octet-stream"
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
val values = ContentValues().apply {
|
||||
put(MediaStore.Downloads.DISPLAY_NAME, filename)
|
||||
put(MediaStore.Downloads.MIME_TYPE, mimeType)
|
||||
put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)
|
||||
}
|
||||
val uri = context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)
|
||||
?: throw IllegalStateException("Could not create the attachment in Downloads.")
|
||||
context.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
|
||||
?: throw IllegalStateException("Could not write the attachment.")
|
||||
return JSONObject().put("saved", true).put("uri", uri.toString()).put("filename", filename)
|
||||
}
|
||||
val directory = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
|
||||
?: throw IllegalStateException("Downloads storage is not available.")
|
||||
val file = File(directory, filename.replace(Regex("[\\\\/:*?\"<>|]"), "_"))
|
||||
file.writeBytes(bytes)
|
||||
return JSONObject().put("saved", true).put("path", file.absolutePath).put("filename", filename)
|
||||
}
|
||||
|
||||
private const val CUSTOM_FOLDER_PREFIX = "Folder:"
|
||||
private val reservedFolderNames = setOf(
|
||||
"inbox", "sent", "drafts", "archive", "trash", "starred", "snoozed", "junk", "spam",
|
||||
"sent items", "sent mail", "sent messages", "archives", "all mail", "deleted items", "deleted messages"
|
||||
)
|
||||
|
||||
fun isCustomFolder(name: String) = name.startsWith(CUSTOM_FOLDER_PREFIX)
|
||||
|
||||
private fun customFolders(store: Store): JSONArray {
|
||||
val systemAttributes = setOf("\\sent", "\\archive", "\\trash", "\\drafts", "\\junk", "\\all", "\\flagged")
|
||||
val result = JSONArray()
|
||||
val folders = try { store.defaultFolder.list("*") } catch (_: Exception) { emptyArray() }
|
||||
folders.filter { folder ->
|
||||
val attributes = (folder as? IMAPFolder)?.attributes?.map { it.lowercase(Locale.ROOT) } ?: emptyList()
|
||||
folder.fullName.uppercase(Locale.ROOT) != "INBOX" &&
|
||||
(folder.type and Folder.HOLDS_MESSAGES) != 0 &&
|
||||
attributes.none { it in systemAttributes } &&
|
||||
folder.fullName.lowercase(Locale.ROOT).split(Regex("[./]")).last() !in reservedFolderNames
|
||||
}.sortedBy { it.fullName }.forEach { folder ->
|
||||
result.put(JSONObject().put("name", folder.name).put("path", folder.fullName)
|
||||
.put("id", CUSTOM_FOLDER_PREFIX + folder.fullName))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
fun listFolders(account: JSONObject): JSONObject =
|
||||
withStore(account) { _, store -> JSONObject().put("folders", customFolders(store)) }
|
||||
|
||||
fun createFolder(account: JSONObject, rawName: String): JSONObject {
|
||||
val name = rawName.trim()
|
||||
require(name.isNotEmpty() && name.length <= 100) { "Enter a folder name of up to 100 characters." }
|
||||
require(!Regex("[\\\\/.*%#&\\u0000-\\u001f]").containsMatchIn(name)) {
|
||||
"Folder names cannot contain / \\ . * % # & or control characters."
|
||||
}
|
||||
require(name.lowercase(Locale.ROOT) !in reservedFolderNames) { "That folder name is reserved." }
|
||||
return withStore(account) { _, store ->
|
||||
val folder = store.getFolder(name)
|
||||
check(!folder.exists()) { "A folder with that name already exists." }
|
||||
check(folder.create(Folder.HOLDS_MESSAGES)) { "The mail server could not create that folder." }
|
||||
try { folder.isSubscribed = true } catch (_: Exception) {}
|
||||
JSONObject().put("ok", true)
|
||||
.put("folder", JSONObject().put("name", name).put("path", folder.fullName)
|
||||
.put("id", CUSTOM_FOLDER_PREFIX + folder.fullName))
|
||||
.put("folders", customFolders(store))
|
||||
}
|
||||
}
|
||||
).joinToString(separator = "|")
|
||||
|
||||
private fun resolveFolder(store: Store, requested: String): Folder? {
|
||||
if (requested.startsWith(CUSTOM_FOLDER_PREFIX)) {
|
||||
@@ -730,16 +98,12 @@ internal object AndroidMailService {
|
||||
val (specialUse, candidates) = when (requested) {
|
||||
"Sent" -> "\\Sent" to setOf("sent", "sent items", "sent mail", "sent messages")
|
||||
"Archive" -> "\\Archive" to setOf("archive", "archives", "all mail")
|
||||
"Trash" -> "\\Trash" to setOf("trash", "deleted items", "deleted messages")
|
||||
else -> return store.getFolder(requested).takeIf { it.exists() }
|
||||
}
|
||||
val folders = try { store.defaultFolder.list("*") } catch (_: Exception) { emptyArray() }
|
||||
return folders.firstOrNull { folder ->
|
||||
val imapFolder = folder as? IMAPFolder
|
||||
imapFolder?.attributes?.any { it.equals(specialUse, true) } == true
|
||||
} ?: folders.firstOrNull { folder ->
|
||||
folder.fullName.lowercase(Locale.ROOT).split(Regex("[./]")).lastOrNull() in candidates
|
||||
"Drafts" -> "\\Drafts" to setOf("drafts")
|
||||
"Trash" -> "\\Trash" to setOf("trash", "deleted items")
|
||||
else -> return null
|
||||
}
|
||||
return store.getFolderNames().firstOrNull { it.lowercase(Locale.ROOT) in candidates }
|
||||
?.let { store.getFolder(it) }
|
||||
}
|
||||
|
||||
private fun <T> withStore(account: JSONObject, block: (Session, Store) -> T): T {
|
||||
@@ -754,48 +118,7 @@ internal object AndroidMailService {
|
||||
)
|
||||
return block(session, store)
|
||||
} finally {
|
||||
if (store.isConnected) store.close()
|
||||
store.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun credentials(account: JSONObject) = object : Authenticator() {
|
||||
override fun getPasswordAuthentication() = PasswordAuthentication(
|
||||
account.optString("email"),
|
||||
account.optString("password")
|
||||
)
|
||||
}
|
||||
|
||||
private fun imapProperties(account: JSONObject) = Properties().apply {
|
||||
setProperty("mail.store.protocol", "imap")
|
||||
setProperty("mail.imap.host", account.optString("imapHost"))
|
||||
setProperty("mail.imap.port", account.optInt("imapPort", 143).toString())
|
||||
setProperty("mail.imap.auth", "true")
|
||||
setProperty("mail.imap.starttls.enable", "true")
|
||||
setProperty("mail.imap.starttls.required", "true")
|
||||
setProperty("mail.imap.ssl.checkserveridentity", "true")
|
||||
setProperty("mail.imap.connectiontimeout", "20000")
|
||||
setProperty("mail.imap.timeout", "30000")
|
||||
setProperty("mail.imap.writetimeout", "30000")
|
||||
}
|
||||
|
||||
private fun smtpProperties(account: JSONObject) = Properties().apply {
|
||||
setProperty("mail.smtp.host", account.optString("smtpHost"))
|
||||
setProperty("mail.smtp.port", account.optInt("smtpPort", 587).toString())
|
||||
setProperty("mail.smtp.auth", "true")
|
||||
setProperty("mail.smtp.starttls.enable", "true")
|
||||
setProperty("mail.smtp.starttls.required", "true")
|
||||
setProperty("mail.smtp.ssl.checkserveridentity", "true")
|
||||
setProperty("mail.smtp.connectiontimeout", "20000")
|
||||
setProperty("mail.smtp.timeout", "30000")
|
||||
setProperty("mail.smtp.writetimeout", "30000")
|
||||
}
|
||||
|
||||
private fun displayName(account: JSONObject) =
|
||||
account.optString("displayName").replace(Regex("[\\r\\n]"), " ").take(80)
|
||||
|
||||
private fun decode(value: String?): String = try {
|
||||
if (value.isNullOrBlank()) "" else MimeUtility.decodeText(value)
|
||||
} catch (_: Exception) {
|
||||
value.orEmpty()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ package studio.daybreak.mail;
|
||||
|
||||
import android.Manifest;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.os.Build;
|
||||
import android.os.Bundle;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.core.app.ActivityCompat;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import com.getcapacitor.BridgeActivity;
|
||||
|
||||
public class MainActivity extends BridgeActivity {
|
||||
@@ -13,7 +14,15 @@ public class MainActivity extends BridgeActivity {
|
||||
super.onCreate(savedInstanceState);
|
||||
registerPlugin(EpMailPlugin.class);
|
||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 701);
|
||||
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.POST_NOTIFICATIONS }, 1);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
|
||||
if (requestCode == 1 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
|
||||
// Permission granted, handle push notifications.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package studio.daybreak.mail
|
||||
|
||||
import com.google.firebase.messaging.FirebaseMessagingService
|
||||
import com.google.firebase.messaging.RemoteMessage
|
||||
|
||||
class MyFirebaseMessagingService : FirebaseMessagingService() {
|
||||
|
||||
override fun onMessageReceived(remoteMessage: RemoteMessage) {
|
||||
super.onMessageReceived(remoteMessage)
|
||||
|
||||
// Handle FCM messages here.
|
||||
// Example: Show a notification or update the UI.
|
||||
}
|
||||
|
||||
override fun onNewToken(token: String) {
|
||||
super.onNewToken(token)
|
||||
|
||||
// Send the new token to your server or save it locally.
|
||||
}
|
||||
}
|
||||
@@ -1,23 +1,18 @@
|
||||
// Top-level build file where you can add configuration options common to all sub-projects/modules.
|
||||
|
||||
buildscript {
|
||||
|
||||
ext.kotlin_version = '1.5.31'
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.13.0'
|
||||
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
|
||||
classpath 'com.google.gms:google-services:4.4.4'
|
||||
|
||||
// NOTE: Do not place your application dependencies here; they belong
|
||||
// in the individual module build.gradle files
|
||||
classpath "com.android.tools.build:gradle:4.2.2"
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
classpath "com.google.gms:google-services:4.3.10" // Add this line
|
||||
}
|
||||
}
|
||||
|
||||
apply from: "variables.gradle"
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
|
||||
+3
-163
@@ -7,8 +7,6 @@ const { simpleParser } = require('mailparser');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { createDAVClient } = require('tsdav');
|
||||
const ICAL = require('ical.js');
|
||||
const openpgp = require('openpgp');
|
||||
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
|
||||
|
||||
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
|
||||
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
||||
@@ -202,7 +200,6 @@ const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
|
||||
const pgpKeys = createKeyStore({
|
||||
async load() {
|
||||
try {
|
||||
assertSecureStorage();
|
||||
const { result } = await safeStorage.decryptStringAsync(await fs.readFile(pgpKeysPath()));
|
||||
return JSON.parse(result);
|
||||
} catch (error) {
|
||||
@@ -211,7 +208,6 @@ const pgpKeys = createKeyStore({
|
||||
}
|
||||
},
|
||||
async save(data) {
|
||||
assertSecureStorage();
|
||||
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.');
|
||||
await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true });
|
||||
await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 });
|
||||
@@ -221,11 +217,9 @@ const pgpKeys = createKeyStore({
|
||||
|
||||
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
|
||||
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
|
||||
const pgpKeyServers = createKeyServerService();
|
||||
|
||||
async function readDavStore() {
|
||||
try {
|
||||
assertSecureStorage();
|
||||
const encrypted = await fs.readFile(davCredentialsPath());
|
||||
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
||||
return JSON.parse(result);
|
||||
@@ -236,7 +230,6 @@ async function readDavStore() {
|
||||
}
|
||||
|
||||
async function saveDavStore(store) {
|
||||
assertSecureStorage();
|
||||
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure credential storage is unavailable.');
|
||||
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
|
||||
await fs.mkdir(path.dirname(davCredentialsPath()), { recursive: true });
|
||||
@@ -347,19 +340,9 @@ function smtpTransport(account) {
|
||||
});
|
||||
}
|
||||
|
||||
function assertSecureStorage() {
|
||||
if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') {
|
||||
const backend = safeStorage.getSelectedStorageBackend();
|
||||
if (backend === 'basic_text') {
|
||||
throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.');
|
||||
}
|
||||
}
|
||||
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
||||
}
|
||||
|
||||
async function readAccountStore() {
|
||||
try {
|
||||
assertSecureStorage();
|
||||
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
||||
const encrypted = await fs.readFile(credentialsPath());
|
||||
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
||||
const stored = JSON.parse(result);
|
||||
@@ -378,7 +361,6 @@ async function readAccountStore() {
|
||||
}
|
||||
|
||||
async function saveAccountStore(store) {
|
||||
assertSecureStorage();
|
||||
if (!await safeStorage.isAsyncEncryptionAvailable()) {
|
||||
throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.');
|
||||
}
|
||||
@@ -1319,12 +1301,6 @@ ipcMain.handle('pgp:export-private', async (event, fingerprint, passphrase) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
return saveKeyFile(event, `ep-mail-private-${id.slice(-16)}.asc`, await pgpKeys.exportPrivate(id, passphrase));
|
||||
});
|
||||
ipcMain.handle('pgp:change-passphrase', async (_event, input) => {
|
||||
const id = pgpFingerprint(input?.fingerprint);
|
||||
const result = await pgpKeys.changePassphrase(id, input?.currentPassphrase, input?.newPassphrase);
|
||||
pgpCache.clear(id);
|
||||
return result;
|
||||
});
|
||||
ipcMain.handle('pgp:export-revocation', async (event, fingerprint, passphrase) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase));
|
||||
@@ -1405,34 +1381,7 @@ ipcMain.handle('pgp:add-contact', async (event, input) => {
|
||||
if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.');
|
||||
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
|
||||
}
|
||||
const key = await openpgp.readKey({ armoredKey }).catch(() => {
|
||||
throw new Error('That is not a valid OpenPGP public key.');
|
||||
});
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
const emails = [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||
const existing = await pgpKeys.listContacts();
|
||||
const overlaps = existing.filter(item => (item.emails || []).some(email => emails.includes(String(email).toLowerCase())));
|
||||
if (overlaps.length) {
|
||||
const detail = overlaps.map(item => {
|
||||
const name = item.name || 'Unknown contact';
|
||||
const addresses = (item.emails || []).join(', ') || 'no address';
|
||||
const fp = String(item.fingerprint || '').replace(/(.{4})/g, '$1 ').trim();
|
||||
return `${name} (${addresses})\nFingerprint: ${fp}`;
|
||||
}).join('\n\n');
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Replace key'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Confirm key replacement',
|
||||
message: 'A different public key already exists for this email address.',
|
||||
detail: `New key:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nExisting key(s):\n${detail}\n\nOnly continue if you verified the new fingerprint with the owner.`,
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) throw new Error('Key replacement cancelled.');
|
||||
}
|
||||
const source = ['message', 'keyserver', 'paste'].includes(input?.source) ? input.source : 'import';
|
||||
return pgpKeys.addContact({ armoredKey, source });
|
||||
return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' });
|
||||
});
|
||||
ipcMain.handle('pgp:set-trust', async (event, fingerprint, trust) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
@@ -1465,98 +1414,6 @@ ipcMain.handle('pgp:set-settings', async (_event, input) => {
|
||||
pgpCache.clear();
|
||||
return settings;
|
||||
});
|
||||
ipcMain.handle('pgp:key-servers', async () => {
|
||||
const settings = await pgpKeys.getSettings();
|
||||
return listServers(settings.customKeyServers, settings.enabledKeyServers);
|
||||
});
|
||||
ipcMain.handle('pgp:set-key-server-enabled', async (_event, input) => {
|
||||
if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.');
|
||||
const settings = await pgpKeys.getSettings();
|
||||
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
|
||||
const serverId = String(input?.serverId || '');
|
||||
if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.');
|
||||
const enabled = new Set(settings.enabledKeyServers);
|
||||
if (input.enabled) enabled.add(serverId);
|
||||
else enabled.delete(serverId);
|
||||
await pgpKeys.setSettings({
|
||||
cacheMinutes: settings.cacheMinutes,
|
||||
customKeyServers: settings.customKeyServers,
|
||||
enabledKeyServers: [...enabled]
|
||||
});
|
||||
return { serverId, enabled: input.enabled };
|
||||
});
|
||||
ipcMain.handle('pgp:add-key-server', async (event, input) => {
|
||||
const candidate = normalizeCustomServer(input);
|
||||
const settings = await pgpKeys.getSettings();
|
||||
const customServers = settings.customKeyServers.map(normalizeCustomServer);
|
||||
if (customServers.length >= MAX_CUSTOM_SERVERS) throw new Error(`You can configure up to ${MAX_CUSTOM_SERVERS} custom key servers.`);
|
||||
if (customServers.some(server => server.url === candidate.url && server.protocol === candidate.protocol)) {
|
||||
throw new Error('That key server is already configured.');
|
||||
}
|
||||
const url = new URL(candidate.url);
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Add server'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Add custom key server?',
|
||||
message: `Allow ep-mail to contact ${url.host} for OpenPGP keys?`,
|
||||
detail: `Protocol: ${candidate.protocol.toUpperCase()}\nEndpoint: ${candidate.url}\nThe server may learn which email addresses you search for. Only add a server you trust.`,
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) return { canceled: true };
|
||||
candidate.id = randomUUID();
|
||||
const updated = await pgpKeys.setSettings({
|
||||
cacheMinutes: settings.cacheMinutes,
|
||||
customKeyServers: [...customServers, candidate]
|
||||
});
|
||||
return { server: updated.customKeyServers[updated.customKeyServers.length - 1] };
|
||||
});
|
||||
ipcMain.handle('pgp:remove-key-server', async (_event, serverId) => {
|
||||
const id = String(serverId || '');
|
||||
const settings = await pgpKeys.getSettings();
|
||||
const customServers = settings.customKeyServers.filter(server => server.id !== id);
|
||||
if (customServers.length === settings.customKeyServers.length) throw new Error('That custom key server was not found.');
|
||||
await pgpKeys.setSettings({
|
||||
cacheMinutes: settings.cacheMinutes,
|
||||
customKeyServers,
|
||||
enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id)
|
||||
});
|
||||
return { removed: true };
|
||||
});
|
||||
ipcMain.handle('pgp:find-key', async (_event, input) => {
|
||||
const settings = await pgpKeys.getSettings();
|
||||
const servers = listServers(settings.customKeyServers, settings.enabledKeyServers);
|
||||
return pgpKeyServers.lookupEnabled(servers, input?.email);
|
||||
});
|
||||
ipcMain.handle('pgp:publish-key', async (event, input) => {
|
||||
const fingerprint = pgpFingerprint(input?.fingerprint);
|
||||
const settings = await pgpKeys.getSettings();
|
||||
const server = listServers(settings.customKeyServers, settings.enabledKeyServers).find(item => item.id === String(input?.serverId || ''));
|
||||
if (!server) throw new Error('Choose a configured key server.');
|
||||
if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.');
|
||||
const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
if (!entry.email) throw new Error('This key has no email address to publish.');
|
||||
const armoredKey = await pgpKeys.exportPublic(fingerprint);
|
||||
const publicKey = await openpgp.readKey({ armoredKey });
|
||||
const emails = [...new Set(publicKey.getUserIDs()
|
||||
.map(userId => (/<([^>]+)>/.exec(userId)?.[1] || (userId.includes('@') ? userId : '')).trim().toLowerCase())
|
||||
.filter(Boolean))];
|
||||
if (!emails.includes(entry.email.toLowerCase())) throw new Error('The selected key no longer matches its stored email address.');
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Publish public key'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Publish public key?',
|
||||
message: `Publish the public key for ${emails.join(', ')} to ${server.name}?`,
|
||||
detail: `Fingerprint:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly the public key will be sent. This exposes the email address(es) in the key to the server, which may retain them. The server may send a verification email before the key becomes searchable.`,
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) return { canceled: true };
|
||||
return pgpKeyServers.publish(server, entry.email, armoredKey, fingerprint);
|
||||
});
|
||||
ipcMain.handle('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
|
||||
|
||||
ipcMain.handle('mail:open-external', async (event, rawUrl) => {
|
||||
@@ -1639,29 +1496,12 @@ async function sendMailNow(account, message) {
|
||||
return { ok: true, savedToSent };
|
||||
}
|
||||
|
||||
ipcMain.handle('mail:send', async (event, message) => {
|
||||
ipcMain.handle('mail:send', async (_event, message) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before sending.');
|
||||
const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null;
|
||||
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
|
||||
delete queuedMessage.pgp;
|
||||
if (!pgpOptions?.encrypt) {
|
||||
const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean);
|
||||
const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email });
|
||||
if (status.recipients.length && !status.missing.length) {
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Send anyway'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Send without encryption?',
|
||||
message: 'Public keys are available for all recipients.',
|
||||
detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.',
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) throw new Error('Plaintext send cancelled.');
|
||||
}
|
||||
}
|
||||
if (pgpOptions) {
|
||||
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
|
||||
const signature = String(account.signature || '').slice(0, 5000);
|
||||
|
||||
@@ -1,277 +0,0 @@
|
||||
const openpgp = require('openpgp');
|
||||
|
||||
const MAX_KEY_LENGTH = 200000;
|
||||
const MAX_RESPONSE_BYTES = 600000;
|
||||
const REQUEST_TIMEOUT_MS = 15000;
|
||||
const MAX_CUSTOM_SERVERS = 10;
|
||||
|
||||
const BUILTIN_SERVERS = [
|
||||
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
|
||||
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true }
|
||||
];
|
||||
|
||||
function normalizeBaseUrl(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (raw.length > 300) throw new Error('The key server URL is too long.');
|
||||
let url;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
throw new Error('Enter a valid HTTPS key server URL.');
|
||||
}
|
||||
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
|
||||
throw new Error('Key server URLs must use HTTPS and cannot contain credentials, a query, or a fragment.');
|
||||
}
|
||||
url.pathname = `${url.pathname.replace(/\/+$/, '')}/`;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function normalizeCustomServer(input) {
|
||||
const name = String(input?.name || '').trim().slice(0, 60);
|
||||
const protocol = input?.protocol;
|
||||
if (!name) throw new Error('Enter a name for the key server.');
|
||||
if (!['hkp', 'vks'].includes(protocol)) throw new Error('Choose a supported HKP or VKS protocol.');
|
||||
return {
|
||||
id: String(input?.id || ''),
|
||||
name,
|
||||
url: normalizeBaseUrl(input?.url),
|
||||
protocol,
|
||||
builtin: false
|
||||
};
|
||||
}
|
||||
|
||||
function listServers(customServers = [], enabledServerIds = []) {
|
||||
const enabled = new Set(enabledServerIds);
|
||||
return [
|
||||
...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })),
|
||||
...customServers.map(server => {
|
||||
const normalized = normalizeCustomServer(server);
|
||||
return { ...normalized, enabled: enabled.has(normalized.id) };
|
||||
})
|
||||
];
|
||||
}
|
||||
|
||||
function validateEmail(value) {
|
||||
const email = String(value || '').trim();
|
||||
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new Error('Enter a valid email address.');
|
||||
return email;
|
||||
}
|
||||
|
||||
function baseUrl(server) {
|
||||
return new URL(normalizeBaseUrl(server.url));
|
||||
}
|
||||
|
||||
function endpoint(server, path) {
|
||||
return new URL(path, baseUrl(server));
|
||||
}
|
||||
|
||||
async function readResponseText(response) {
|
||||
const declaredLength = Number(response.headers?.get?.('content-length') || 0);
|
||||
if (declaredLength > MAX_RESPONSE_BYTES) throw new Error('The key server response is too large.');
|
||||
if (!response.body) return '';
|
||||
const chunks = [];
|
||||
let length = 0;
|
||||
for await (const chunk of response.body) {
|
||||
const bytes = Buffer.from(chunk);
|
||||
length += bytes.length;
|
||||
if (length > MAX_RESPONSE_BYTES) {
|
||||
throw new Error('The key server response is too large.');
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
return Buffer.concat(chunks, length).toString('utf8');
|
||||
}
|
||||
|
||||
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
||||
if (typeof fetchImpl !== 'function') throw new Error('Fetch is unavailable for key server requests.');
|
||||
|
||||
async function request(server, url, options = {}) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetchImpl(url, {
|
||||
...options,
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Could not reach ${server.name}: ${error.message}`);
|
||||
}
|
||||
const text = await readResponseText(response);
|
||||
return { response, text };
|
||||
}
|
||||
|
||||
async function parsePublicKeys(armored, email) {
|
||||
if (typeof armored !== 'string' || armored.length > MAX_RESPONSE_BYTES) {
|
||||
throw new Error('The key server returned an invalid or oversized key response.');
|
||||
}
|
||||
const blocks = armored.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g) || [];
|
||||
if (!blocks.length) {
|
||||
if (!armored.trim() || /no (matching )?keys|no results/i.test(armored)) return [];
|
||||
throw new Error('The key server response did not contain an OpenPGP public key.');
|
||||
}
|
||||
if (blocks.length > 10) throw new Error('The key server returned too many keys.');
|
||||
const keys = [];
|
||||
const seen = new Set();
|
||||
let validKeyCount = 0;
|
||||
for (const block of blocks) {
|
||||
if (block.length > MAX_KEY_LENGTH) continue;
|
||||
const key = await openpgp.readKey({ armoredKey: block }).catch(() => null);
|
||||
if (!key) continue;
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
if (seen.has(fingerprint)) continue;
|
||||
seen.add(fingerprint);
|
||||
const emails = [...new Set(key.getUserIDs()
|
||||
.map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase())
|
||||
.filter(Boolean))];
|
||||
const primary = await key.getPrimaryUser().catch(() => null);
|
||||
if (!primary) continue;
|
||||
validKeyCount += 1;
|
||||
if (email && !emails.includes(email.toLowerCase())) continue;
|
||||
keys.push({
|
||||
fingerprint,
|
||||
name: primary.user.userID?.name || '',
|
||||
emails,
|
||||
armoredKey: key.armor()
|
||||
});
|
||||
}
|
||||
if (!validKeyCount) throw new Error('The key server returned no valid public keys.');
|
||||
return keys;
|
||||
}
|
||||
|
||||
async function lookup(serverInput, emailInput) {
|
||||
const server = normalizeCustomServer(serverInput);
|
||||
const email = validateEmail(emailInput);
|
||||
let url;
|
||||
if (server.protocol === 'vks') {
|
||||
url = endpoint(server, `vks/v1/by-email/${encodeURIComponent(email)}`);
|
||||
} else {
|
||||
url = endpoint(server, 'pks/lookup');
|
||||
url.searchParams.set('op', 'get');
|
||||
url.searchParams.set('search', email);
|
||||
}
|
||||
const { response, text } = await request(server, url);
|
||||
if (response.status === 404) return [];
|
||||
if (!response.ok) throw new Error(`${server.name} returned HTTP ${response.status}.`);
|
||||
let armored = text;
|
||||
if (server.protocol === 'hkp' && /^\s*\{/.test(text)) {
|
||||
try {
|
||||
const data = JSON.parse(text);
|
||||
armored = data.publicKeyArmored || '';
|
||||
} catch {
|
||||
throw new Error(`${server.name} returned an invalid key response.`);
|
||||
}
|
||||
}
|
||||
return parsePublicKeys(armored, email);
|
||||
}
|
||||
|
||||
async function lookupEnabled(serverInputs, emailInput) {
|
||||
const servers = serverInputs.filter(server => server.enabled === true);
|
||||
if (!servers.length) throw new Error('Enable at least one key server before searching.');
|
||||
const email = validateEmail(emailInput);
|
||||
const lookups = await Promise.all(servers.map(async server => {
|
||||
try {
|
||||
return { server, keys: await lookup(server, email), error: null };
|
||||
} catch (error) {
|
||||
return { server, keys: [], error: error.message };
|
||||
}
|
||||
}));
|
||||
const keysByFingerprint = new Map();
|
||||
for (const result of lookups) {
|
||||
for (const key of result.keys) {
|
||||
const existing = keysByFingerprint.get(key.fingerprint);
|
||||
if (existing) existing.sources.push(result.server.name);
|
||||
else keysByFingerprint.set(key.fingerprint, { ...key, sources: [result.server.name] });
|
||||
}
|
||||
}
|
||||
return {
|
||||
keys: [...keysByFingerprint.values()],
|
||||
searchedServers: lookups.map(({ server }) => ({ id: server.id, name: server.name })),
|
||||
errors: lookups.filter(result => result.error).map(({ server, error }) => ({
|
||||
id: server.id,
|
||||
name: server.name,
|
||||
message: error
|
||||
}))
|
||||
};
|
||||
}
|
||||
|
||||
async function publishVks(server, email, armoredKey, expectedFingerprint) {
|
||||
const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||
body: JSON.stringify({ keytext: armoredKey })
|
||||
});
|
||||
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
||||
let result;
|
||||
try { result = JSON.parse(text); } catch { throw new Error(`${server.name} returned an invalid upload response.`); }
|
||||
if (String(result.key_fpr || '').toUpperCase() !== expectedFingerprint || !result.token || !result.status || typeof result.status !== 'object') {
|
||||
throw new Error(`${server.name} returned an incomplete or mismatched upload response.`);
|
||||
}
|
||||
const addressStatus = Object.entries(result.status).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||
if (addressStatus === 'published') return { uploaded: true, verification: 'published' };
|
||||
if (addressStatus === 'pending') return { uploaded: true, verification: 'pending' };
|
||||
if (addressStatus !== 'unpublished') {
|
||||
return { uploaded: true, verification: addressStatus || 'unknown' };
|
||||
}
|
||||
try {
|
||||
const verify = await request(server, endpoint(server, 'vks/v1/request-verify'), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||
body: JSON.stringify({ token: result.token, addresses: [email] })
|
||||
});
|
||||
if (!verify.response.ok) throw new Error(`HTTP ${verify.response.status}`);
|
||||
let verified;
|
||||
try { verified = JSON.parse(verify.text); } catch { throw new Error('invalid verification response'); }
|
||||
if (String(verified.key_fpr || '').toUpperCase() !== expectedFingerprint || !verified.status || typeof verified.status !== 'object') {
|
||||
throw new Error('verification response did not match the uploaded key');
|
||||
}
|
||||
const state = Object.entries(verified.status || {}).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||
return { uploaded: true, verification: state || 'requested' };
|
||||
} catch (error) {
|
||||
return { uploaded: true, verification: 'request-failed', warning: `The key was uploaded, but email verification could not be requested: ${error.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function publishHkp(server, armoredKey) {
|
||||
const form = new URLSearchParams({ keytext: armoredKey });
|
||||
const { response, text } = await request(server, endpoint(server, 'pks/add'), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: form.toString()
|
||||
});
|
||||
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
||||
if (!/upload successful|successfully added|key added/i.test(text)) {
|
||||
throw new Error(`${server.name} did not confirm the key upload: ${text.trim().slice(0, 300) || 'empty response'}`);
|
||||
}
|
||||
return {
|
||||
uploaded: true,
|
||||
verification: server.id === 'mailvelope-hkp' ? 'check-email' : 'server-accepted',
|
||||
message: text.trim().slice(0, 500)
|
||||
};
|
||||
}
|
||||
|
||||
async function publish(serverInput, emailInput, armoredInput, expectedFingerprint) {
|
||||
const server = normalizeCustomServer(serverInput);
|
||||
const email = validateEmail(emailInput);
|
||||
const armoredKey = String(armoredInput || '').trim();
|
||||
if (!armoredKey || armoredKey.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armoredKey)) {
|
||||
throw new Error('Only a valid public key can be published.');
|
||||
}
|
||||
const keys = await parsePublicKeys(armoredKey, email);
|
||||
if (keys.length !== 1 || keys[0].fingerprint !== String(expectedFingerprint || '').toUpperCase()) {
|
||||
throw new Error('The selected public key does not match the key and email being published.');
|
||||
}
|
||||
if (server.protocol === 'vks') return publishVks(server, email, keys[0].armoredKey, keys[0].fingerprint);
|
||||
return publishHkp(server, keys[0].armoredKey);
|
||||
}
|
||||
|
||||
return { lookup, lookupEnabled, publish };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BUILTIN_SERVERS,
|
||||
MAX_CUSTOM_SERVERS,
|
||||
createKeyServerService,
|
||||
listServers,
|
||||
normalizeBaseUrl,
|
||||
normalizeCustomServer
|
||||
};
|
||||
@@ -109,7 +109,7 @@ function createKeyStore(storage) {
|
||||
name: user.user.userID?.name || '',
|
||||
emails,
|
||||
trust: 'unknown',
|
||||
source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import',
|
||||
source: ['import', 'message', 'paste'].includes(source) ? source : 'import',
|
||||
addedAt: Date.now(),
|
||||
publicKey: key.armor()
|
||||
};
|
||||
@@ -193,43 +193,16 @@ function createKeyStore(storage) {
|
||||
|
||||
async getSettings() {
|
||||
const settings = (await read()).settings;
|
||||
return {
|
||||
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
|
||||
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [],
|
||||
enabledKeyServers: Array.isArray(settings.enabledKeyServers)
|
||||
? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))]
|
||||
: []
|
||||
};
|
||||
return { cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES };
|
||||
},
|
||||
|
||||
async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) {
|
||||
async setSettings({ cacheMinutes }) {
|
||||
const minutes = Number(cacheMinutes);
|
||||
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
||||
const data = await read();
|
||||
data.settings.cacheMinutes = Math.round(minutes);
|
||||
if (customKeyServers !== undefined) {
|
||||
if (!Array.isArray(customKeyServers) || customKeyServers.length > 10 || customKeyServers.some(server => !server || typeof server !== 'object')) {
|
||||
throw new Error('You can configure up to 10 valid custom key servers.');
|
||||
}
|
||||
data.settings.customKeyServers = customKeyServers.map(server => ({
|
||||
id: String(server.id || ''),
|
||||
name: String(server.name || '').slice(0, 60),
|
||||
url: String(server.url || '').slice(0, 300),
|
||||
protocol: String(server.protocol || '')
|
||||
}));
|
||||
}
|
||||
if (enabledKeyServers !== undefined) {
|
||||
if (!Array.isArray(enabledKeyServers) || enabledKeyServers.length > 12 || enabledKeyServers.some(id => typeof id !== 'string' || !id.trim())) {
|
||||
throw new Error('Choose no more than 12 valid enabled key servers.');
|
||||
}
|
||||
data.settings.enabledKeyServers = [...new Set(enabledKeyServers)];
|
||||
}
|
||||
await storage.save(data);
|
||||
return {
|
||||
cacheMinutes: data.settings.cacheMinutes,
|
||||
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
|
||||
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : []
|
||||
};
|
||||
return { cacheMinutes: data.settings.cacheMinutes };
|
||||
},
|
||||
|
||||
async list() {
|
||||
@@ -305,24 +278,6 @@ function createKeyStore(storage) {
|
||||
return entry.privateKey;
|
||||
},
|
||||
|
||||
async changePassphrase(fingerprint, currentPassphrase, newPassphrase) {
|
||||
requirePassphrase(newPassphrase);
|
||||
const data = await read();
|
||||
const keyIndex = data.keys.findIndex(key => key.fingerprint === fingerprint);
|
||||
if (keyIndex < 0) throw new Error('That key was not found.');
|
||||
const entry = data.keys[keyIndex];
|
||||
const privateKey = await unlock(entry.privateKey, currentPassphrase);
|
||||
const protectedKey = await openpgp.encryptKey({ privateKey, passphrase: newPassphrase });
|
||||
const updated = {
|
||||
...data,
|
||||
keys: data.keys.map((key, index) => index === keyIndex
|
||||
? { ...key, privateKey: protectedKey.armor() }
|
||||
: key)
|
||||
};
|
||||
await storage.save(updated);
|
||||
return { changed: true };
|
||||
},
|
||||
|
||||
async exportRevocation(fingerprint, passphrase) {
|
||||
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
|
||||
+1
-8
@@ -29,7 +29,6 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
||||
importKey: details => ipcRenderer.invoke('pgp:import', details),
|
||||
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
|
||||
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
|
||||
changePassphrase: details => ipcRenderer.invoke('pgp:change-passphrase', details),
|
||||
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
|
||||
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
|
||||
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
|
||||
@@ -41,13 +40,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
||||
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
|
||||
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
|
||||
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
|
||||
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases'),
|
||||
keyServers: () => ipcRenderer.invoke('pgp:key-servers'),
|
||||
setKeyServerEnabled: (serverId, enabled) => ipcRenderer.invoke('pgp:set-key-server-enabled', { serverId, enabled }),
|
||||
addKeyServer: server => ipcRenderer.invoke('pgp:add-key-server', server),
|
||||
removeKeyServer: id => ipcRenderer.invoke('pgp:remove-key-server', id),
|
||||
findKey: details => ipcRenderer.invoke('pgp:find-key', details),
|
||||
publishKey: details => ipcRenderer.invoke('pgp:publish-key', details)
|
||||
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases')
|
||||
},
|
||||
davList: () => ipcRenderer.invoke('dav:list'),
|
||||
davConnect: config => ipcRenderer.invoke('dav:connect', config),
|
||||
|
||||
@@ -7,27 +7,9 @@ function openEncryptionKeys() {
|
||||
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">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>
|
||||
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
|
||||
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
|
||||
<h3 class="pgp-heading">Contact public keys</h3>
|
||||
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
||||
<h3 class="pgp-heading">Public key servers</h3>
|
||||
<p class="account-note">Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.</p>
|
||||
<div id="pgp-server-list" class="attachment-list">Loading key servers…</div>
|
||||
<label class="compose-line"><span>Email address</span><input id="pgp-search-email" type="email" value="${esc(account.email || '')}"></label>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-find-key">Search all enabled servers</button></div>
|
||||
<div id="pgp-found-keys" class="attachment-list"></div>
|
||||
<label class="compose-line"><span>Publish to one server</span><select id="pgp-publish-server"></select></label>
|
||||
<p class="account-note">Publishing targets only the selected enabled server. ep-mail names the destination and asks for native confirmation before uploading.</p>
|
||||
<h4 class="pgp-heading">Add a custom HTTPS server</h4>
|
||||
<label class="compose-line"><span>Name</span><input id="pgp-server-name" maxlength="60" placeholder="My key server"></label>
|
||||
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
|
||||
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>
|
||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||
@@ -44,15 +26,6 @@ function openEncryptionKeys() {
|
||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||
const status = message => { $('#pgp-status').textContent = message; };
|
||||
const passphraseField = () => $('#pgp-passphrase');
|
||||
let keyServers = [];
|
||||
const selectedPublishServer = () => keyServers.find(server => server.id === $('#pgp-publish-server').value && server.enabled);
|
||||
const updatePublishButtons = () => {
|
||||
const server = selectedPublishServer();
|
||||
$$('.pgp-publish').forEach(button => {
|
||||
button.disabled = !server;
|
||||
button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…';
|
||||
});
|
||||
};
|
||||
const needPassphrase = () => {
|
||||
const value = passphraseField().value;
|
||||
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
||||
@@ -82,44 +55,6 @@ function openEncryptionKeys() {
|
||||
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
||||
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
||||
];
|
||||
const changePassphrase = document.createElement('button');
|
||||
changePassphrase.className = 'discard';
|
||||
changePassphrase.textContent = 'Change passphrase…';
|
||||
changePassphrase.onclick = async () => {
|
||||
const currentPassphrase = $('#pgp-change-current-passphrase').value;
|
||||
if (!currentPassphrase) {
|
||||
status('Enter the current passphrase for this key.');
|
||||
$('#pgp-change-current-passphrase').focus();
|
||||
return;
|
||||
}
|
||||
const newPassphrase = $('#pgp-new-passphrase').value;
|
||||
if (newPassphrase.length < 8) {
|
||||
status('Use a new passphrase of at least 8 characters.');
|
||||
$('#pgp-new-passphrase').focus();
|
||||
return;
|
||||
}
|
||||
if (newPassphrase !== $('#pgp-confirm-passphrase').value) {
|
||||
status('The new passphrases do not match.');
|
||||
$('#pgp-confirm-passphrase').focus();
|
||||
return;
|
||||
}
|
||||
changePassphrase.disabled = true;
|
||||
try {
|
||||
await window.daybreakMail.pgp.changePassphrase({
|
||||
fingerprint: key.fingerprint,
|
||||
currentPassphrase,
|
||||
newPassphrase
|
||||
});
|
||||
$('#pgp-change-current-passphrase').value = '';
|
||||
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
|
||||
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
|
||||
finally {
|
||||
$('#pgp-new-passphrase').value = '';
|
||||
$('#pgp-confirm-passphrase').value = '';
|
||||
changePassphrase.disabled = false;
|
||||
}
|
||||
};
|
||||
row.append(changePassphrase);
|
||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||
actions.push(['Delete', async () => {
|
||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||
@@ -140,28 +75,8 @@ function openEncryptionKeys() {
|
||||
};
|
||||
row.append(button);
|
||||
});
|
||||
const publish = document.createElement('button');
|
||||
publish.className = 'discard pgp-publish';
|
||||
publish.onclick = async () => {
|
||||
const server = selectedPublishServer();
|
||||
if (!server) { status('Enable a key server and select it as the publication target first.'); return; }
|
||||
publish.disabled = true;
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id });
|
||||
if (result.canceled) return;
|
||||
if (result.warning) status(result.warning);
|
||||
else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${server.name}. Check ${key.email || 'your email'} for a verification message before the key becomes searchable.`);
|
||||
else if (result.verification === 'published') status(`The key is already published and searchable on ${server.name}.`);
|
||||
else if (result.verification === 'request-failed') status('The key was uploaded, but the server could not request email verification.');
|
||||
else if (result.verification === 'check-email') status(`${server.name} accepted the key. Check ${key.email || 'your email'} for its verification message. ${result.message || ''}`.trim());
|
||||
else status(`${server.name} accepted the key. ${result.message || ''}`.trim());
|
||||
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
||||
finally { updatePublishButtons(); }
|
||||
};
|
||||
row.append(publish);
|
||||
list.append(row);
|
||||
});
|
||||
updatePublishButtons();
|
||||
}
|
||||
|
||||
$('#pgp-generate').onclick = async () => {
|
||||
@@ -251,153 +166,12 @@ function openEncryptionKeys() {
|
||||
await renderContacts();
|
||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||
};
|
||||
async function renderKeyServers() {
|
||||
const list = $('#pgp-server-list');
|
||||
const selector = $('#pgp-publish-server');
|
||||
const selectedId = selector.value;
|
||||
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
||||
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
||||
selector.replaceChildren();
|
||||
const enabledServers = keyServers.filter(server => server.enabled);
|
||||
if (!enabledServers.length) {
|
||||
const option = document.createElement('option');
|
||||
option.value = '';
|
||||
option.textContent = 'No enabled servers';
|
||||
selector.append(option);
|
||||
} else enabledServers.forEach(server => {
|
||||
const option = document.createElement('option');
|
||||
option.value = server.id;
|
||||
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
||||
option.selected = server.id === selectedId;
|
||||
selector.append(option);
|
||||
});
|
||||
if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0;
|
||||
selector.onchange = updatePublishButtons;
|
||||
list.replaceChildren();
|
||||
keyServers.forEach(server => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'attachment-row';
|
||||
const info = document.createElement('div');
|
||||
info.className = 'attachment-row-info';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = server.name;
|
||||
const details = document.createElement('small');
|
||||
details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`;
|
||||
info.append(title, details);
|
||||
const enabledLabel = document.createElement('label');
|
||||
enabledLabel.className = 'compose-line';
|
||||
const enabledText = document.createElement('span');
|
||||
enabledText.textContent = 'Use for lookup and publishing';
|
||||
const enabled = document.createElement('input');
|
||||
enabled.type = 'checkbox';
|
||||
enabled.checked = server.enabled;
|
||||
enabled.setAttribute('aria-label', `${server.name} enabled`);
|
||||
enabled.onchange = async () => {
|
||||
enabled.disabled = true;
|
||||
try {
|
||||
await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked);
|
||||
await renderKeyServers();
|
||||
status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`);
|
||||
} catch (error) {
|
||||
enabled.checked = server.enabled;
|
||||
status(error.message || `Could not update ${server.name}.`);
|
||||
} finally { enabled.disabled = false; }
|
||||
};
|
||||
enabledLabel.append(enabledText, enabled);
|
||||
row.append(info, enabledLabel);
|
||||
if (!server.builtin) {
|
||||
const remove = document.createElement('button');
|
||||
remove.className = 'discard';
|
||||
remove.textContent = 'Remove';
|
||||
remove.onclick = async () => {
|
||||
try {
|
||||
await window.daybreakMail.pgp.removeKeyServer(server.id);
|
||||
await renderKeyServers();
|
||||
status('Custom key server removed.');
|
||||
} catch (error) { status(error.message || 'Could not remove the key server.'); }
|
||||
};
|
||||
row.append(remove);
|
||||
}
|
||||
list.append(row);
|
||||
});
|
||||
}
|
||||
$('#pgp-find-key').onclick = async () => {
|
||||
const button = $('#pgp-find-key');
|
||||
const results = $('#pgp-found-keys');
|
||||
button.disabled = true;
|
||||
results.textContent = 'Searching…';
|
||||
try {
|
||||
const found = await window.daybreakMail.pgp.findKey({
|
||||
email: $('#pgp-search-email').value
|
||||
});
|
||||
results.replaceChildren();
|
||||
found.keys.forEach(key => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'attachment-row';
|
||||
const info = document.createElement('div');
|
||||
info.className = 'attachment-row-info';
|
||||
const title = document.createElement('strong');
|
||||
title.textContent = key.emails.join(', ') || key.name || 'Public key';
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = `Found on ${key.sources.join(', ')} · not verified`;
|
||||
const fingerprint = document.createElement('small');
|
||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||
info.append(title, meta, fingerprint);
|
||||
const add = document.createElement('button');
|
||||
add.className = 'discard';
|
||||
add.textContent = 'Add to contacts…';
|
||||
add.onclick = async () => {
|
||||
add.disabled = true;
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||
if (result.canceled) return;
|
||||
status(result.keyChangedFrom?.length ? 'Key added. You already had another key for this address; compare fingerprints before trusting either key.' : 'Key added as unverified. Compare its fingerprint with the owner before trusting it.');
|
||||
await renderContacts();
|
||||
row.remove();
|
||||
} catch (error) { status(error.message || 'Could not add the public key.'); }
|
||||
finally { add.disabled = false; }
|
||||
};
|
||||
row.append(info, add);
|
||||
results.append(row);
|
||||
});
|
||||
found.errors.forEach(error => {
|
||||
const warning = document.createElement('small');
|
||||
warning.textContent = `${error.name}: ${error.message}`;
|
||||
results.append(warning);
|
||||
});
|
||||
if (!found.keys.length && !found.errors.length) results.textContent = 'No matching public key was found on the enabled servers.';
|
||||
if (found.keys.length) status(`Found ${found.keys.length} public key(s) on ${found.searchedServers.map(server => server.name).join(', ')}. They remain unverified until you check their fingerprints independently.${found.errors.length ? ` ${found.errors.length} server(s) could not be searched; see details above.` : ''}`);
|
||||
else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`);
|
||||
else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`);
|
||||
} catch (error) {
|
||||
results.textContent = '';
|
||||
status(error.message || 'Could not search the key server.');
|
||||
} finally { button.disabled = false; }
|
||||
};
|
||||
$('#pgp-add-server').onclick = async () => {
|
||||
const button = $('#pgp-add-server');
|
||||
button.disabled = true;
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.addKeyServer({
|
||||
name: $('#pgp-server-name').value,
|
||||
url: $('#pgp-server-url').value,
|
||||
protocol: $('#pgp-server-protocol').value
|
||||
});
|
||||
if (result.canceled) return;
|
||||
$('#pgp-server-name').value = '';
|
||||
$('#pgp-server-url').value = '';
|
||||
await renderKeyServers();
|
||||
status('Custom key server added.');
|
||||
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
||||
finally { button.disabled = false; }
|
||||
};
|
||||
window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||
$('#pgp-save-cache').onclick = async () => {
|
||||
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number($('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||
};
|
||||
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||
void renderKeyServers();
|
||||
void renderContacts();
|
||||
void render();
|
||||
}
|
||||
|
||||
@@ -1,244 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const openpgp = require('openpgp');
|
||||
const { createKeyServerService, listServers, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs');
|
||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||
|
||||
const email = 'ada@example.org';
|
||||
|
||||
function memoryStore() {
|
||||
let data = null;
|
||||
return {
|
||||
async load() { return data && JSON.parse(JSON.stringify(data)); },
|
||||
async save(value) { data = JSON.parse(JSON.stringify(value)); }
|
||||
};
|
||||
}
|
||||
|
||||
async function makeKey() {
|
||||
const generated = await openpgp.generateKey({
|
||||
type: 'ecc',
|
||||
curve: 'curve25519Legacy',
|
||||
userIDs: [{ name: 'Ada Lovelace', email }],
|
||||
passphrase: 'correct horse battery',
|
||||
format: 'armored'
|
||||
});
|
||||
const key = await openpgp.readKey({ armoredKey: generated.publicKey });
|
||||
return { fingerprint: key.getFingerprint().toUpperCase(), armoredKey: key.armor() };
|
||||
}
|
||||
|
||||
test('validates custom HTTPS key server configuration', () => {
|
||||
assert.deepEqual(normalizeCustomServer({
|
||||
id: 'custom',
|
||||
name: 'Internal server',
|
||||
url: 'https://keys.example.org/openpgp',
|
||||
protocol: 'hkp'
|
||||
}), {
|
||||
id: 'custom',
|
||||
name: 'Internal server',
|
||||
url: 'https://keys.example.org/openpgp/',
|
||||
protocol: 'hkp',
|
||||
builtin: false
|
||||
});
|
||||
assert.throws(() => normalizeCustomServer({ name: 'Plain HTTP', url: 'http://keys.example.org', protocol: 'hkp' }), /HTTPS/);
|
||||
assert.throws(() => normalizeCustomServer({ name: 'Credential URL', url: 'https://user:pass@keys.example.org', protocol: 'vks' }), /credentials/);
|
||||
assert.throws(() => normalizeCustomServer({ name: 'Query URL', url: 'https://keys.example.org/?token=x', protocol: 'vks' }), /query/);
|
||||
assert.throws(() => normalizeCustomServer({ name: 'Unknown protocol', url: 'https://keys.example.org', protocol: 'unknown' }), /protocol/);
|
||||
});
|
||||
|
||||
test('all built-in and custom key servers start disabled', () => {
|
||||
const servers = listServers([{
|
||||
id: 'custom',
|
||||
name: 'Internal server',
|
||||
url: 'https://keys.example.org',
|
||||
protocol: 'hkp'
|
||||
}]);
|
||||
assert.equal(servers.length, 3);
|
||||
assert.ok(servers.every(server => server.enabled === false));
|
||||
const enabled = listServers([], ['openpgp-vks']);
|
||||
assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true);
|
||||
assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false);
|
||||
});
|
||||
|
||||
test('VKS lookup returns only valid keys matching the requested address', async () => {
|
||||
const key = await makeKey();
|
||||
let requestedUrl;
|
||||
const service = createKeyServerService({
|
||||
async fetchImpl(url, options) {
|
||||
requestedUrl = new URL(url);
|
||||
assert.equal(options.redirect, 'error');
|
||||
return new Response(key.armoredKey, { status: 200, headers: { 'content-type': 'application/pgp-keys' } });
|
||||
}
|
||||
});
|
||||
const found = await service.lookup({
|
||||
id: 'openpgp-vks',
|
||||
name: 'keys.openpgp.org',
|
||||
url: 'https://keys.openpgp.org',
|
||||
protocol: 'vks'
|
||||
}, email);
|
||||
assert.equal(requestedUrl.pathname, '/vks/v1/by-email/ada%40example.org');
|
||||
assert.equal(found.length, 1);
|
||||
assert.equal(found[0].fingerprint, key.fingerprint);
|
||||
assert.deepEqual(found[0].emails, [email]);
|
||||
});
|
||||
|
||||
test('HKP lookup filters unrelated keys and reports an empty result', async () => {
|
||||
const key = await makeKey();
|
||||
let requestedUrl;
|
||||
const service = createKeyServerService({
|
||||
async fetchImpl(url) {
|
||||
requestedUrl = new URL(url);
|
||||
return new Response(`not a key\n${key.armoredKey}`, { status: 200 });
|
||||
}
|
||||
});
|
||||
const server = { id: 'custom', name: 'Example', url: 'https://keys.example.org/base/', protocol: 'hkp' };
|
||||
const found = await service.lookup(server, email);
|
||||
assert.equal(requestedUrl.pathname, '/base/pks/lookup');
|
||||
assert.equal(requestedUrl.searchParams.get('op'), 'get');
|
||||
assert.equal(requestedUrl.searchParams.get('search'), email);
|
||||
assert.equal(found.length, 1);
|
||||
assert.deepEqual(await service.lookup(server, 'other@example.org'), []);
|
||||
});
|
||||
|
||||
test('enabled-server lookup checks every enabled server, merges duplicate keys and reports failures', async () => {
|
||||
const key = await makeKey();
|
||||
const requested = [];
|
||||
const service = createKeyServerService({
|
||||
async fetchImpl(url) {
|
||||
const target = new URL(url);
|
||||
requested.push(target.hostname);
|
||||
if (target.hostname === 'broken.example.org') throw new Error('server unavailable');
|
||||
return new Response(key.armoredKey, { status: 200 });
|
||||
}
|
||||
});
|
||||
const results = await service.lookupEnabled([
|
||||
{ id: 'one', name: 'First', url: 'https://first.example.org', protocol: 'hkp', enabled: true },
|
||||
{ id: 'two', name: 'Second', url: 'https://second.example.org', protocol: 'vks', enabled: true },
|
||||
{ id: 'bad', name: 'Offline', url: 'https://broken.example.org', protocol: 'hkp', enabled: true },
|
||||
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
|
||||
], email);
|
||||
assert.deepEqual(requested.sort(), ['broken.example.org', 'first.example.org', 'second.example.org']);
|
||||
assert.equal(results.keys.length, 1);
|
||||
assert.deepEqual(results.keys[0].sources, ['First', 'Second']);
|
||||
assert.deepEqual(results.errors.map(error => error.name), ['Offline']);
|
||||
assert.deepEqual(results.searchedServers.map(server => server.name), ['First', 'Second', 'Offline']);
|
||||
await assert.rejects(() => service.lookupEnabled([
|
||||
{ id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false }
|
||||
], email), /Enable at least one key server/);
|
||||
});
|
||||
|
||||
test('VKS publication uploads only the public key and requests email verification', async () => {
|
||||
const key = await makeKey();
|
||||
const calls = [];
|
||||
const service = createKeyServerService({
|
||||
async fetchImpl(url, options) {
|
||||
calls.push({ url: new URL(url), options });
|
||||
if (calls.length === 1) {
|
||||
return Response.json({
|
||||
key_fpr: key.fingerprint,
|
||||
token: 'temporary-upload-token',
|
||||
status: { [email]: 'unpublished' }
|
||||
});
|
||||
}
|
||||
return Response.json({ key_fpr: key.fingerprint, token: 'temporary-upload-token', status: { [email]: 'pending' } });
|
||||
}
|
||||
});
|
||||
const result = await service.publish({
|
||||
id: 'openpgp-vks',
|
||||
name: 'keys.openpgp.org',
|
||||
url: 'https://keys.openpgp.org',
|
||||
protocol: 'vks'
|
||||
}, email, key.armoredKey, key.fingerprint);
|
||||
assert.equal(calls[0].url.pathname, '/vks/v1/upload');
|
||||
assert.equal(calls[1].url.pathname, '/vks/v1/request-verify');
|
||||
assert.equal(result.verification, 'pending');
|
||||
const upload = JSON.parse(calls[0].options.body);
|
||||
assert.equal(upload.keytext, key.armoredKey);
|
||||
assert.equal(upload.keytext.includes('PRIVATE KEY'), false);
|
||||
assert.deepEqual(JSON.parse(calls[1].options.body).addresses, [email]);
|
||||
});
|
||||
|
||||
test('HKP publication posts armored public material only', async () => {
|
||||
const key = await makeKey();
|
||||
let requestInfo;
|
||||
const service = createKeyServerService({
|
||||
async fetchImpl(url, options) {
|
||||
requestInfo = { url: new URL(url), options };
|
||||
return new Response('Upload successful. Check your inbox to verify your email address.', { status: 200 });
|
||||
}
|
||||
});
|
||||
const result = await service.publish({
|
||||
id: 'mailvelope-hkp',
|
||||
name: 'keys.mailvelope.com',
|
||||
url: 'https://keys.mailvelope.com',
|
||||
protocol: 'hkp'
|
||||
}, email, key.armoredKey, key.fingerprint);
|
||||
assert.equal(requestInfo.url.pathname, '/pks/add');
|
||||
assert.equal(requestInfo.options.headers['content-type'], 'application/x-www-form-urlencoded');
|
||||
assert.equal(new URLSearchParams(requestInfo.options.body).get('keytext'), key.armoredKey);
|
||||
assert.equal(requestInfo.options.body.includes('PRIVATE KEY'), false);
|
||||
assert.equal(result.verification, 'check-email');
|
||||
});
|
||||
|
||||
test('key-server contact imports stay untrusted and retain keyserver provenance', async () => {
|
||||
const key = await makeKey();
|
||||
const keyStore = createKeyStore(memoryStore());
|
||||
const added = await keyStore.addContact({ armoredKey: key.armoredKey, source: 'keyserver' });
|
||||
assert.equal(added.contact.trust, 'unknown');
|
||||
assert.equal(added.contact.source, 'keyserver');
|
||||
});
|
||||
|
||||
test('lookup rejects oversized responses and HTTP failures', async () => {
|
||||
const server = { id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks' };
|
||||
const tooLarge = createKeyServerService({
|
||||
async fetchImpl() { return new Response('x'.repeat(600001), { status: 200 }); }
|
||||
});
|
||||
await assert.rejects(() => tooLarge.lookup(server, email), /too large/);
|
||||
const failure = createKeyServerService({
|
||||
async fetchImpl() { return new Response('', { status: 503 }); }
|
||||
});
|
||||
await assert.rejects(() => failure.lookup(server, email), /HTTP 503/);
|
||||
const invalid = createKeyServerService({
|
||||
async fetchImpl() { return new Response('<html>unexpected response</html>', { status: 200 }); }
|
||||
});
|
||||
await assert.rejects(() => invalid.lookup(server, email), /did not contain an OpenPGP public key/);
|
||||
});
|
||||
|
||||
test('VKS verification failure reports that the key upload already succeeded', async () => {
|
||||
const key = await makeKey();
|
||||
let calls = 0;
|
||||
const service = createKeyServerService({
|
||||
async fetchImpl() {
|
||||
calls += 1;
|
||||
if (calls === 1) {
|
||||
return Response.json({
|
||||
key_fpr: key.fingerprint,
|
||||
token: 'temporary-upload-token',
|
||||
status: { [email]: 'unpublished' }
|
||||
});
|
||||
}
|
||||
throw new Error('network unavailable');
|
||||
}
|
||||
});
|
||||
const result = await service.publish({
|
||||
id: 'openpgp-vks',
|
||||
name: 'keys.openpgp.org',
|
||||
url: 'https://keys.openpgp.org',
|
||||
protocol: 'vks'
|
||||
}, email, key.armoredKey, key.fingerprint);
|
||||
assert.equal(result.uploaded, true);
|
||||
assert.equal(result.verification, 'request-failed');
|
||||
assert.match(result.warning, /key was uploaded/);
|
||||
});
|
||||
|
||||
test('publication rejects a fingerprint that does not match the public key', async () => {
|
||||
const key = await makeKey();
|
||||
const service = createKeyServerService({
|
||||
async fetchImpl() { throw new Error('unexpected network request'); }
|
||||
});
|
||||
await assert.rejects(() => service.publish({
|
||||
id: 'mailvelope-hkp',
|
||||
name: 'keys.mailvelope.com',
|
||||
url: 'https://keys.mailvelope.com',
|
||||
protocol: 'hkp'
|
||||
}, email, key.armoredKey, '0'.repeat(40)), /does not match/);
|
||||
});
|
||||
@@ -43,52 +43,6 @@ test('export requires the right passphrase and round-trips through import', asyn
|
||||
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
||||
});
|
||||
|
||||
test('changes a key passphrase without changing its public identity or revocation certificate', async () => {
|
||||
const storage = memoryStore();
|
||||
const keys = createKeyStore(storage);
|
||||
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||
const original = JSON.parse(JSON.stringify((await storage.load()).keys[0]));
|
||||
const newPassphrase = 'new passphrase securely';
|
||||
|
||||
await assert.rejects(keys.changePassphrase(key.fingerprint, 'wrong passphrase', newPassphrase), /incorrect/);
|
||||
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'short'), /at least 8/);
|
||||
assert.deepEqual((await storage.load()).keys[0], original);
|
||||
|
||||
assert.deepEqual(await keys.changePassphrase(key.fingerprint, passphrase, newPassphrase), { changed: true });
|
||||
const changed = (await storage.load()).keys[0];
|
||||
assert.equal(changed.fingerprint, original.fingerprint);
|
||||
assert.equal(changed.publicKey, original.publicKey);
|
||||
assert.equal(changed.name, original.name);
|
||||
assert.equal(changed.email, original.email);
|
||||
assert.equal(changed.accountId, original.accountId);
|
||||
assert.equal(changed.createdAt, original.createdAt);
|
||||
assert.equal(changed.algorithm, original.algorithm);
|
||||
assert.equal(changed.revocationCertificate, original.revocationCertificate);
|
||||
assert.notEqual(changed.privateKey, original.privateKey);
|
||||
await assert.rejects(keys.exportPrivate(key.fingerprint, passphrase), /incorrect/);
|
||||
assert.equal(await keys.exportPrivate(key.fingerprint, newPassphrase), changed.privateKey);
|
||||
assert.equal(await keys.exportRevocation(key.fingerprint, newPassphrase), revocationCertificate);
|
||||
});
|
||||
|
||||
test('does not mutate the loaded key if saving a changed passphrase fails', async () => {
|
||||
let data = null;
|
||||
let failSave = false;
|
||||
const storage = {
|
||||
load: async () => data,
|
||||
save: async value => {
|
||||
if (failSave) throw new Error('Storage unavailable.');
|
||||
data = JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
const keys = createKeyStore(storage);
|
||||
const { key } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||
const original = JSON.parse(JSON.stringify(data.keys[0]));
|
||||
failSave = true;
|
||||
|
||||
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'new passphrase securely'), /Storage unavailable/);
|
||||
assert.deepEqual(data.keys[0], original);
|
||||
});
|
||||
|
||||
test('imports an unprotected key by encrypting it with the given passphrase', async () => {
|
||||
const { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
|
||||
const keys = createKeyStore(memoryStore());
|
||||
|
||||
@@ -166,15 +166,9 @@ test('keyring: contacts, trust levels, expired passphrase cache and settings', a
|
||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
|
||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
|
||||
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
|
||||
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [] });
|
||||
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
|
||||
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] });
|
||||
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10 });
|
||||
await alice.keyStore.setSettings({ cacheMinutes: 0 });
|
||||
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
|
||||
await alice.keyStore.setSettings({ cacheMinutes: 5 });
|
||||
assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]);
|
||||
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, ['custom', 'openpgp-vks']);
|
||||
await alice.keyStore.setSettings({ cacheMinutes: 5, enabledKeyServers: [] });
|
||||
assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, []);
|
||||
await alice.keyStore.removeContact(contact.fingerprint);
|
||||
assert.equal((await alice.keyStore.listContacts()).length, 0);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user