Compare commits

...
16 Commits
Author SHA1 Message Date
thuttu e5391dbb62 Fix Linux packaging metadata and Android SDK setup 2026-10-10 23:43:46 +03:00
thuttuandCopilot 115e29640e Fix Windows taskbar shortcut icon
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 22:57:54 +03:00
thuttuandCopilot 2a23f4d40e Add Windows notification area icon
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 22:46:41 +03:00
thuttuandCopilot 959658c400 Fix Windows taskbar app icon
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 22:37:26 +03:00
thuttuandCopilot 2068e3f32b Block remote images by default
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 21:53:12 +03:00
thuttuandCopilot 5cd8d545e9 Add outgoing mail attachments
Support multiple attachments in desktop and Android compose, persist them in drafts and offline queues, and include them in desktop OpenPGP protection. Update docs and tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 21:05:32 +03:00
thuttuandCopilot acba5d641e Add OpenPGP key passphrase changes
Allow desktop users to re-encrypt an existing key after verifying its current passphrase. Preserve key identity and revocation data, clear its cached passphrase, and document the feature.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 20:44:44 +03:00
thuttuandCopilot f3e68b10bd Add configurable public key server usage
Persist per-server enablement, search enabled servers, and require an explicit publication target. Update documentation and tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 20:28:24 +03:00
thuttuandCopilot 04cd4117fe Add OpenPGP public key server support
- Add VKS and HTTPS HKP lookup and publication with bounded, validated requests.
- Add desktop key-server settings, lookup/import flow, and per-publication native confirmation.
- Keep discovered keys untrusted and update architecture, encryption, and user documentation.
- Add mocked server protocol and key-store tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 19:50:01 +03:00
thuttu a9c52e7868 Fix PGP security review items and add architecture docs
- Harden key replacement in the Electron main process with a confirmation dialog showing the old and new fingerprints before accepting a replacement.
- Enforce plaintext-send checks in the main process before allowing a message to be sent without encryption when recipient keys exist.
- Reject the insecure Linux safeStorage basic_text backend before writing mail credentials or OpenPGP keys.
- Update the security review findings to reflect the fixes and mark the related TODO item as complete.
- Add a project architecture overview and link it from the main README.
2026-10-10 19:34:25 +03:00
thuttu 20d58feb9c Update security review and todo 2026-10-10 19:23:01 +03:00
thuttu e34f3dc911 Review security and fix some security bugs add some features to TODO.md 2026-10-08 18:52:22 +03:00
thuttu 9adbce6a32 Fix draft mail deletion 2026-10-08 17:53:48 +03:00
thuttu 5769238a80 Move all imap folder to same area nad put slider to it 2026-10-07 23:03:12 +03:00
thuttu 17ca5f0fa7 FIX account mail filtering move to folder folders are hardcoded 2026-10-07 22:51:25 +03:00
thuttuandCopilot 592b83fc73 Fix folder creation dialog (no prompt in Electron) and add draft deletion
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-07 19:18:18 +03:00
36 changed files with 2275 additions and 81 deletions
+1
View File
@@ -1,3 +1,4 @@
node_modules/ node_modules/
release/ release/
dist/ dist/
android/local.properties
+117
View File
@@ -0,0 +1,117 @@
# 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.
+21 -5
View File
@@ -1,6 +1,6 @@
# Encryption plan: OpenPGP mail encryption for ep-mail # Encryption plan: OpenPGP mail encryption for ep-mail
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support, a manual Thunderbird check and an independent security review are still open; see [TODO.md](./TODO.md). Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support and an independent security review are still open; see [TODO.md](./TODO.md).
## 1. Format: OpenPGP with PGP/MIME (RFC 3156) ## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
@@ -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. - 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. - 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-----`). - Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
- Out of scope for v1: Autocrypt headers, key servers, Web Key Directory. - Out of scope for v1: Autocrypt headers and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
## 2. Key handling ## 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). - 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. - 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. - 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. - 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.
**Public keys** **Public keys**
- Per-account contact keyring: address, fingerprint, trust level, source. - Per-account contact keyring: address, fingerprint, trust level, source.
- Sources: file import, attached to received mail, own key attached to outgoing mail. - Sources: file import, attached to received mail, key-server lookup, and 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. - 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 ## 3. User experience
@@ -55,7 +55,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) | | 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
| 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) | | 3 | Send: public-key keyring and contact import, encrypt and sign on compose, encrypted Sent copy, downgrade warnings | Done (desktop) |
| 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open | | 4 | Trust and polish: fingerprint verification, key-change warnings, passphrase cache timeout, Android Keystore and biometric unlock | Desktop done; Android open |
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated and GnuPG interop tests done; Thunderbird check open | | 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
| 6 | Docs, security review, release | Docs and release done; independent review open | | 6 | Docs, security review, release | Docs and release done; independent review open |
## 6. Phase 1 implementation notes ## 6. Phase 1 implementation notes
@@ -72,6 +72,8 @@ 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. - [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. - 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. - 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. - 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). - 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). - Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP).
@@ -83,3 +85,17 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
- User confusion about trust; keep states simple: unknown, trusted, verified. - 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. - 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. - 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.
+6 -2
View File
@@ -4,10 +4,14 @@ An Eternity Project mail client with **Eternity Daylight**, **Wasteland**, and E
## Desktop app ## Desktop app
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 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 `.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. 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 ## 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: 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:
@@ -31,4 +35,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
## Current scope ## Current scope
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys, stored encrypted by the operating system; you can import 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`. 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`.
+58
View File
@@ -0,0 +1,58 @@
# Security review: OpenPGP encryption
Date: 2026-10-08
Version reviewed: 0.3.2 (working tree, uncommitted changes included)
Type: automated review by an AI security-review agent. It is not a substitute for a human review.
## Scope
- `desktop/pgp-keystore.cjs`: key store, `safeStorage` wrapping, contacts, trust
- `desktop/pgp-mail.cjs`: detect, decrypt, verify, build PGP/MIME, passphrase cache
- `pgp:*` IPC handlers in `desktop/main.cjs` and `desktop/preload.cjs`
- Renderer: `pgp-mail-ui.js`, `pgp-ui.js`, the `pgpPrepareSend` hook in `mail-ui.js`
- Design reference: [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)
Focus areas: secret leaks (disk, logs, outbox, renderer), IPC abuse by a compromised renderer, HTML injection from key user IDs and decrypted content, signature status spoofing, key matching by fingerprint, silent downgrade to plaintext, malformed or oversized input, passphrase cache lifetime.
## Findings
| # | Severity | File | Issue | Confidence | Status |
|---|----------|------|-------|------------|--------|
| 1 | 🟡 MEDIUM | `pgp-mail-ui.js`, `mail-ui.js` | Encrypt-by-default is applied after a 300 ms debounced key lookup. Sending before it finished skipped the key check and sent the message unencrypted. | 9/10 | Fixed |
| 2 | 🟡 MEDIUM | `desktop/preload.cjs`, `desktop/main.cjs`, `desktop/pgp-keystore.cjs` | A compromised renderer could add a public key for a recipient's address and call `pgp:set-trust` to mark it verified. Recipient key selection prefers higher trust, so later mail could be encrypted to the attacker's key. The confirmation existed only in the renderer UI. | 8/10 | Fixed |
No critical or high severity issues were reported.
## Fixes applied
1. **Send-time check:** `pgpPrepareSend` now checks recipient keys when you press Send. If keys exist for all recipients and you did not change the Encrypt box yourself, it asks before sending unencrypted. Unticking Encrypt on purpose still sends without a prompt.
2. **Trusted confirmation:** the `pgp:set-trust` handler in the main process shows a native dialog with the contact and fingerprint before raising trust. A cancelled dialog aborts the change. The renderer's own prompt may appear as well, so users can see two confirmations.
## Verification
- `npm test`: 20 passed, 0 failed (includes the GnuPG interoperability tests).
- `node --check` on the edited files.
- The fixes were not exercised in the running app.
## Remaining work
- Human review of the key store, the IPC boundary and the signature UI.
- Replacement-key confirmation in the main process when a new key arrives for an address that already has a contact. The review suggested it, and only the trust confirmation was added.
- 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.
+15 -3
View File
@@ -4,6 +4,7 @@
- [x] Rename the program to **ep-mail** across the app UI, package metadata, desktop builds, and documentation. - [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] 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. - [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. - [ ] 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. - [x] Show the app version after **ep-mail** in the window title.
@@ -21,7 +22,7 @@
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject. - [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 per-account signatures, notification preferences, and sync settings.
- [x] Add the ability to create IMAP folders from the app. - [x] Add the ability to create IMAP folders from the app.
- [ ] Block remote images by default and let users load them per message. - [x] Block remote images by default and let users load them per message on desktop and Android/Web.
## Mail security ## Mail security
@@ -34,8 +35,8 @@
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests. - [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures). - [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
- [x] Phase 6: documentation and release. - [x] Phase 6: documentation and release.
- [ ] Manual interoperability check with Thunderbird. - [x] Manual interoperability check with Thunderbird.
- [ ] Independent security review of the encryption code before relying on it. - [x] Independent security review of the encryption code before relying on it.
## Appearance and settings ## Appearance and settings
@@ -60,3 +61,14 @@
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name. - [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] Display name must be set per account.
- [x] Remove the display name initials from the bottom-left corner. - [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.
@@ -18,6 +18,8 @@ import java.util.Date
import java.util.Locale import java.util.Locale
import java.util.Properties import java.util.Properties
import java.util.UUID import java.util.UUID
import android.util.Base64
import javax.activation.DataHandler
import javax.mail.Address import javax.mail.Address
import javax.mail.Authenticator import javax.mail.Authenticator
import javax.mail.Flags import javax.mail.Flags
@@ -28,6 +30,7 @@ import javax.mail.PasswordAuthentication
import javax.mail.Session import javax.mail.Session
import javax.mail.Store import javax.mail.Store
import javax.mail.Transport import javax.mail.Transport
import javax.mail.util.ByteArrayDataSource
import javax.mail.UIDFolder import javax.mail.UIDFolder
import javax.mail.internet.InternetAddress import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart import javax.mail.internet.MimeBodyPart
@@ -272,10 +275,37 @@ internal object AndroidMailService {
message.subject = input.optString("subject", "(no subject)") message.subject = input.optString("subject", "(no subject)")
val body = input.optString("text") val body = input.optString("text")
val signature = account.optString("signature").take(5000) val signature = account.optString("signature").take(5000)
message.setText( val fullBody = if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature"
if (signature.isBlank()) body else "$body${if (body.isBlank()) "" else "\n\n"}$signature", val attachments = input.optJSONArray("attachments") ?: JSONArray()
"UTF-8" 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.sentDate = Date()
message.saveChanges() message.saveChanges()
input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) } input.optString("messageId").takeIf(String::isNotBlank)?.let { message.setHeader("Message-ID", it) }
@@ -561,9 +591,10 @@ internal object AndroidMailService {
val senderEmail = sender?.address ?: "" val senderEmail = sender?.address ?: ""
val subject = decode(message.subject).ifBlank { "(no subject)" } val subject = decode(message.subject).ifBlank { "(no subject)" }
val body = ArrayList<String>() val body = ArrayList<String>()
val htmlBodies = ArrayList<String>()
val attachments = JSONArray() val attachments = JSONArray()
val links = linkedSetOf<String>() val links = linkedSetOf<String>()
collectParts(message, body, attachments, links) collectParts(message, body, htmlBodies, attachments, links)
val bodyText = body.joinToString("\n\n").trim().take(8000) val bodyText = body.joinToString("\n\n").trim().take(8000)
val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180) val snippet = (bodyText.ifBlank { subject }).replace(Regex("\\s+"), " ").take(180)
val date = message.receivedDate ?: message.sentDate ?: Date() val date = message.receivedDate ?: message.sentDate ?: Date()
@@ -598,6 +629,7 @@ internal object AndroidMailService {
.put("archived", requestedFolder == "Archive") .put("archived", requestedFolder == "Archive")
.put("deleted", requestedFolder == "Trash") .put("deleted", requestedFolder == "Trash")
.put("sourceFolder", labelFolder) .put("sourceFolder", labelFolder)
.put("html", htmlBodies.firstOrNull()?.take(100000) ?: "")
.put("body", JSONArray().apply { .put("body", JSONArray().apply {
val paragraphs = bodyText.split(Regex("\\n\\s*\\n")).map(String::trim).filter(String::isNotEmpty).take(40) 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) if (paragraphs.isEmpty()) put("This message has no plain-text body.") else paragraphs.forEach(::put)
@@ -611,7 +643,13 @@ internal object AndroidMailService {
private fun attachmentList(attachments: JSONArray): List<JSONObject> = private fun attachmentList(attachments: JSONArray): List<JSONObject> =
(0 until attachments.length()).map { attachments.getJSONObject(it) } (0 until attachments.length()).map { attachments.getJSONObject(it) }
private fun collectParts(part: javax.mail.Part, body: MutableList<String>, attachments: JSONArray, links: MutableSet<String>) { private fun collectParts(
part: javax.mail.Part,
body: MutableList<String>,
htmlBodies: MutableList<String>,
attachments: JSONArray,
links: MutableSet<String>
) {
val filename = decode(part.fileName) val filename = decode(part.fileName)
if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) { if (filename.isNotBlank() || part.disposition.equals(javax.mail.Part.ATTACHMENT, true)) {
val name = filename.ifBlank { "attachment" } val name = filename.ifBlank { "attachment" }
@@ -624,6 +662,7 @@ internal object AndroidMailService {
is String -> if (part.isMimeType("text/plain")) { is String -> if (part.isMimeType("text/plain")) {
body.add(content.replace("\r", "").trim()) body.add(content.replace("\r", "").trim())
} else if (part.isMimeType("text/html")) { } else if (part.isMimeType("text/html")) {
if (htmlBodies.isEmpty()) htmlBodies.add(content.take(100000))
Regex("""<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE) Regex("""<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", RegexOption.IGNORE_CASE)
.findAll(content) .findAll(content)
.mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&amp;", "&") } .mapNotNull { match -> (match.groups[1]?.value ?: match.groups[2]?.value ?: match.groups[3]?.value)?.replace("&amp;", "&") }
@@ -632,9 +671,9 @@ internal object AndroidMailService {
if (body.isEmpty()) body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim()) if (body.isEmpty()) body.add(Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY).toString().trim())
} }
is Multipart -> for (index in 0 until content.count) { is Multipart -> for (index in 0 until content.count) {
collectParts(content.getBodyPart(index), body, attachments, links) collectParts(content.getBodyPart(index), body, htmlBodies, attachments, links)
} }
is javax.mail.BodyPart -> collectParts(content, body, attachments, links) is javax.mail.BodyPart -> collectParts(content, body, htmlBodies, attachments, links)
} }
} }
@@ -331,6 +331,7 @@ class EpMailPlugin : Plugin() {
.put("cc", input.optString("cc").take(4000)) .put("cc", input.optString("cc").take(4000))
.put("subject", input.optString("subject").take(998)) .put("subject", input.optString("subject").take(998))
.put("text", input.optString("text").take(500000)) .put("text", input.optString("text").take(500000))
.put("attachments", input.optJSONArray("attachments") ?: JSONArray())
.put("updatedAt", System.currentTimeMillis()) .put("updatedAt", System.currentTimeMillis())
AndroidAccountVault.saveDraft(account.optString("id"), draft) AndroidAccountVault.saveDraft(account.optString("id"), draft)
call.resolve(draft.toJSObject()) call.resolve(draft.toJSObject())
@@ -497,8 +498,8 @@ class EpMailPlugin : Plugin() {
require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) { require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) {
"Mail rule ${index + 1} has an invalid destination folder." "Mail rule ${index + 1} has an invalid destination folder."
} }
require(action != "move" || value in setOf("Inbox", "Archive", "Trash")) { require(action != "move" || value in setOf("Inbox", "Archive", "Trash") || AndroidMailService.isCustomFolder(value)) {
"Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash." "Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders."
} }
result.put(JSONObject() result.put(JSONObject()
.put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() }) .put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() })
+68 -1
View File
@@ -4,8 +4,75 @@ const contacts=[];
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set(); let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; 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 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 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();$('#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 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 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 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 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()} 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
@@ -0,0 +1,30 @@
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 };
+277 -11
View File
@@ -1,4 +1,5 @@
const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor } = require('electron'); const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron');
const fsSync = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const fs = require('node:fs/promises'); const fs = require('node:fs/promises');
const { ImapFlow } = require('imapflow'); const { ImapFlow } = require('imapflow');
@@ -7,6 +8,9 @@ const { simpleParser } = require('mailparser');
const { randomUUID } = require('node:crypto'); const { randomUUID } = require('node:crypto');
const { createDAVClient } = require('tsdav'); const { createDAVClient } = require('tsdav');
const ICAL = require('ical.js'); 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 credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc'); const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
@@ -15,6 +19,7 @@ const backgroundRetryIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2; const backgroundSyncConcurrency = 2;
const backgroundIdleConcurrency = 2; const backgroundIdleConcurrency = 2;
const snoozeCheckIntervalMs = 30 * 1000; const snoozeCheckIntervalMs = 30 * 1000;
const windowsAppUserModelId = 'studio.daybreak.mail';
let accountStoreQueue = Promise.resolve(); let accountStoreQueue = Promise.resolve();
let backgroundSyncInProgress = false; let backgroundSyncInProgress = false;
let backgroundSyncRequested = false; let backgroundSyncRequested = false;
@@ -24,6 +29,8 @@ const backgroundSyncFailures = new Map();
const flagSnapshots = new Map(); const flagSnapshots = new Map();
const idleWatchers = new Map(); const idleWatchers = new Map();
const lastBackgroundSyncAt = new Map(); const lastBackgroundSyncAt = new Map();
let windowsAppIcon = null;
let tray = null;
function updateAccountStore(update) { function updateAccountStore(update) {
const operation = accountStoreQueue.then(async () => { const operation = accountStoreQueue.then(async () => {
@@ -200,6 +207,7 @@ const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
const pgpKeys = createKeyStore({ const pgpKeys = createKeyStore({
async load() { async load() {
try { try {
assertSecureStorage();
const { result } = await safeStorage.decryptStringAsync(await fs.readFile(pgpKeysPath())); const { result } = await safeStorage.decryptStringAsync(await fs.readFile(pgpKeysPath()));
return JSON.parse(result); return JSON.parse(result);
} catch (error) { } catch (error) {
@@ -208,6 +216,7 @@ const pgpKeys = createKeyStore({
} }
}, },
async save(data) { async save(data) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.'); if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.');
await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true }); await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true });
await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 }); await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 });
@@ -217,9 +226,11 @@ const pgpKeys = createKeyStore({
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes); const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache }); const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
const pgpKeyServers = createKeyServerService();
async function readDavStore() { async function readDavStore() {
try { try {
assertSecureStorage();
const encrypted = await fs.readFile(davCredentialsPath()); const encrypted = await fs.readFile(davCredentialsPath());
const { result } = await safeStorage.decryptStringAsync(encrypted); const { result } = await safeStorage.decryptStringAsync(encrypted);
return JSON.parse(result); return JSON.parse(result);
@@ -230,6 +241,7 @@ async function readDavStore() {
} }
async function saveDavStore(store) { async function saveDavStore(store) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure credential storage is unavailable.'); if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure credential storage is unavailable.');
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store)); const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
await fs.mkdir(path.dirname(davCredentialsPath()), { recursive: true }); await fs.mkdir(path.dirname(davCredentialsPath()), { recursive: true });
@@ -294,8 +306,8 @@ function normalizeAccount(input) {
if ((action === 'move' || action === 'label') && !value) { if ((action === 'move' || action === 'label') && !value) {
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`); throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
} }
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value)) { if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value) && !value.startsWith(CUSTOM_FOLDER_PREFIX)) {
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash.`); throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders.`);
} }
return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value }; return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value };
}); });
@@ -340,9 +352,19 @@ 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() { async function readAccountStore() {
try { try {
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.'); assertSecureStorage();
const encrypted = await fs.readFile(credentialsPath()); const encrypted = await fs.readFile(credentialsPath());
const { result } = await safeStorage.decryptStringAsync(encrypted); const { result } = await safeStorage.decryptStringAsync(encrypted);
const stored = JSON.parse(result); const stored = JSON.parse(result);
@@ -361,6 +383,7 @@ async function readAccountStore() {
} }
async function saveAccountStore(store) { async function saveAccountStore(store) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) { if (!await safeStorage.isAsyncEncryptionAvailable()) {
throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.'); throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.');
} }
@@ -592,6 +615,7 @@ async function toUiMessage(item, folder) {
deleted: folder === 'Trash', deleted: folder === 'Trash',
sourceFolder: folder, sourceFolder: folder,
body, body,
html: content.html,
links, links,
uid: Number(item.uid), uid: Number(item.uid),
attachments: content.attachments, attachments: content.attachments,
@@ -612,6 +636,7 @@ function mailContent(parsed) {
return { return {
bodyText, bodyText,
body, body,
html: html.slice(0, 100000),
links, links,
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })), attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: files[0]?.filename || null, attachment: files[0]?.filename || null,
@@ -1009,6 +1034,7 @@ ipcMain.handle('mail:save-draft', async (_event, input) => {
cc: String(input?.cc || '').slice(0, 4000), cc: String(input?.cc || '').slice(0, 4000),
subject: String(input?.subject || '').slice(0, 998), subject: String(input?.subject || '').slice(0, 998),
text: String(input?.text || '').slice(0, 500000), text: String(input?.text || '').slice(0, 500000),
attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)),
updatedAt: Date.now() updatedAt: Date.now()
}; };
await updateAccountStore(store => { await updateAccountStore(store => {
@@ -1301,6 +1327,12 @@ ipcMain.handle('pgp:export-private', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint); const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-private-${id.slice(-16)}.asc`, await pgpKeys.exportPrivate(id, passphrase)); 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) => { ipcMain.handle('pgp:export-revocation', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint); const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase)); return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase));
@@ -1352,6 +1384,7 @@ ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
return { return {
ok: true, ok: true,
body: content.body, body: content.body,
html: content.html,
links: content.links, links: content.links,
attachments: content.attachments, attachments: content.attachments,
attachment: content.attachment, attachment: content.attachment,
@@ -1381,9 +1414,55 @@ 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.'); 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'); armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
} }
return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' }); 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 });
});
ipcMain.handle('pgp:set-trust', async (event, fingerprint, trust) => {
const id = pgpFingerprint(fingerprint);
const level = String(trust);
// Raising trust changes which key outgoing mail is encrypted to, so confirm it here, outside the renderer.
if (level !== 'unknown') {
const contact = (await pgpKeys.listContacts()).find(item => item.fingerprint === id);
if (!contact) throw new Error('That contact key was not found.');
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
type: 'question',
buttons: ['Cancel', `Mark as ${level}`],
defaultId: 0,
cancelId: 0,
title: 'Confirm key trust',
message: `Mark this key as ${level}?`,
detail: `${contact.name || ''} ${(contact.emails || []).join(', ')}\nFingerprint:\n${id.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly continue if you checked this fingerprint with the owner.`
});
if (response !== 1) throw new Error('Trust change cancelled.');
}
return pgpKeys.setTrust(id, level);
}); });
ipcMain.handle('pgp:set-trust', (_event, fingerprint, trust) => pgpKeys.setTrust(pgpFingerprint(fingerprint), String(trust)));
ipcMain.handle('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint))); ipcMain.handle('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
ipcMain.handle('pgp:export-contact', async (event, fingerprint) => { ipcMain.handle('pgp:export-contact', async (event, fingerprint) => {
const id = pgpFingerprint(fingerprint); const id = pgpFingerprint(fingerprint);
@@ -1395,6 +1474,98 @@ ipcMain.handle('pgp:set-settings', async (_event, input) => {
pgpCache.clear(); pgpCache.clear();
return settings; 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('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
ipcMain.handle('mail:open-external', async (event, rawUrl) => { ipcMain.handle('mail:open-external', async (event, rawUrl) => {
@@ -1432,6 +1603,7 @@ ipcMain.handle('mail:sync-inbox', async () => {
async function sendMailNow(account, message) { async function sendMailNow(account, message) {
const to = String(message?.to || '').trim(); const to = String(message?.to || '').trim();
if (!to) throw new Error('Add at least one recipient.'); if (!to) throw new Error('Add at least one recipient.');
const attachments = normalizeOutgoingAttachments(message?.attachments);
const transport = smtpTransport(account); const transport = smtpTransport(account);
const sentMessageId = String(message.messageId || `<${require('node:crypto').randomUUID()}@ep-mail.local>`); 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; const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
@@ -1443,7 +1615,12 @@ async function sendMailNow(account, message) {
cc: String(message.cc || '').trim() || undefined, cc: String(message.cc || '').trim() || undefined,
subject: String(message.subject || '(no subject)').slice(0, 998), subject: String(message.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: sentMessageId messageId: sentMessageId,
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
}; };
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null; const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
try { try {
@@ -1477,12 +1654,31 @@ async function sendMailNow(account, message) {
return { ok: true, savedToSent }; return { ok: true, savedToSent };
} }
ipcMain.handle('mail:send', async (_event, message) => { ipcMain.handle('mail:send', async (event, message) => {
const account = await readAccount(); const account = await readAccount();
if (!account) throw new Error('Add a mail account before sending.'); 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 pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null;
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` }; const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
const attachments = normalizeOutgoingAttachments(message?.attachments);
queuedMessage.attachments = serializeOutgoingAttachments(attachments);
delete queuedMessage.pgp; 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) { if (pgpOptions) {
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox. // Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
const signature = String(account.signature || '').slice(0, 5000); const signature = String(account.signature || '').slice(0, 5000);
@@ -1498,11 +1694,13 @@ ipcMain.handle('mail:send', async (_event, message) => {
messageId: queuedMessage.messageId, messageId: queuedMessage.messageId,
encrypt: Boolean(pgpOptions.encrypt), encrypt: Boolean(pgpOptions.encrypt),
sign: Boolean(pgpOptions.sign), sign: Boolean(pgpOptions.sign),
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null,
attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content }))
}); });
queuedMessage.rawBase64 = built.raw.toString('base64'); queuedMessage.rawBase64 = built.raw.toString('base64');
queuedMessage.envelope = built.envelope; queuedMessage.envelope = built.envelope;
queuedMessage.text = ''; queuedMessage.text = '';
queuedMessage.attachments = [];
} catch (error) { } catch (error) {
if (error instanceof PgpError) return pgpFailure(error); if (error instanceof PgpError) return pgpFailure(error);
throw error; throw error;
@@ -1699,7 +1897,7 @@ function createWindow() {
backgroundColor: '#f4f5f1', backgroundColor: '#f4f5f1',
show: false, show: false,
autoHideMenuBar: true, autoHideMenuBar: true,
icon: path.join(__dirname, '..', 'icon.svg'), icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'),
webPreferences: { webPreferences: {
preload: path.join(__dirname, 'preload.cjs'), preload: path.join(__dirname, 'preload.cjs'),
contextIsolation: true, contextIsolation: true,
@@ -1717,10 +1915,78 @@ function createWindow() {
window.webContents.on('will-navigate', (event, url) => { window.webContents.on('will-navigate', (event, url) => {
if (!url.startsWith('file:')) event.preventDefault(); 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.whenReady().then(() => {
app.setAppUserModelId('studio.daybreak.mail'); 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();
}
createWindow(); createWindow();
const syncTimer = setInterval(() => { const syncTimer = setInterval(() => {
void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error)); void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error));
+277
View File
@@ -0,0 +1,277 @@
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
};
+49 -4
View File
@@ -109,7 +109,7 @@ function createKeyStore(storage) {
name: user.user.userID?.name || '', name: user.user.userID?.name || '',
emails, emails,
trust: 'unknown', trust: 'unknown',
source: ['import', 'message', 'paste'].includes(source) ? source : 'import', source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import',
addedAt: Date.now(), addedAt: Date.now(),
publicKey: key.armor() publicKey: key.armor()
}; };
@@ -193,16 +193,43 @@ function createKeyStore(storage) {
async getSettings() { async getSettings() {
const settings = (await read()).settings; const settings = (await read()).settings;
return { cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES }; 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'))]
: []
};
}, },
async setSettings({ cacheMinutes }) { async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) {
const minutes = Number(cacheMinutes); const minutes = Number(cacheMinutes);
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.'); if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
const data = await read(); const data = await read();
data.settings.cacheMinutes = Math.round(minutes); 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); await storage.save(data);
return { cacheMinutes: data.settings.cacheMinutes }; return {
cacheMinutes: data.settings.cacheMinutes,
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [],
enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : []
};
}, },
async list() { async list() {
@@ -278,6 +305,24 @@ function createKeyStore(storage) {
return entry.privateKey; 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) { async exportRevocation(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint); const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.'); if (!entry) throw new Error('That key was not found.');
+18 -3
View File
@@ -1,6 +1,7 @@
const openpgp = require('openpgp'); const openpgp = require('openpgp');
const { simpleParser } = require('mailparser'); const { simpleParser } = require('mailparser');
const addressParser = require('nodemailer/lib/addressparser'); const addressParser = require('nodemailer/lib/addressparser');
const MailComposer = require('nodemailer/lib/mail-composer');
const { randomBytes } = require('node:crypto'); const { randomBytes } = require('node:crypto');
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/; const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
@@ -131,7 +132,21 @@ function parseAddresses(value) {
return addressParser(String(value || '')).filter(entry => entry.address || entry.name); return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
} }
function innerEntity(text) { 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')));
});
}
const body = Buffer.from(String(text || ''), 'utf8'); 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'); return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1');
} }
@@ -252,7 +267,7 @@ function createPgpMail({ keyStore, cache }) {
}, },
// Builds a complete RFC 3156 message. Returns { raw, envelope }. // Builds a complete RFC 3156 message. Returns { raw, envelope }.
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint }) { async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint, attachments = [] }) {
const toList = parseAddresses(to); const toList = parseAddresses(to);
const ccList = parseAddresses(cc); const ccList = parseAddresses(cc);
if (!toList.length) throw new Error('Add at least one recipient.'); if (!toList.length) throw new Error('Add at least one recipient.');
@@ -284,7 +299,7 @@ function createPgpMail({ keyStore, cache }) {
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`, `Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
'MIME-Version: 1.0' 'MIME-Version: 1.0'
]; ];
const inner = innerEntity(text); const inner = await innerEntity(text, attachments);
const mark = boundary(); const mark = boundary();
let body; let body;
let contentType; let contentType;
+8 -1
View File
@@ -29,6 +29,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
importKey: details => ipcRenderer.invoke('pgp:import', details), importKey: details => ipcRenderer.invoke('pgp:import', details),
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint), exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase), 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), exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase), remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details), decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
@@ -40,7 +41,13 @@ contextBridge.exposeInMainWorld('daybreakMail', {
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint), exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
getSettings: () => ipcRenderer.invoke('pgp:get-settings'), getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings), setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases') 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)
}, },
davList: () => ipcRenderer.invoke('dav:list'), davList: () => ipcRenderer.invoke('dav:list'),
davConnect: config => ipcRenderer.invoke('dav:connect', config), davConnect: config => ipcRenderer.invoke('dav:connect', config),
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 364 KiB

+3 -3
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4f5f1"> <meta name="theme-color" content="#f4f5f1">
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux."> <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:; font-src 'self'; connect-src 'none'"> <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'">
<title>ep-mail</title> <title>ep-mail</title>
<link rel="manifest" href="manifest.webmanifest"> <link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="styles.css">
@@ -24,6 +24,7 @@
<aside class="sidebar"> <aside class="sidebar">
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div> <div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div> <div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders"> <nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button> <button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button> <button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
@@ -32,10 +33,9 @@
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button> <button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button> <button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button> <button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
<div id="custom-folders"></div>
</nav> </nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button> <button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<div id="custom-folders" class="folder-nav"></div>
<div class="sidebar-divider"></div> <div class="sidebar-divider"></div>
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div> <div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button> <button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
+161 -9
View File
@@ -140,9 +140,38 @@ async function loadCustomFolders() {
} catch {} } catch {}
} }
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
function ruleFolderSelect(selected = 'Inbox') {
const options = [['Inbox', 'Inbox'], ['Archive', 'Archive'], ['Trash', 'Trash'], ...customFolders.map(folder => [folder.id, folder.name])];
if (!options.some(([value]) => value === selected)) {
options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]);
}
return '<select class="mail-rule-value" aria-label="Destination folder">' +
options.map(([value, name]) => '<option value="' + esc(value) + '"' + (value === selected ? ' selected' : '') + '>' + esc(name) + '</option>').join('') + '</select>';
}
// window.prompt() is not available in Electron, so ask for text in an in-app dialog.
function askText(title, label, placeholder = '') {
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay pgp-prompt';
overlay.innerHTML = '<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><label class="compose-line"><span></span><input type="text" maxlength="200"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">OK</button></div></form>';
overlay.querySelector('.modal-head span').textContent = title;
overlay.querySelector('.compose-line span').textContent = label;
const input = overlay.querySelector('input');
input.placeholder = placeholder;
const finish = value => { overlay.remove(); resolve(value); };
overlay.querySelector('form').onsubmit = event => { event.preventDefault(); finish(input.value.trim() || null); };
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
document.body.append(overlay);
input.focus();
});
}
async function createMailFolder() { async function createMailFolder() {
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; } if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = prompt('New mail folder name:')?.trim(); const name = await askText('New mail folder', 'Name');
if (!name) return; if (!name) return;
try { try {
const result = await window.daybreakMail.createFolder(name); const result = await window.daybreakMail.createFolder(name);
@@ -187,7 +216,7 @@ function openMailAccount(existingAccount = null) {
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')} ${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
</select> </select>
${rule.action==='move' ${rule.action==='move'
? `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${rule.value==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${rule.value==='Archive'?' selected':''}>Archive</option><option value="Trash"${rule.value==='Trash'?' selected':''}>Trash</option></select>` ? `${ruleFolderSelect(rule.value)}`
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`} : `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button> <button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
</div>`).join(''); </div>`).join('');
@@ -212,8 +241,8 @@ function openMailAccount(existingAccount = null) {
const row = event.target.closest('.mail-rule-row'); const row = event.target.closest('.mail-rule-row');
const value = row.querySelector('.mail-rule-value'); const value = row.querySelector('.mail-rule-value');
if (event.target.value === 'move') { if (event.target.value === 'move') {
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox'; const selected = value.value || 'Inbox';
value.outerHTML = `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${selected==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${selected==='Archive'?' selected':''}>Archive</option><option value="Trash"${selected==='Trash'?' selected':''}>Trash</option></select>`; value.outerHTML = ruleFolderSelect(selected);
} else if (value.tagName === 'SELECT') { } else if (value.tagName === 'SELECT') {
value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`; value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
} }
@@ -288,7 +317,37 @@ function mailSearchFilters() {
}; };
} }
const selectedDraftIds = new Set();
async function deleteSelectedDrafts() {
const ids = messages.map(message => String(message.id)).filter(id => selectedDraftIds.has(id));
if (!ids.length) { toast('Select one or more drafts first'); return; }
if (!confirm(`Delete ${ids.length} selected draft${ids.length === 1 ? '' : 's'}?`)) return;
try {
for (const id of ids) await window.daybreakMail.deleteDraft(id);
selectedDraftIds.clear();
toast(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`);
await syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete the drafts'); }
}
// In the Drafts folder the shared toolbar acts on drafts, which use string ids.
document.addEventListener('click', event => {
if (activeFolder !== 'Drafts') return;
const button = event.target.closest('#select-all, #delete-selected, #archive-selected, #mark-unread');
if (!button) return;
event.stopImmediatePropagation();
if (button.id === 'select-all') {
const ids = messages.map(message => String(message.id));
const all = ids.length && ids.every(id => selectedDraftIds.has(id));
ids.forEach(id => all ? selectedDraftIds.delete(id) : selectedDraftIds.add(id));
renderDrafts(messages.map(message => message.draft));
} else if (button.id === 'delete-selected') void deleteSelectedDrafts();
}, true);
function renderDrafts(drafts) { function renderDrafts(drafts) {
const present = new Set(drafts.map(draft => String(draft.id)));
[...selectedDraftIds].forEach(id => { if (!present.has(id)) selectedDraftIds.delete(id); });
messages.splice(0, messages.length, ...drafts.map(draft => ({ messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id, id: draft.id,
sender: 'Draft', sender: 'Draft',
@@ -302,14 +361,28 @@ function renderDrafts(drafts) {
draft draft
}))); })));
$('#message-list').innerHTML = messages.length ? messages.map(message => ` $('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div> <div class="message" data-id="${esc(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div> <div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') : <div class="message-meta"><span class="time">${esc(message.date)}</span><button type="button" class="icon-button draft-delete" title="Delete draft" aria-label="Delete draft">⌫</button></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>'; '<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft'); const start = $('#start-draft');
if (start) start.onclick = () => showCompose(); if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => { $$('.message').forEach(row => row.onclick = event => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft; const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (event.target.closest('.row-check')) {
event.stopPropagation();
const id = row.dataset.id;
selectedDraftIds.has(id) ? selectedDraftIds.delete(id) : selectedDraftIds.add(id);
return;
}
if (event.target.closest('.draft-delete')) {
event.stopPropagation();
if (!draft || !confirm('Delete this draft?')) return;
window.daybreakMail.deleteDraft(draft.id)
.then(() => { toast('Draft deleted'); return syncMailbox(false); })
.catch(error => toast(error.message || 'Could not delete the draft'));
return;
}
if (draft) showCompose(null, false, draft); if (draft) showCompose(null, false, draft);
}); });
$('#reader-pane').innerHTML = emptyReader(); $('#reader-pane').innerHTML = emptyReader();
@@ -325,6 +398,83 @@ function setupDraftComposer() {
const modal = root.querySelector('.compose-modal'); const modal = root.querySelector('.compose-modal');
if (!modal) return; if (!modal) return;
modal.dataset.draftId = draft?.id || ''; 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) { if (draft) {
$('#compose-to').value = draft.to || ''; $('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || ''; $('#compose-cc').value = draft.cc || '';
@@ -347,9 +497,10 @@ function setupDraftComposer() {
to: $('#compose-to').value, to: $('#compose-to').value,
cc: $('#compose-cc').value, cc: $('#compose-cc').value,
subject: $('#compose-subject').value, subject: $('#compose-subject').value,
text: $('#compose-body').value text: $('#compose-body').value,
attachments
}; };
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return; if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
modal.dataset.draftId = values.id; modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values); const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id; modal.dataset.draftId = result.id;
@@ -595,6 +746,7 @@ if (window.daybreakMail) {
cc: $('#compose-cc').value, cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(), subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value, text: $('#compose-body').value,
attachments: $('#modal-root .compose-modal')?._composeAttachments || [],
displayName: connectedMailAccount.displayName || profileSettings.name, displayName: connectedMailAccount.displayName || profileSettings.name,
...(pgp ? { pgp } : {}) ...(pgp ? { pgp } : {})
}); });
+2 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.3.1", "version": "0.4.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "ep-mail", "name": "ep-mail",
"version": "0.3.1", "version": "0.4.4",
"dependencies": { "dependencies": {
"@capacitor/android": "^8.5.2", "@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2", "@capacitor/core": "^8.5.2",
+11 -3
View File
@@ -1,9 +1,13 @@
{ {
"name": "ep-mail", "name": "ep-mail",
"version": "0.3.1", "version": "0.4.4",
"private": true, "private": true,
"description": "Eternity Project mail client", "description": "Eternity Project mail client",
"author": "Eternity Project", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
"author": {
"name": "Eternity Project",
"email": "tero.huttunen@eternityproject.fi"
},
"desktopName": "ep-mail", "desktopName": "ep-mail",
"main": "desktop/main.cjs", "main": "desktop/main.cjs",
"scripts": { "scripts": {
@@ -20,7 +24,8 @@
"build:android-web": "node scripts/prepare-android-web.cjs", "build:android-web": "node scripts/prepare-android-web.cjs",
"android:sync": "npm run build:android-web && cap sync android", "android:sync": "npm run build:android-web && cap sync android",
"android:open": "npm run android:sync && cap open android", "android:open": "npm run android:sync && cap open android",
"android:apk": "npm run android:sync && node scripts/build-android-apk.cjs" "android:apk": "npm run android:sync && node scripts/build-android-apk.cjs",
"build:all": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/build-all.ps1"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^8.5.2", "@capacitor/cli": "^8.5.2",
@@ -47,6 +52,7 @@
"pgp-ui.js", "pgp-ui.js",
"pgp-mail-ui.js", "pgp-mail-ui.js",
"icon.svg", "icon.svg",
"icon.ico",
"logo-ep-daylight.svg", "logo-ep-daylight.svg",
"logo-ep-wasteland.svg", "logo-ep-wasteland.svg",
"manifest.webmanifest", "manifest.webmanifest",
@@ -58,6 +64,7 @@
"output": "release" "output": "release"
}, },
"win": { "win": {
"icon": "icon.ico",
"target": [ "target": [
"nsis", "nsis",
"portable" "portable"
@@ -76,6 +83,7 @@
"AppImage", "AppImage",
"deb" "deb"
], ],
"maintainer": "Tero Huttunen <tero.huttunen@eternityproject.fi>",
"synopsis": "A calmer place for mail, people, and plans" "synopsis": "A calmer place for mail, people, and plans"
} }
}, },
+11 -3
View File
@@ -92,7 +92,7 @@ async function pgpUnlockMessage(message, interactive) {
} }
if (result.ok) { if (result.ok) {
Object.assign(message, { Object.assign(message, {
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys } snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
}); });
if (activeMessage === message.id) openMessage(message.id); if (activeMessage === message.id) openMessage(message.id);
@@ -140,7 +140,8 @@ if (typeof showCompose === 'function') {
const encrypt = $('#pgp-encrypt'); const encrypt = $('#pgp-encrypt');
const sign = $('#pgp-sign'); const sign = $('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
encrypt.addEventListener('change', () => { touched = true; }); if (touched) encrypt.dataset.touched = '1';
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
let timer = null; let timer = null;
const refresh = async () => { const refresh = async () => {
const to = $('#compose-to')?.value || ''; const to = $('#compose-to')?.value || '';
@@ -170,8 +171,15 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
if (!pgpApi()) return null; if (!pgpApi()) return null;
let encrypt = Boolean($('#pgp-encrypt')?.checked); let encrypt = Boolean($('#pgp-encrypt')?.checked);
const sign = Boolean($('#pgp-sign')?.checked); const sign = Boolean($('#pgp-sign')?.checked);
if (!encrypt && !sign) return null; if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
const status = await pgpApi().checkSend({ to, cc, sign }); const status = await pgpApi().checkSend({ to, cc, sign });
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
if (!encrypt && !status.missing.length && status.recipients.length && $('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return null;
} else return false;
}
if (!encrypt && !sign) return null;
if (encrypt && status.missing.length) { if (encrypt && status.missing.length) {
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`); const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
if (!sendPlain) return false; if (!sendPlain) return false;
+226
View File
@@ -7,9 +7,27 @@ 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"> 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> <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> <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> <h3 class="pgp-heading">Contact public keys</h3>
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div> <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> <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> <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> <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> <div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
@@ -26,6 +44,15 @@ function openEncryptionKeys() {
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const status = message => { $('#pgp-status').textContent = message; }; const status = message => { $('#pgp-status').textContent = message; };
const passphraseField = () => $('#pgp-passphrase'); 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 needPassphrase = () => {
const value = passphraseField().value; const value = passphraseField().value;
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); } if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
@@ -55,6 +82,44 @@ function openEncryptionKeys() {
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false], ['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true] ['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]); if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
actions.push(['Delete', async () => { 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 }; if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
@@ -75,8 +140,28 @@ function openEncryptionKeys() {
}; };
row.append(button); 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); list.append(row);
}); });
updatePublishButtons();
} }
$('#pgp-generate').onclick = async () => { $('#pgp-generate').onclick = async () => {
@@ -166,12 +251,153 @@ function openEncryptionKeys() {
await renderContacts(); await renderContacts();
} catch (error) { status(error.message || 'Could not import the key.'); } } 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(() => {}); window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
$('#pgp-save-cache').onclick = async () => { $('#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).`); } 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.'); } catch (error) { status(error.message || 'Could not save the setting.'); }
}; };
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); }; $('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
void renderKeyServers();
void renderContacts(); void renderContacts();
void render(); void render();
} }
+19
View File
@@ -0,0 +1,19 @@
# Builds the Android APK and the Windows portable exe into .\release
$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot\..
$version = (Get-Content package.json -Raw | ConvertFrom-Json).version
if (-not $env:JAVA_HOME) { $env:JAVA_HOME = 'C:\Program Files\Android\Android Studio\jbr' }
if (-not $env:ANDROID_HOME) { $env:ANDROID_HOME = Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
New-Item -ItemType Directory -Force release | Out-Null
Write-Host "== Building APK $version =="
npm run android:apk
if ($LASTEXITCODE) { throw 'APK build failed' }
Copy-Item android\app\build\outputs\apk\debug\app-debug.apk "release\ep-mail $version.apk" -Force
Write-Host "== Building portable exe $version =="
npm run dist:win:portable
if ($LASTEXITCODE) { throw 'Portable build failed' }
Write-Host "`nDone:"
Get-ChildItem release | Where-Object { $_.Name -like "ep-mail $version.*" } | ForEach-Object { " $($_.FullName)" }
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE='ep-mail-v7'; const CACHE='ep-mail-v8';
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']; 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('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)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
+5
View File
@@ -136,3 +136,8 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px} .pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px}
.pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8} .pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8}
.pgp-trust{margin-left:8px} .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
@@ -0,0 +1,38 @@
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
@@ -0,0 +1,244 @@
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,6 +43,52 @@ 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')); 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 () => { 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 { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
const keys = createKeyStore(memoryStore()); const keys = createKeyStore(memoryStore());
+38 -3
View File
@@ -75,6 +75,29 @@ 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 () => { test('detects tampered and corrupted encrypted messages', async () => {
const alice = await actor('Alice', 'alice@example.com'); const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com'); const bob = await actor('Bob', 'bob@example.com');
@@ -112,10 +135,16 @@ test('signs without encrypting and verifies PGP/MIME signatures', async () => {
const alice = await actor('Alice', 'alice@example.com'); const alice = await actor('Alice', 'alice@example.com');
const bob = await actor('Bob', 'bob@example.com'); const bob = await actor('Bob', 'bob@example.com');
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) }); await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { sign: true, passphrase: alice.passphrase })); 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 parsed = await simpleParser(raw); const parsed = await simpleParser(raw);
assert.equal(detect(parsed), 'signed-mime'); assert.equal(detect(parsed), 'signed-mime');
assert.match(parsed.text, /Top secret/); assert.match(parsed.text, /Top secret/);
assert.deepEqual(parsed.attachments[0].content, attachment);
const [signature] = await bob.mail.verifySigned(parsed, raw); const [signature] = await bob.mail.verifySigned(parsed, raw);
assert.equal(signature.status, 'valid'); assert.equal(signature.status, 'valid');
const altered = Buffer.from(raw.toString('latin1').replace('Content-Type: text/plain', 'Content-Type: text/plain'), 'latin1'); const altered = Buffer.from(raw.toString('latin1').replace('Content-Type: text/plain', 'Content-Type: text/plain'), 'latin1');
@@ -166,9 +195,15 @@ 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.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(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/); await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10 }); assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [] });
await alice.keyStore.setSettings({ cacheMinutes: 0 }); 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.equal((await alice.keyStore.getSettings()).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); await alice.keyStore.removeContact(contact.fingerprint);
assert.equal((await alice.keyStore.listContacts()).length, 0); assert.equal((await alice.keyStore.listContacts()).length, 0);
+68 -1
View File
@@ -4,8 +4,75 @@ const contacts=[];
let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set(); let activeMessage=1,activeFolder='Inbox',activeView='mail',query='',toastTimer,selectedIds=new Set();
const $=s=>document.querySelector(s), $$=s=>[...document.querySelectorAll(s)]; 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 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 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();$('#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 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 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 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 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()} 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()}
+3 -3
View File
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#f4f5f1"> <meta name="theme-color" content="#f4f5f1">
<meta name="description" content="ep-mail: Eternity Project mail, calendar, and contacts for Windows and Linux."> <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:; font-src 'self'; connect-src 'none'"> <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'">
<title>ep-mail</title> <title>ep-mail</title>
<link rel="manifest" href="manifest.webmanifest"> <link rel="manifest" href="manifest.webmanifest">
<link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="styles.css">
@@ -24,6 +24,7 @@
<aside class="sidebar"> <aside class="sidebar">
<div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div> <div class="sidebar-head"><div><p class="eyebrow">YOUR WORKSPACE</p><h1 id="sidebar-title">Inbox</h1></div><button class="icon-button" id="sidebar-menu" aria-label="More options">···</button></div>
<div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div> <div class="account-card" id="account-settings" role="button" tabindex="0" title="Set up a mail account"><div class="account-avatar">✉</div><div class="account-info"><strong>Mail accounts</strong><span>Manage connected mailboxes</span></div><span class="online-dot"></span></div>
<div class="section-label folders-head"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<nav id="mail-nav" class="folder-nav" aria-label="Mail folders"> <nav id="mail-nav" class="folder-nav" aria-label="Mail folders">
<button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button> <button class="folder active" data-folder="Inbox"><span class="nav-glyph">▣</span><span>Inbox</span></button>
<button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button> <button class="folder" data-folder="Starred"><span class="nav-glyph">☆</span><span>Starred</span></button>
@@ -32,10 +33,9 @@
<button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button> <button class="folder" data-folder="Drafts"><span class="nav-glyph">▤</span><span>Drafts</span></button>
<button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button> <button class="folder" data-folder="Archive"><span class="nav-glyph">▱</span><span>Archive</span></button>
<button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button> <button class="folder" data-folder="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
<div id="custom-folders"></div>
</nav> </nav>
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button> <button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
<div id="custom-folders" class="folder-nav"></div>
<div class="sidebar-divider"></div> <div class="sidebar-divider"></div>
<div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div> <div class="section-label"><span>LABELS</span><button class="tiny-plus" id="add-label" aria-label="Add label">+</button></div>
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button> <button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
+161 -9
View File
@@ -140,9 +140,38 @@ async function loadCustomFolders() {
} catch {} } catch {}
} }
// Destination options for the mail-rule folder picker: built-in folders plus the account's IMAP folders.
function ruleFolderSelect(selected = 'Inbox') {
const options = [['Inbox', 'Inbox'], ['Archive', 'Archive'], ['Trash', 'Trash'], ...customFolders.map(folder => [folder.id, folder.name])];
if (!options.some(([value]) => value === selected)) {
options.push([selected, String(selected).replace(/^[^:]*:/, '') || selected]);
}
return '<select class="mail-rule-value" aria-label="Destination folder">' +
options.map(([value, name]) => '<option value="' + esc(value) + '"' + (value === selected ? ' selected' : '') + '>' + esc(name) + '</option>').join('') + '</select>';
}
// window.prompt() is not available in Electron, so ask for text in an in-app dialog.
function askText(title, label, placeholder = '') {
return new Promise(resolve => {
const overlay = document.createElement('div');
overlay.className = 'modal-overlay pgp-prompt';
overlay.innerHTML = '<form class="compose-modal pgp-prompt-box" autocomplete="off"><div class="modal-head"><span></span></div><div class="compose-fields"><label class="compose-line"><span></span><input type="text" maxlength="200"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">OK</button></div></form>';
overlay.querySelector('.modal-head span').textContent = title;
overlay.querySelector('.compose-line span').textContent = label;
const input = overlay.querySelector('input');
input.placeholder = placeholder;
const finish = value => { overlay.remove(); resolve(value); };
overlay.querySelector('form').onsubmit = event => { event.preventDefault(); finish(input.value.trim() || null); };
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
document.body.append(overlay);
input.focus();
});
}
async function createMailFolder() { async function createMailFolder() {
if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; } if (!connectedMailAccount || !window.daybreakMail?.createFolder) { openMailAccount(); return; }
const name = prompt('New mail folder name:')?.trim(); const name = await askText('New mail folder', 'Name');
if (!name) return; if (!name) return;
try { try {
const result = await window.daybreakMail.createFolder(name); const result = await window.daybreakMail.createFolder(name);
@@ -187,7 +216,7 @@ function openMailAccount(existingAccount = null) {
${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')} ${[['archive','Archive'],['move','Move to folder'],['label','Apply label'],['flag','Flag']].map(([value,label])=>`<option value="${value}"${rule.action===value?' selected':''}>${label}</option>`).join('')}
</select> </select>
${rule.action==='move' ${rule.action==='move'
? `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${rule.value==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${rule.value==='Archive'?' selected':''}>Archive</option><option value="Trash"${rule.value==='Trash'?' selected':''}>Trash</option></select>` ? `${ruleFolderSelect(rule.value)}`
: `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`} : `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label" value="${esc(rule.value || '')}"${rule.action==='flag'?' disabled':''}>`}
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button> <button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
</div>`).join(''); </div>`).join('');
@@ -212,8 +241,8 @@ function openMailAccount(existingAccount = null) {
const row = event.target.closest('.mail-rule-row'); const row = event.target.closest('.mail-rule-row');
const value = row.querySelector('.mail-rule-value'); const value = row.querySelector('.mail-rule-value');
if (event.target.value === 'move') { if (event.target.value === 'move') {
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? value.value : 'Inbox'; const selected = value.value || 'Inbox';
value.outerHTML = `<select class="mail-rule-value" aria-label="Destination folder"><option value="Inbox"${selected==='Inbox'?' selected':''}>Inbox</option><option value="Archive"${selected==='Archive'?' selected':''}>Archive</option><option value="Trash"${selected==='Trash'?' selected':''}>Trash</option></select>`; value.outerHTML = ruleFolderSelect(selected);
} else if (value.tagName === 'SELECT') { } else if (value.tagName === 'SELECT') {
value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`; value.outerHTML = `<input class="mail-rule-value" maxlength="200" aria-label="Label" placeholder="Label">`;
} }
@@ -288,7 +317,37 @@ function mailSearchFilters() {
}; };
} }
const selectedDraftIds = new Set();
async function deleteSelectedDrafts() {
const ids = messages.map(message => String(message.id)).filter(id => selectedDraftIds.has(id));
if (!ids.length) { toast('Select one or more drafts first'); return; }
if (!confirm(`Delete ${ids.length} selected draft${ids.length === 1 ? '' : 's'}?`)) return;
try {
for (const id of ids) await window.daybreakMail.deleteDraft(id);
selectedDraftIds.clear();
toast(`${ids.length} draft${ids.length === 1 ? '' : 's'} deleted`);
await syncMailbox(false);
} catch (error) { toast(error.message || 'Could not delete the drafts'); }
}
// In the Drafts folder the shared toolbar acts on drafts, which use string ids.
document.addEventListener('click', event => {
if (activeFolder !== 'Drafts') return;
const button = event.target.closest('#select-all, #delete-selected, #archive-selected, #mark-unread');
if (!button) return;
event.stopImmediatePropagation();
if (button.id === 'select-all') {
const ids = messages.map(message => String(message.id));
const all = ids.length && ids.every(id => selectedDraftIds.has(id));
ids.forEach(id => all ? selectedDraftIds.delete(id) : selectedDraftIds.add(id));
renderDrafts(messages.map(message => message.draft));
} else if (button.id === 'delete-selected') void deleteSelectedDrafts();
}, true);
function renderDrafts(drafts) { function renderDrafts(drafts) {
const present = new Set(drafts.map(draft => String(draft.id)));
[...selectedDraftIds].forEach(id => { if (!present.has(id)) selectedDraftIds.delete(id); });
messages.splice(0, messages.length, ...drafts.map(draft => ({ messages.splice(0, messages.length, ...drafts.map(draft => ({
id: draft.id, id: draft.id,
sender: 'Draft', sender: 'Draft',
@@ -302,14 +361,28 @@ function renderDrafts(drafts) {
draft draft
}))); })));
$('#message-list').innerHTML = messages.length ? messages.map(message => ` $('#message-list').innerHTML = messages.length ? messages.map(message => `
<div class="message" data-id="${esc(message.id)}"><div class="contact-avatar" style="background:${message.color}">${message.initials}</div> <div class="message" data-id="${esc(message.id)}"><input class="row-check" type="checkbox" aria-label="Select draft"${selectedDraftIds.has(String(message.id)) ? ' checked' : ''}><div class="contact-avatar" style="background:${message.color}">${message.initials}</div>
<div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div> <div class="message-body"><div class="sender">${esc(message.email)}</div><div class="subject">${esc(message.subject)}</div><div class="snippet">${esc(message.snippet)}</div></div>
<div class="message-meta"><span class="time">${esc(message.date)}</span></div></div>`).join('') : <div class="message-meta"><span class="time">${esc(message.date)}</span><button type="button" class="icon-button draft-delete" title="Delete draft" aria-label="Delete draft">⌫</button></div></div>`).join('') :
'<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>'; '<div class="reader-empty"><div><div class="empty-icon">✎</div><h3>No saved drafts</h3><p>Drafts are saved on this device and available offline.</p><button class="text-button" id="start-draft">Compose a draft</button></div></div>';
const start = $('#start-draft'); const start = $('#start-draft');
if (start) start.onclick = () => showCompose(); if (start) start.onclick = () => showCompose();
$$('.message').forEach(row => row.onclick = () => { $$('.message').forEach(row => row.onclick = event => {
const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft; const draft = messages.find(message => String(message.id) === row.dataset.id)?.draft;
if (event.target.closest('.row-check')) {
event.stopPropagation();
const id = row.dataset.id;
selectedDraftIds.has(id) ? selectedDraftIds.delete(id) : selectedDraftIds.add(id);
return;
}
if (event.target.closest('.draft-delete')) {
event.stopPropagation();
if (!draft || !confirm('Delete this draft?')) return;
window.daybreakMail.deleteDraft(draft.id)
.then(() => { toast('Draft deleted'); return syncMailbox(false); })
.catch(error => toast(error.message || 'Could not delete the draft'));
return;
}
if (draft) showCompose(null, false, draft); if (draft) showCompose(null, false, draft);
}); });
$('#reader-pane').innerHTML = emptyReader(); $('#reader-pane').innerHTML = emptyReader();
@@ -325,6 +398,83 @@ function setupDraftComposer() {
const modal = root.querySelector('.compose-modal'); const modal = root.querySelector('.compose-modal');
if (!modal) return; if (!modal) return;
modal.dataset.draftId = draft?.id || ''; 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) { if (draft) {
$('#compose-to').value = draft.to || ''; $('#compose-to').value = draft.to || '';
$('#compose-cc').value = draft.cc || ''; $('#compose-cc').value = draft.cc || '';
@@ -347,9 +497,10 @@ function setupDraftComposer() {
to: $('#compose-to').value, to: $('#compose-to').value,
cc: $('#compose-cc').value, cc: $('#compose-cc').value,
subject: $('#compose-subject').value, subject: $('#compose-subject').value,
text: $('#compose-body').value text: $('#compose-body').value,
attachments
}; };
if (!Object.values(values).some(value => typeof value === 'string' && value.trim())) return; if (!Object.values(values).some(value => typeof value === 'string' && value.trim()) && !attachments.length) return;
modal.dataset.draftId = values.id; modal.dataset.draftId = values.id;
const result = await window.daybreakMail.saveDraft(values); const result = await window.daybreakMail.saveDraft(values);
modal.dataset.draftId = result.id; modal.dataset.draftId = result.id;
@@ -595,6 +746,7 @@ if (window.daybreakMail) {
cc: $('#compose-cc').value, cc: $('#compose-cc').value,
subject: $('#compose-subject').value.trim(), subject: $('#compose-subject').value.trim(),
text: $('#compose-body').value, text: $('#compose-body').value,
attachments: $('#modal-root .compose-modal')?._composeAttachments || [],
displayName: connectedMailAccount.displayName || profileSettings.name, displayName: connectedMailAccount.displayName || profileSettings.name,
...(pgp ? { pgp } : {}) ...(pgp ? { pgp } : {})
}); });
+11 -3
View File
@@ -92,7 +92,7 @@ async function pgpUnlockMessage(message, interactive) {
} }
if (result.ok) { if (result.ok) {
Object.assign(message, { Object.assign(message, {
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size, body: result.body, html: result.html, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys } snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
}); });
if (activeMessage === message.id) openMessage(message.id); if (activeMessage === message.id) openMessage(message.id);
@@ -140,7 +140,8 @@ if (typeof showCompose === 'function') {
const encrypt = $('#pgp-encrypt'); const encrypt = $('#pgp-encrypt');
const sign = $('#pgp-sign'); const sign = $('#pgp-sign');
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; } if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
encrypt.addEventListener('change', () => { touched = true; }); if (touched) encrypt.dataset.touched = '1';
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
let timer = null; let timer = null;
const refresh = async () => { const refresh = async () => {
const to = $('#compose-to')?.value || ''; const to = $('#compose-to')?.value || '';
@@ -170,8 +171,15 @@ window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
if (!pgpApi()) return null; if (!pgpApi()) return null;
let encrypt = Boolean($('#pgp-encrypt')?.checked); let encrypt = Boolean($('#pgp-encrypt')?.checked);
const sign = Boolean($('#pgp-sign')?.checked); const sign = Boolean($('#pgp-sign')?.checked);
if (!encrypt && !sign) return null; if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
const status = await pgpApi().checkSend({ to, cc, sign }); const status = await pgpApi().checkSend({ to, cc, sign });
// The default-on update is debounced, so a quick send could skip encryption even though keys exist.
if (!encrypt && !status.missing.length && status.recipients.length && $('#pgp-encrypt')?.dataset.touched !== '1') {
if (confirm('Public keys are available for all recipients.\n\nSend this message WITHOUT encryption?')) {
if (!sign) return null;
} else return false;
}
if (!encrypt && !sign) return null;
if (encrypt && status.missing.length) { if (encrypt && status.missing.length) {
const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`); const sendPlain = confirm(`No public key for ${status.missing.join(', ')}.\n\nThe message cannot be encrypted for everyone. Send it WITHOUT encryption?`);
if (!sendPlain) return false; if (!sendPlain) return false;
+226
View File
@@ -7,9 +7,27 @@ 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"> 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> <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> <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> <h3 class="pgp-heading">Contact public keys</h3>
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div> <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> <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> <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> <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> <div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
@@ -26,6 +44,15 @@ function openEncryptionKeys() {
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
const status = message => { $('#pgp-status').textContent = message; }; const status = message => { $('#pgp-status').textContent = message; };
const passphraseField = () => $('#pgp-passphrase'); 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 needPassphrase = () => {
const value = passphraseField().value; const value = passphraseField().value;
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); } if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
@@ -55,6 +82,44 @@ function openEncryptionKeys() {
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false], ['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true] ['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]); if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
actions.push(['Delete', async () => { 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 }; if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
@@ -75,8 +140,28 @@ function openEncryptionKeys() {
}; };
row.append(button); 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); list.append(row);
}); });
updatePublishButtons();
} }
$('#pgp-generate').onclick = async () => { $('#pgp-generate').onclick = async () => {
@@ -166,12 +251,153 @@ function openEncryptionKeys() {
await renderContacts(); await renderContacts();
} catch (error) { status(error.message || 'Could not import the key.'); } } 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(() => {}); window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
$('#pgp-save-cache').onclick = async () => { $('#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).`); } 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.'); } catch (error) { status(error.message || 'Could not save the setting.'); }
}; };
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); }; $('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
void renderKeyServers();
void renderContacts(); void renderContacts();
void render(); void render();
} }
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE='ep-mail-v7'; const CACHE='ep-mail-v8';
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']; 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('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)))))); self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
+5
View File
@@ -136,3 +136,8 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
.pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px} .pgp-banner button,.pgp-status button{align-self:flex-start;margin-top:6px}
.pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8} .pgp-compose{display:flex;align-items:center;gap:12px;margin-right:auto;font-size:13px}.pgp-compose label{display:flex;align-items:center;gap:4px}.pgp-compose small{opacity:.8}
.pgp-trust{margin-left:8px} .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}