Compare commits

..
Author SHA1 Message Date
Your Nameandaider 5059dde07b feat: Add push-mail support using Firebase Cloud Messaging
Co-authored-by: aider (ollama_chat/qwen2.5-coder:14b) <aider@aider.chat>
2026-10-10 00:30:26 +03:00
Your Nameandaider 717a2760fa refactor: Update TODO.md with current status and remove completed tasks
Co-authored-by: aider (ollama_chat/qwen2.5-coder:14b) <aider@aider.chat>
2026-10-10 00:17:33 +03:00
40 changed files with 127 additions and 2825 deletions
-1
View File
@@ -1,4 +1,3 @@
node_modules/
release/
dist/
android/local.properties
-117
View File
@@ -1,117 +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. On Windows, its notification-area tray icon uses the packaged multi-resolution application icon and provides Open and Quit actions. Packaged startup repairs an existing per-user Start Menu shortcut to target the launched app and use its icon, keeping taskbar pins associated with the matching AppUserModelID.
- `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, while mail-protocol and cryptographic network work stays in the main process. The reader makes direct HTTPS image requests only after explicit per-message approval.
### 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 the desktop `mail:send` IPC or the Android `EpMail.send` plugin with message fields and selected attachment bytes
- the native send path resolves the account, checks sender settings, builds multipart MIME, and on desktop applies OpenPGP encryption/signing to the body and attachments before sending
- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable; local draft attachments are persisted with draft content
The renderer sends file bytes rather than local paths. OpenPGP messages are encrypted before offline queueing so the outbox contains ciphertext instead of plaintext message or attachment content.
## 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.
- Incoming HTML is sanitized in the renderer before insertion. HTTPS image URLs are kept in inert data attributes; only a per-message user action assigns image sources, and reopening the message resets that approval. HTTP images are rejected to preserve Android's cleartext-traffic protection. The CSP allows HTTPS images; scripts, frames, forms, and remote connections remain blocked.
- 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 native mail service and passed to the renderer as plain text, bounded HTML alternatives, links, and attachment metadata. HTML is allowlist-sanitized before display; HTTPS image requests remain inert until explicitly enabled for the current message view.
- 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 -19
View File
@@ -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
@@ -72,8 +72,6 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting.
- Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload.
- Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key.
- Multiple outgoing attachments are included in the OpenPGP MIME payload and encrypted/signed together with the body. Android does not yet implement OpenPGP.
- Attachment selection has no app-enforced aggregate size cap; local storage capacity and mail-provider limits still apply.
- A signature from a key that differs from the one on file for the sender is flagged as a changed key.
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
- Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP).
@@ -85,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.
+2 -6
View File
@@ -4,14 +4,10 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E
## Desktop app
The Electron app runs in its own window. On Windows, ep-mail also shows its icon in the notification area beside the clock; click it to open the app, or right-click for Open and Quit. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser. On desktop and Android, incoming HTML is sanitized before display; external HTTPS images stay blocked until you explicitly load them for that message. Loading remote images can disclose your network address and message-open timing to their hosts. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. Windows builds use the app icon for the executable, window, and shortcuts. If Windows continues showing an old icon for an existing taskbar pin, unpin ep-mail, install or launch the updated build, then pin it again from the updated shortcut. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
The Electron app runs in its own window. With Node.js installed, run `npm install` and then `npm start`. Open **Mail account settings** to connect an IMAP/SMTP account. Each account can have its own outgoing signature, new-mail notification toggle, periodic sync interval (2–60 minutes; IDLE remains event-driven), and mail rules. Rules match incoming Inbox messages by sender and/or subject; the first matching rule archives, moves to Inbox/Archive/Trash, applies a label, or flags the message. Sender/domain and extracted message-link checks highlight selected phishing warning signs. Message links are shown separately from the body and require explicit confirmation before opening in a browser; the app never renders remote message HTML. Settings, cached recent messages, offline drafts, and queued mail operations are stored with the encrypted account credentials. Search supports text, sender, subject, date range, attachment, and folder filters; a filtered online search scans up to the newest 5,000 messages in the selected folder. When offline, the app can read cached messages, save drafts, and queue supported message actions and sends for retry on the next successful sync. The app uses required STARTTLS for IMAP port 143 and SMTP port 587. Before preparing a new release, bump the version once with `npm run bump:build`; then build all platform targets for that same version. To package it on Windows, run `npm run dist:win`; the installer and portable `.exe` are written to `release/`. To package on Linux, run `npm install` and `npm run dist:linux` on a Linux machine; this produces AppImage and Debian packages in `release/`.
The `.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.
On packaged Windows builds, startup repairs an existing per-user Start Menu shortcut to point to the launched installed or portable executable and use its icon and AppUserModelID. Windows may keep a cached icon for an existing taskbar pin; if so, unpin and pin ep-mail again after launching the updated build.
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:
@@ -35,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. Compose can attach multiple files of any type; attachments are retained in local drafts and sent with the message. There is no app-enforced total-size cap, though local storage and mail providers may impose limits. Desktop encrypts and signs attachments together with the body when OpenPGP is selected. 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`.
-15
View File
@@ -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 -50
View File
@@ -2,73 +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] Fix the ep-mail logo not appearing in the Windows taskbar.
- [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.
- [x] Block remote images by default and let users load them per message on desktop and Android/Web.
- [ ] 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.
- [x] Add the ability to attach multiple files to outgoing mails on desktop and Android/Web, persist them in local drafts, and include them within desktop OpenPGP protection.
- [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
View File
@@ -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
}
+11 -30
View File
@@ -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,42 +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 android.util.Base64
import javax.activation.DataHandler
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.util.ByteArrayDataSource
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)
@@ -48,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 {
@@ -158,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)
@@ -181,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")
@@ -221,192 +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)
val fullBody = if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature"
val attachments = input.optJSONArray("attachments") ?: JSONArray()
if (attachments.length() == 0) {
message.setText(fullBody, "UTF-8")
} else {
val multipart = MimeMultipart("mixed")
multipart.addBodyPart(MimeBodyPart().apply { setText(fullBody, "UTF-8") })
for (index in 0 until attachments.length()) {
val file = attachments.optJSONObject(index)
?: throw IllegalArgumentException("An attachment could not be read.")
val encoded = file.optString("contentBase64")
require(encoded.length % 4 == 0 && encoded.matches(Regex("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"))) {
"The contents of an attachment are invalid."
}
val filename = file.optString("filename", "attachment")
.replace(Regex("[\\\\/\\r\\n\\u0000]"), "")
.take(255)
.ifBlank { "attachment" }
val contentType = file.optString("contentType", "application/octet-stream")
.lowercase(Locale.ROOT)
require(contentType.matches(Regex("^[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+$"))) {
"The content type for $filename is invalid."
}
val part = MimeBodyPart()
part.dataHandler = DataHandler(ByteArrayDataSource(Base64.decode(encoded, Base64.DEFAULT), contentType))
part.fileName = MimeUtility.encodeText(filename, "UTF-8", null)
part.disposition = javax.mail.Part.ATTACHMENT
multipart.addBodyPart(part)
}
message.setContent(multipart)
}
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 {
@@ -419,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"),
@@ -576,188 +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 htmlBodies = ArrayList<String>()
val attachments = JSONArray()
val links = linkedSetOf<String>()
collectParts(message, body, htmlBodies, 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("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
.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>,
htmlBodies: 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")) {
if (htmlBodies.isEmpty()) htmlBodies.add(content.take(100000))
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("&amp;", "&") }
.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, htmlBodies, attachments, links)
}
is javax.mail.BodyPart -> collectParts(content, body, htmlBodies, 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)) {
@@ -769,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 {
@@ -793,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()
}
}
@@ -331,7 +331,6 @@ class EpMailPlugin : Plugin() {
.put("cc", input.optString("cc").take(4000))
.put("subject", input.optString("subject").take(998))
.put("text", input.optString("text").take(500000))
.put("attachments", input.optJSONArray("attachments") ?: JSONArray())
.put("updatedAt", System.currentTimeMillis())
AndroidAccountVault.saveDraft(account.optString("id"), draft)
call.resolve(draft.toJSObject())
@@ -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.
}
}
+4 -9
View File
@@ -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()
+1 -68
View File
@@ -4,75 +4,8 @@ const contacts=[];
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
function safeRemoteImageUrl(value){if(typeof value!=='string'||value.length>2048)return null;try{const url=new URL(value);return url.protocol==='https:'&&url.hostname&&!url.username&&!url.password?url.href:null}catch{return null}}
function sanitizeMailHtml(value){
const html=String(value||'').slice(0,100000);
const inertImages=html
.replace(/<(script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track)\b[\s\S]*?<\/\1\s*>/gi,'')
.replace(/<(?:script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track|link|base|meta)\b[^>]*>/gi,'')
.replace(/<!--[\s\S]*?-->/g,'')
.replace(/<img\b[^>]*>/gi,tag=>{
const source=tag.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const alt=tag.match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const remote=source&&(source[1]||source[2]||source[3]||'').trim();
const alternative=alt&&(alt[1]||alt[2]||alt[3]||'');
return `<img${remote?` data-remote-src="${esc(remote)}"`:''}${alternative?` alt="${esc(alternative)}"`:''}>`;
})
.replace(/\s(?:src|srcset|background|poster|action|formaction|href|xlink:href|srcdoc|dynsrc|lowsrc|style)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,'');
const document=new DOMParser().parseFromString(inertImages,'text/html');
const allowed=new Set(['a','p','div','span','br','hr','h1','h2','h3','h4','h5','h6','b','strong','i','em','u','s','del','blockquote','pre','code','ul','ol','li','table','thead','tbody','tfoot','tr','th','td','img']);
const discard=new Set(['script','style','iframe','frame','object','embed','svg','math','form','input','button','textarea','select','option','link','base','meta','video','audio','source','picture','track']);
let remoteImageCount=0;
const clean=parent=>{
for(const node of [...parent.childNodes]){
if(node.nodeType!==Node.ELEMENT_NODE){if(node.nodeType!==Node.TEXT_NODE)node.remove();continue}
const name=node.localName.toLowerCase();
if(discard.has(name)){node.remove();continue}
if(!allowed.has(name)){node.replaceWith(...node.childNodes);continue}
for(const attribute of [...node.attributes]){
const key=attribute.name.toLowerCase();
const keep=(name==='img'&&(key==='alt'||key==='data-remote-src'))||
(name==='td'||name==='th')&&['colspan','rowspan'].includes(key)&&/^\d{1,2}$/.test(attribute.value);
if(!keep)node.removeAttribute(attribute.name);
}
if(name==='img'){
const url=safeRemoteImageUrl(node.getAttribute('data-remote-src'));
if(url){node.setAttribute('data-remote-src',url);remoteImageCount+=1}
else node.removeAttribute('data-remote-src');
}
clean(node);
}
};
clean(document.body);
return {html:document.body.innerHTML,remoteImageCount};
}
function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
function openMessage(id){
activeMessage=id;
const m=messages.find(x=>x.id===id);
if(!m)return;
m.unread=false;
renderList();
let safeHtml={html:'',remoteImageCount:0};
if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)}
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;
$('#load-remote-images')?.addEventListener('click',()=>{
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
image.removeAttribute('data-remote-src');
if(url)image.src=url;
});
$('.remote-image-notice')?.remove();
});
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
$('#reply').onclick=()=>showCompose(m);
$('#forward').onclick=()=>showCompose(m,true);
}
function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div><div class="reader-body">${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('')}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)}
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send&nbsp; ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
-30
View File
@@ -1,30 +0,0 @@
const path = require('node:path');
function normalizeOutgoingAttachments(value) {
if (value === undefined) return [];
if (!Array.isArray(value)) throw new Error('The attachment list is invalid.');
return value.map(file => {
if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') {
throw new Error('An attachment could not be read.');
}
const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/'))
.replace(/[\r\n\0]/g, '')
.slice(0, 255) || 'attachment';
const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase();
if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) {
throw new Error(`The content type for ${filename} is invalid.`);
}
const encoded = file.contentBase64;
if (encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) {
throw new Error(`The contents of ${filename} are invalid.`);
}
const content = Buffer.from(encoded, 'base64');
return { filename, contentType, contentBase64: encoded, size: content.length, content };
});
}
function serializeOutgoingAttachments(attachments) {
return attachments.map(({ content, ...file }) => file);
}
module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments };
+8 -255
View File
@@ -1,5 +1,4 @@
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron');
const fsSync = require('node:fs');
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor } = require('electron');
const path = require('node:path');
const fs = require('node:fs/promises');
const { ImapFlow } = require('imapflow');
@@ -8,9 +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 { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
@@ -19,7 +15,6 @@ const backgroundRetryIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2;
const backgroundIdleConcurrency = 2;
const snoozeCheckIntervalMs = 30 * 1000;
const windowsAppUserModelId = 'studio.daybreak.mail';
let accountStoreQueue = Promise.resolve();
let backgroundSyncInProgress = false;
let backgroundSyncRequested = false;
@@ -29,8 +24,6 @@ const backgroundSyncFailures = new Map();
const flagSnapshots = new Map();
const idleWatchers = new Map();
const lastBackgroundSyncAt = new Map();
let windowsAppIcon = null;
let tray = null;
function updateAccountStore(update) {
const operation = accountStoreQueue.then(async () => {
@@ -207,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) {
@@ -216,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 });
@@ -226,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);
@@ -241,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 });
@@ -352,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);
@@ -383,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.');
}
@@ -615,7 +592,6 @@ async function toUiMessage(item, folder) {
deleted: folder === 'Trash',
sourceFolder: folder,
body,
html: content.html,
links,
uid: Number(item.uid),
attachments: content.attachments,
@@ -636,7 +612,6 @@ function mailContent(parsed) {
return {
bodyText,
body,
html: html.slice(0, 100000),
links,
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: files[0]?.filename || null,
@@ -1034,7 +1009,6 @@ ipcMain.handle('mail:save-draft', async (_event, input) => {
cc: String(input?.cc || '').slice(0, 4000),
subject: String(input?.subject || '').slice(0, 998),
text: String(input?.text || '').slice(0, 500000),
attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)),
updatedAt: Date.now()
};
await updateAccountStore(store => {
@@ -1327,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));
@@ -1384,7 +1352,6 @@ ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
return {
ok: true,
body: content.body,
html: content.html,
links: content.links,
attachments: content.attachments,
attachment: content.attachment,
@@ -1414,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);
@@ -1474,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) => {
@@ -1603,7 +1451,6 @@ ipcMain.handle('mail:sync-inbox', async () => {
async function sendMailNow(account, message) {
const to = String(message?.to || '').trim();
if (!to) throw new Error('Add at least one recipient.');
const attachments = normalizeOutgoingAttachments(message?.attachments);
const transport = smtpTransport(account);
const sentMessageId = String(message.messageId || `<${require('node:crypto').randomUUID()}@ep-mail.local>`);
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
@@ -1615,12 +1462,7 @@ async function sendMailNow(account, message) {
cc: String(message.cc || '').trim() || undefined,
subject: String(message.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: sentMessageId,
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
messageId: sentMessageId
};
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
try {
@@ -1654,31 +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>` };
const attachments = normalizeOutgoingAttachments(message?.attachments);
queuedMessage.attachments = serializeOutgoingAttachments(attachments);
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);
@@ -1694,13 +1517,11 @@ ipcMain.handle('mail:send', async (event, message) => {
messageId: queuedMessage.messageId,
encrypt: Boolean(pgpOptions.encrypt),
sign: Boolean(pgpOptions.sign),
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null,
attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }))
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null
});
queuedMessage.rawBase64 = built.raw.toString('base64');
queuedMessage.envelope = built.envelope;
queuedMessage.text = '';
queuedMessage.attachments = [];
} catch (error) {
if (error instanceof PgpError) return pgpFailure(error);
throw error;
@@ -1897,7 +1718,7 @@ function createWindow() {
backgroundColor: '#f4f5f1',
show: false,
autoHideMenuBar: true,
icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
icon: path.join(__dirname, '..', 'icon.svg'),
webPreferences: {
preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true,
@@ -1915,78 +1736,10 @@ function createWindow() {
window.webContents.on('will-navigate', (event, url) => {
if (!url.startsWith('file:')) event.preventDefault();
});
return window;
}
function showMainWindow() {
let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed());
if (!window) {
window = createWindow();
} else {
if (window.isMinimized()) window.restore();
window.show();
window.focus();
}
}
function createWindowsTray() {
tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 }));
tray.setToolTip('ep-mail');
tray.setContextMenu(Menu.buildFromTemplate([
{ label: 'Open ep-mail', click: showMainWindow },
{ type: 'separator' },
{ label: 'Quit ep-mail', click: () => app.quit() }
]));
tray.on('click', showMainWindow);
tray.on('double-click', showMainWindow);
}
function repairWindowsStartMenuShortcut() {
if (!app.isPackaged) return;
const shortcutPath = path.join(
app.getPath('appData'),
'Microsoft',
'Windows',
'Start Menu',
'Programs',
'ep-mail.lnk'
);
if (!fsSync.existsSync(shortcutPath)) return;
try {
const shortcut = shell.readShortcutLink(shortcutPath);
const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe'
|| shortcut.appUserModelId === windowsAppUserModelId;
if (!isEpMailShortcut) return;
if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return;
const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE;
const executable = portableExecutable && fsSync.existsSync(portableExecutable)
? portableExecutable
: process.execPath;
const updated = shell.writeShortcutLink(shortcutPath, 'update', {
...shortcut,
target: executable,
cwd: path.dirname(executable),
icon: executable,
iconIndex: 0,
appUserModelId: windowsAppUserModelId
});
if (!updated) throw new Error('Windows did not update the shortcut.');
} catch (error) {
console.error('Could not repair the ep-mail Start Menu shortcut:', error);
}
}
app.whenReady().then(() => {
app.setAppUserModelId(windowsAppUserModelId);
if (process.platform === 'win32') {
windowsAppIcon = nativeImage.createFromPath(path.join(__dirname, '..', 'icon.ico'));
if (windowsAppIcon.isEmpty()) throw new Error('Could not load the Windows application icon.');
repairWindowsStartMenuShortcut();
createWindowsTray();
}
app.setAppUserModelId('studio.daybreak.mail');
createWindow();
const syncTimer = setInterval(() => {
void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error));
-277
View File
@@ -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
};
+4 -49
View File
@@ -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.');
+3 -18
View File
@@ -1,7 +1,6 @@
const openpgp = require('openpgp');
const { simpleParser } = require('mailparser');
const addressParser = require('nodemailer/lib/addressparser');
const MailComposer = require('nodemailer/lib/mail-composer');
const { randomBytes } = require('node:crypto');
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
@@ -132,21 +131,7 @@ function parseAddresses(value) {
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
}
async function innerEntity(text, attachments) {
if (attachments.length) {
return new Promise((resolve, reject) => {
new MailComposer({
text: String(text || ''),
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
}).compile().build((error, message) => error
? reject(error)
: resolve(Buffer.from(message.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1')));
});
}
function innerEntity(text) {
const body = Buffer.from(String(text || ''), 'utf8');
return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1');
}
@@ -267,7 +252,7 @@ function createPgpMail({ keyStore, cache }) {
},
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) {
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint }) {
const toList = parseAddresses(to);
const ccList = parseAddresses(cc);
if (!toList.length) throw new Error('Add at least one recipient.');
@@ -299,7 +284,7 @@ function createPgpMail({ keyStore, cache }) {
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
'MIME-Version: 1.0'
];
const inner = await innerEntity(text, attachments);
const inner = innerEntity(text);
const mark = boundary();
let body;
let contentType;
+1 -8
View File
@@ -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),
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 KiB

+1 -1
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4f5f1">
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'none'">
<title>ep-mail</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="styles.css">
+2 -81
View File
@@ -398,83 +398,6 @@ function setupDraftComposer() {
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
let attachments = Array.isArray(draft?.attachments) ? draft.attachments : [];
modal._composeAttachments = attachments;
const fields = modal.querySelector('.compose-fields');
const attachmentRow = document.createElement('div');
attachmentRow.className = 'compose-line';
const attachmentLabel = document.createElement('span');
attachmentLabel.textContent = 'Attachments';
const attachmentControls = document.createElement('div');
attachmentControls.className = 'compose-attachments';
const attachmentInput = document.createElement('input');
attachmentInput.type = 'file';
attachmentInput.multiple = true;
attachmentInput.accept = '*/*';
attachmentInput.hidden = true;
attachmentInput.setAttribute('aria-label', 'Choose files to attach');
const attachButton = document.createElement('button');
attachButton.type = 'button';
attachButton.className = 'discard';
attachButton.textContent = 'Attach files…';
const attachmentList = document.createElement('div');
attachmentList.className = 'attachment-list';
attachmentList.setAttribute('aria-live', 'polite');
attachmentControls.append(attachButton, attachmentInput);
attachmentRow.append(attachmentLabel, attachmentControls);
fields.append(attachmentRow, attachmentList);
attachButton.onclick = () => attachmentInput.click();
const renderAttachments = () => {
attachmentList.replaceChildren();
attachments.forEach((file, index) => {
const row = document.createElement('div');
row.className = 'attachment-row';
const name = document.createElement('strong');
name.textContent = file.filename;
const size = document.createElement('small');
size.textContent = `${((file.size || 0) / 1048576).toFixed(2)} MB`;
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'discard';
remove.textContent = 'Remove';
remove.setAttribute('aria-label', `Remove ${file.filename}`);
remove.onclick = () => {
attachments.splice(index, 1);
renderAttachments();
void persist().catch(error => toast(error.message || 'Could not save the draft'));
};
row.append(name, size, remove);
attachmentList.append(row);
});
};
attachmentInput.onchange = async () => {
attachButton.disabled = true;
try {
const selected = [];
for (const file of attachmentInput.files) {
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = '';
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
}
selected.push({
filename: file.name,
contentType: file.type || 'application/octet-stream',
size: file.size,
contentBase64: btoa(binary)
});
}
attachments.push(...selected);
renderAttachments();
await persist();
} catch (error) {
toast(error.message || 'Could not add the selected files');
} finally {
attachmentInput.value = '';
attachButton.disabled = false;
}
};
renderAttachments();
if (draft) {
$('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || '';
@@ -497,10 +420,9 @@ function setupDraftComposer() {
to: $('#compose-to').value,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value,
text: $('#compose-body').value,
attachments
text: $('#compose-body').value
};
if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return;
modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id;
@@ -746,7 +668,6 @@ if (window.daybreakMail) {
cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value,
attachments: $('#modal-root .compose-modal')?._composeAttachments || [],
displayName: connectedMailAccount.displayName || profileSettings.name,
...(pgp ? { pgp } : {})
});
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
"version": "0.4.4",
"version": "0.3.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
"version": "0.4.4",
"version": "0.3.6",
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
+2 -9
View File
@@ -1,13 +1,9 @@
{
"name": "ep-mail",
"version": "0.4.4",
"version": "0.3.6",
"private": true,
"description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
"author": {
"name": "Eternity Project",
"email": "tero.huttunen@eternityproject.fi"
},
"author": "Eternity Project",
"desktopName": "ep-mail",
"main": "desktop/main.cjs",
"scripts": {
@@ -52,7 +48,6 @@
"pgp-ui.js",
"pgp-mail-ui.js",
"icon.svg",
"icon.ico",
"logo-ep-daylight.svg",
"logo-ep-wasteland.svg",
"manifest.webmanifest",
@@ -64,7 +59,6 @@
"output": "release"
},
"win": {
"icon": "icon.ico",
"target": [
"nsis",
"portable"
@@ -83,7 +77,6 @@
"AppImage",
"deb"
],
"maintainer": "Tero Huttunen <tero.huttunen@eternityproject.fi>",
"synopsis": "A calmer place for mail, people, and plans"
}
},
+1 -1
View File
@@ -92,7 +92,7 @@ async function pgpUnlockMessage(message, interactive) {
}
if (result.ok) {
Object.assign(message, {
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
});
if (activeMessage === message.id) openMessage(message.id);
-226
View File
@@ -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 -1
View File
@@ -1,4 +1,4 @@
const CACHE='ep-mail-v8';
const CACHE='ep-mail-v7';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
-1
View File
@@ -138,6 +138,5 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.pgp-trust{margin-left:8px}
.draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)}
.reader-body img{display:block;max-width:100%;height:auto;margin:12px 0;border-radius:6px}.reader-body table{max-width:100%;border-collapse:collapse}.reader-body th,.reader-body td{border:1px solid var(--line);padding:5px}.remote-image-notice{margin:14px 0 0;padding:12px;border:1px solid #d7a85c;border-radius:8px;background:#fff8e9;color:#664a23;font-size:10px;line-height:1.5}.remote-image-notice p{margin:0 0 8px}.remote-image-notice .reply-button{background:transparent;color:inherit;border-color:#d7a85c}body.ep-wasteland .remote-image-notice{background:#3a3022;color:#e6d1a8;border-color:#806b44}body.ep-daylight .remote-image-notice{background:#fff8e9;color:#664a23;border-color:#d7a85c}
.sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0}
-38
View File
@@ -1,38 +0,0 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('../desktop/mail-attachments.cjs');
test('normalizes attachment metadata and round-trips bytes through serialized drafts and sends', () => {
const bytes = Buffer.from([0, 1, 2, 127, 128, 255]);
const [file] = normalizeOutgoingAttachments([{
filename: 'folder\\report.bin',
contentType: 'APPLICATION/OCTET-STREAM',
size: 999,
contentBase64: bytes.toString('base64')
}]);
assert.equal(file.filename, 'report.bin');
assert.equal(file.contentType, 'application/octet-stream');
assert.equal(file.size, bytes.length);
assert.deepEqual(file.content, bytes);
const [serialized] = serializeOutgoingAttachments([file]);
assert.equal(serialized.contentBase64, bytes.toString('base64'));
assert.equal('content' in serialized, false);
});
test('rejects malformed attachment data and unsafe content types', () => {
assert.throws(() => normalizeOutgoingAttachments({}), /attachment list is invalid/);
assert.throws(() => normalizeOutgoingAttachments([{ filename: 'x', contentBase64: '***=' }]), /contents.*invalid/);
assert.throws(() => normalizeOutgoingAttachments([{
filename: 'x',
contentType: 'text/plain\r\nBcc: bad@example.com',
contentBase64: ''
}]), /content type.*invalid/);
});
test('uses fallback names and MIME types for empty metadata', () => {
const [file] = normalizeOutgoingAttachments([{ contentBase64: '' }]);
assert.equal(file.filename, 'attachment');
assert.equal(file.contentType, 'application/octet-stream');
assert.equal(file.size, 0);
});
-244
View File
@@ -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/);
});
-46
View File
@@ -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());
+3 -38
View File
@@ -75,29 +75,6 @@ test('encrypts to several recipients and each can decrypt', async () => {
}
});
test('encrypts and signs outgoing attachments with the message body', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await exchange(alice, bob);
const contents = Buffer.from([0, 1, 2, 127, 128, 255]);
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
encrypt: true,
sign: true,
passphrase: alice.passphrase,
attachments: [{ filename: 'binary-data.bin', contentType: 'application/octet-stream', content: contents }]
}));
assert.ok(!raw.toString('latin1').includes(contents.toString('latin1')));
const parsed = await simpleParser(raw);
const decrypted = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
assert.equal(decrypted.parsed.text.trim(), 'Top secret ✓\nline two');
assert.equal(decrypted.parsed.attachments.length, 1);
assert.equal(decrypted.parsed.attachments[0].filename, 'binary-data.bin');
assert.equal(decrypted.parsed.attachments[0].contentType, 'application/octet-stream');
assert.deepEqual(decrypted.parsed.attachments[0].content, contents);
assert.equal(decrypted.signatures[0].status, 'valid');
});
test('detects tampered and corrupted encrypted messages', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
@@ -135,16 +112,10 @@ test('signs without encrypting and verifies PGP/MIME signatures', async () => {
const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com');
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
const attachment = Buffer.from('signed attachment data');
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', {
sign: true,
passphrase: alice.passphrase,
attachments: [{ filename: 'signed.txt', contentType: 'text/plain', content: attachment }]
}));
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { sign: true, passphrase: alice.passphrase }));
const parsed = await simpleParser(raw);
assert.equal(detect(parsed), 'signed-mime');
assert.match(parsed.text, /Top secret/);
assert.deepEqual(parsed.attachments[0].content, attachment);
const [signature] = await bob.mail.verifySigned(parsed, raw);
assert.equal(signature.status, 'valid');
const altered = Buffer.from(raw.toString('latin1').replace('Content-Type: text/plain', 'Content-Type: text/plain'), 'latin1');
@@ -195,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);
+1 -68
View File
@@ -4,75 +4,8 @@ const contacts=[];
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)];
function esc(x){return String(x).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]))}
function safeRemoteImageUrl(value){if(typeof value!=='string'||value.length>2048)return null;try{const url=new URL(value);return url.protocol==='https:'&&url.hostname&&!url.username&&!url.password?url.href:null}catch{return null}}
function sanitizeMailHtml(value){
const html=String(value||'').slice(0,100000);
const inertImages=html
.replace(/<(script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track)\b[\s\S]*?<\/\1\s*>/gi,'')
.replace(/<(?:script|style|iframe|frame|object|embed|svg|math|form|noscript|template|video|audio|source|picture|track|link|base|meta)\b[^>]*>/gi,'')
.replace(/<!--[\s\S]*?-->/g,'')
.replace(/<img\b[^>]*>/gi,tag=>{
const source=tag.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const alt=tag.match(/\balt\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s/>]+))/i);
const remote=source&&(source[1]||source[2]||source[3]||'').trim();
const alternative=alt&&(alt[1]||alt[2]||alt[3]||'');
return `<img${remote?` data-remote-src="${esc(remote)}"`:''}${alternative?` alt="${esc(alternative)}"`:''}>`;
})
.replace(/\s(?:src|srcset|background|poster|action|formaction|href|xlink:href|srcdoc|dynsrc|lowsrc|style)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,'');
const document=new DOMParser().parseFromString(inertImages,'text/html');
const allowed=new Set(['a','p','div','span','br','hr','h1','h2','h3','h4','h5','h6','b','strong','i','em','u','s','del','blockquote','pre','code','ul','ol','li','table','thead','tbody','tfoot','tr','th','td','img']);
const discard=new Set(['script','style','iframe','frame','object','embed','svg','math','form','input','button','textarea','select','option','link','base','meta','video','audio','source','picture','track']);
let remoteImageCount=0;
const clean=parent=>{
for(const node of [...parent.childNodes]){
if(node.nodeType!==Node.ELEMENT_NODE){if(node.nodeType!==Node.TEXT_NODE)node.remove();continue}
const name=node.localName.toLowerCase();
if(discard.has(name)){node.remove();continue}
if(!allowed.has(name)){node.replaceWith(...node.childNodes);continue}
for(const attribute of [...node.attributes]){
const key=attribute.name.toLowerCase();
const keep=(name==='img'&&(key==='alt'||key==='data-remote-src'))||
(name==='td'||name==='th')&&['colspan','rowspan'].includes(key)&&/^\d{1,2}$/.test(attribute.value);
if(!keep)node.removeAttribute(attribute.name);
}
if(name==='img'){
const url=safeRemoteImageUrl(node.getAttribute('data-remote-src'));
if(url){node.setAttribute('data-remote-src',url);remoteImageCount+=1}
else node.removeAttribute('data-remote-src');
}
clean(node);
}
};
clean(document.body);
return {html:document.body.innerHTML,remoteImageCount};
}
function renderList(){let rows=messages.filter(m=>{if(activeFolder==='Starred'&&!m.star)return false;if(activeFolder==='Inbox'&&m.archived)return false;if(activeFolder==='Archive'&&!m.archived)return false;if(activeFolder==='Trash'&&!m.deleted)return false;if(activeFolder==='Sent'&&!m.sent)return false;if(activeFolder==='Drafts')return false;if(activeFolder==='Snoozed')return false;if(m.deleted&&activeFolder!=='Trash')return false;return !query||`${m.sender} ${m.email} ${m.subject} ${m.snippet}`.toLowerCase().includes(query.toLowerCase())});$('#message-list').innerHTML=rows.length?rows.map(m=>`<div class="message ${m.unread?'unread':''} ${m.id===activeMessage?'selected':''}" data-id="${m.id}"><input class="row-check" type="checkbox" aria-label="Select message" ${selectedIds.has(m.id)?'checked':''}><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="message-body"><div class="sender">${esc(m.sender)}</div><div class="subject">${esc(m.subject)}</div><div class="snippet">${esc(m.snippet)}</div></div><div class="message-meta"><span class="time">${esc(m.time)}</span><button class="star ${m.star?'on':''}" aria-label="${m.star?'Unstar':'Star'}">${m.star?'★':'☆'}</button></div></div>`).join(''):`<div class="reader-empty"><div><div class="empty-icon">⌕</div><h3>No messages here</h3><p>Try another folder or search.</p></div></div>`;$$('.message').forEach(row=>{row.addEventListener('click',e=>{if(e.target.closest('.row-check')){const id=+row.dataset.id;selectedIds.has(id)?selectedIds.delete(id):selectedIds.add(id);return}if(e.target.closest('.star')){const m=messages.find(x=>x.id===+row.dataset.id);m.star=!m.star;renderList();return}openMessage(+row.dataset.id)});});if(!rows.length)$('#reader-pane').innerHTML=emptyReader()}
function openMessage(id){
activeMessage=id;
const m=messages.find(x=>x.id===id);
if(!m)return;
m.unread=false;
renderList();
let safeHtml={html:'',remoteImageCount:0};
if(m.html)try{safeHtml=sanitizeMailHtml(m.html)}catch(error){console.error('Could not sanitize message HTML; showing plain text instead.',error)}
const body=safeHtml.html?safeHtml.html:`${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>`;
const imageNotice=safeHtml.remoteImageCount?`<section class="remote-image-notice" role="status"><p>This message contains ${safeHtml.remoteImageCount} remote image${safeHtml.remoteImageCount===1?'':'s'}. Loading them can reveal your network address and that you opened this message to the image host.</p><button type="button" class="reply-button" id="load-remote-images">Load images for this message</button></section>`:'';
const attachments=(m.attachments?.length?m.attachments:m.attachment?[{filename:m.attachment,size:m.size}]:[]).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size?(typeof file.size==='string'?esc(file.size):`${(file.size/1048576).toFixed(1)} MB`):'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('');
$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div>${imageNotice}<div class="reader-body">${body}${attachments}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;
$('#load-remote-images')?.addEventListener('click',()=>{
$('#reader-pane').querySelectorAll('.reader-body img[data-remote-src]').forEach(image=>{
const url=safeRemoteImageUrl(image.getAttribute('data-remote-src'));
image.removeAttribute('data-remote-src');
if(url)image.src=url;
});
$('.remote-image-notice')?.remove();
});
$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};
$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};
$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};
$('#reply').onclick=()=>showCompose(m);
$('#forward').onclick=()=>showCompose(m,true);
}
function openMessage(id){activeMessage=id;const m=messages.find(x=>x.id===id);if(!m)return;m.unread=false;renderList();$('#reader-pane').innerHTML=`<div class="reader-header"><div class="reader-topline"><div class="reader-tags">${m.tags.map((t,i)=>`<span class="tag ${i?'green':''}">${esc(t)}</span>`).join('')}</div><div class="reader-tools"><button class="icon-button" id="reader-archive" title="Archive">▱</button><button class="icon-button" id="reader-delete" title="Delete">⌫</button><button class="icon-button" title="More">···</button></div></div><h2 class="reader-subject">${esc(m.subject)}</h2><div class="sender-row"><div class="contact-avatar" style="background:${m.color}">${m.initials}</div><div class="sender-details"><strong>${esc(m.sender)}</strong><span>${esc(m.email)} · to me</span></div><span class="message-date">${esc(m.date)}</span><button class="icon-button" title="Star" id="reader-star">${m.star?'★':'☆'}</button></div></div><div class="reader-body">${m.body.map(p=>`<p>${esc(p)}</p>`).join('')}<p class="signoff">${esc(m.signature||m.sender)}</p>${(m.attachments?.length ? m.attachments : m.attachment ? [{filename:m.attachment,size:m.size}] : []).map(file=>`<div class="attachment"><div class="file-icon">${file.filename.toLowerCase().endsWith('.pdf')?'▤':'▧'}</div><div class="attachment-info"><strong title="${esc(file.filename)}">${esc(file.filename)}</strong><small>${file.size ? (typeof file.size==='string' ? esc(file.size) : `${(file.size/1048576).toFixed(1)} MB`) : 'Attachment'}</small></div><button class="download" data-filename="${esc(file.filename)}" title="Download ${esc(file.filename)}">↓</button></div>`).join('')}</div><div class="reply-bar"><button class="reply-button primary" id="reply">↶ &nbsp;Reply</button><button class="reply-button" id="forward">↗ &nbsp;Forward</button></div>`;$('#reader-archive').onclick=()=>{m.archived=true;toast('Moved to Archive');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-delete').onclick=()=>{m.deleted=true;toast('Moved to Trash');renderList();$('#reader-pane').innerHTML=emptyReader()};$('#reader-star').onclick=()=>{m.star=!m.star;renderList();openMessage(id)};$('#reply').onclick=()=>showCompose(m);$('#forward').onclick=()=>showCompose(m,true)}
function emptyReader(){return `<div class="reader-empty"><div><div class="empty-icon">✉</div><h3>Your inbox, at your pace</h3><p>Select a message to read it here.</p></div></div>`}
function toast(s){const el=$('#toast');el.textContent=s;el.classList.add('visible');clearTimeout(toastTimer);toastTimer=setTimeout(()=>el.classList.remove('visible'),2300)}
function showCompose(reply,forward=false){const root=$('#modal-root');root.innerHTML=`<div class="modal-overlay"><div class="compose-modal"><div class="modal-head"><span>${reply?(forward?'Forward message':'Reply to message'):'New message'}</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><label class="compose-line"><span>To</span><input id="compose-to" placeholder="name@example.com" value="${reply?esc(forward?'':reply.email):''}"></label><label class="compose-line"><span>Cc</span><input id="compose-cc" placeholder="Add Cc"></label><input id="compose-subject" class="compose-subject" placeholder="Subject" value="${reply?esc((forward?'Fwd: ':'Re: ')+reply.subject):''}"></div><textarea class="compose-body" id="compose-body" placeholder="Write something thoughtful…">${reply&&!forward?'\n\nOn '+reply.date+', '+reply.sender+' wrote:\n> '+reply.snippet:''}</textarea><div class="compose-footer"><button class="discard" id="discard">Discard</button><button class="send-button" id="send">Send&nbsp; ↗</button></div></div></div>`;const close=()=>root.innerHTML='';$('.modal-close').onclick=close;$('#discard').onclick=close;$('.modal-overlay').addEventListener('click',e=>{if(e.target.classList.contains('modal-overlay'))close()});$('#send').onclick=()=>{const to=$('#compose-to').value.trim();if(!to){$('#compose-to').focus();toast('Add a recipient to send your message');return}const subject=$('#compose-subject').value.trim()||'(no subject)';const body=$('#compose-body').value;messages.unshift({id:Date.now(),initials:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me').split(/\\s+/).map(x=>x[0]).join('').slice(0,2).toUpperCase(),color:'#dce9dd',sender:(profileSettings.name||connectedMailAccount?.email?.split('@')[0]||'Me'),email:(connectedMailAccount?.email||''),subject,snippet:body||'No message text',time:'Just now',date:'Today',unread:false,star:false,sent:true,tags:['Sent'],body:body.split('\n').filter(Boolean)});close();toast('Message sent');renderList()};$('#compose-to').focus()}
+1 -1
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4f5f1">
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux.">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'none'">
<title>ep-mail</title>
<link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="styles.css">
+2 -81
View File
@@ -398,83 +398,6 @@ function setupDraftComposer() {
const modal = root.querySelector('.compose-modal');
if (!modal) return;
modal.dataset.draftId = draft?.id || '';
let attachments = Array.isArray(draft?.attachments) ? draft.attachments : [];
modal._composeAttachments = attachments;
const fields = modal.querySelector('.compose-fields');
const attachmentRow = document.createElement('div');
attachmentRow.className = 'compose-line';
const attachmentLabel = document.createElement('span');
attachmentLabel.textContent = 'Attachments';
const attachmentControls = document.createElement('div');
attachmentControls.className = 'compose-attachments';
const attachmentInput = document.createElement('input');
attachmentInput.type = 'file';
attachmentInput.multiple = true;
attachmentInput.accept = '*/*';
attachmentInput.hidden = true;
attachmentInput.setAttribute('aria-label', 'Choose files to attach');
const attachButton = document.createElement('button');
attachButton.type = 'button';
attachButton.className = 'discard';
attachButton.textContent = 'Attach files…';
const attachmentList = document.createElement('div');
attachmentList.className = 'attachment-list';
attachmentList.setAttribute('aria-live', 'polite');
attachmentControls.append(attachButton, attachmentInput);
attachmentRow.append(attachmentLabel, attachmentControls);
fields.append(attachmentRow, attachmentList);
attachButton.onclick = () => attachmentInput.click();
const renderAttachments = () => {
attachmentList.replaceChildren();
attachments.forEach((file, index) => {
const row = document.createElement('div');
row.className = 'attachment-row';
const name = document.createElement('strong');
name.textContent = file.filename;
const size = document.createElement('small');
size.textContent = `${((file.size || 0) / 1048576).toFixed(2)} MB`;
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'discard';
remove.textContent = 'Remove';
remove.setAttribute('aria-label', `Remove ${file.filename}`);
remove.onclick = () => {
attachments.splice(index, 1);
renderAttachments();
void persist().catch(error => toast(error.message || 'Could not save the draft'));
};
row.append(name, size, remove);
attachmentList.append(row);
});
};
attachmentInput.onchange = async () => {
attachButton.disabled = true;
try {
const selected = [];
for (const file of attachmentInput.files) {
const bytes = new Uint8Array(await file.arrayBuffer());
let binary = '';
for (let offset = 0; offset < bytes.length; offset += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
}
selected.push({
filename: file.name,
contentType: file.type || 'application/octet-stream',
size: file.size,
contentBase64: btoa(binary)
});
}
attachments.push(...selected);
renderAttachments();
await persist();
} catch (error) {
toast(error.message || 'Could not add the selected files');
} finally {
attachmentInput.value = '';
attachButton.disabled = false;
}
};
renderAttachments();
if (draft) {
$('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || '';
@@ -497,10 +420,9 @@ function setupDraftComposer() {
to: $('#compose-to').value,
cc: $('#compose-cc').value,
subject: $('#compose-subject').value,
text: $('#compose-body').value,
attachments
text: $('#compose-body').value
};
if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return;
modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id;
@@ -746,7 +668,6 @@ if (window.daybreakMail) {
cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value,
attachments: $('#modal-root .compose-modal')?._composeAttachments || [],
displayName: connectedMailAccount.displayName || profileSettings.name,
...(pgp ? { pgp } : {})
});
+1 -1
View File
@@ -92,7 +92,7 @@ async function pgpUnlockMessage(message, interactive) {
}
if (result.ok) {
Object.assign(message, {
body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
});
if (activeMessage === message.id) openMessage(message.id);
-226
View File
@@ -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 -1
View File
@@ -1,4 +1,4 @@
const CACHE='ep-mail-v8';
const CACHE='ep-mail-v7';
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
-1
View File
@@ -138,6 +138,5 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.pgp-trust{margin-left:8px}
.draft-delete{margin-top:4px;font-size:15px;opacity:.55}.draft-delete:hover{opacity:1;color:#b3261e}.pgp-prompt-box{width:min(380px,92vw)}
.reader-body img{display:block;max-width:100%;height:auto;margin:12px 0;border-radius:6px}.reader-body table{max-width:100%;border-collapse:collapse}.reader-body th,.reader-body td{border:1px solid var(--line);padding:5px}.remote-image-notice{margin:14px 0 0;padding:12px;border:1px solid #d7a85c;border-radius:8px;background:#fff8e9;color:#664a23;font-size:10px;line-height:1.5}.remote-image-notice p{margin:0 0 8px}.remote-image-notice .reply-button{background:transparent;color:inherit;border-color:#d7a85c}body.ep-wasteland .remote-image-notice{background:#3a3022;color:#e6d1a8;border-color:#806b44}body.ep-daylight .remote-image-notice{background:#fff8e9;color:#664a23;border-color:#d7a85c}
.sidebar{overflow-y:auto}#mail-nav{overflow-y:auto;min-height:150px;flex:0 1 auto;scrollbar-width:thin;align-content:start}#custom-folders{display:contents}.folders-head{flex:none}.sidebar>:not(#mail-nav){flex-shrink:0}.folders-head+.folder-nav{margin-top:0}