Compare commits
14
Commits
V0.2.0
...
04cd4117fe
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04cd4117fe | ||
|
|
a9c52e7868 | ||
|
|
20d58feb9c | ||
|
|
e34f3dc911 | ||
|
|
9adbce6a32 | ||
|
|
5769238a80 | ||
|
|
17ca5f0fa7 | ||
|
|
592b83fc73 | ||
|
|
edf7cec93e | ||
|
|
750665f96b | ||
|
|
bae9c7966d | ||
|
|
b9e2f7fa30 | ||
|
|
5529a8f18f | ||
|
|
63ee146719 |
+116
@@ -0,0 +1,116 @@
|
||||
# Architecture
|
||||
|
||||
This project has a layered architecture: a desktop Electron shell, a browser-rendered mail interface, platform-specific storage and sync adapters, and a separate Android Capacitor wrapper. The design keeps user state and credentials in the OS keyring, pushes IMAP/SMTP work into the main process, and exposes only a narrow IPC surface to the renderer.
|
||||
|
||||
## 1. Runtime layout
|
||||
|
||||
### Desktop shell
|
||||
|
||||
- `desktop/main.cjs` is the privileged process.
|
||||
- It owns account storage, mail sync, IMAP/SMTP connectivity, DAV sync, and OpenPGP key handling.
|
||||
- It can show native dialogs, notifications, and system prompts.
|
||||
- `desktop/preload.cjs` exposes a minimal API to the renderer through `window.daybreakMail` and `window.pgpPrepareSend`.
|
||||
|
||||
### Renderer UI
|
||||
|
||||
The browser UI is rendered from the web assets in the root and `www/` folders:
|
||||
|
||||
- `index.html` and the shared shell files define the layout and global state.
|
||||
- `app.js`, `mail-ui.js`, `account-ui.js`, `dav-ui.js`, `pgp-ui.js`, and `pgp-mail-ui.js` handle page flow, compose/read views, account setup, and encryption UX.
|
||||
- The renderer is intentionally thin: it requests actions and displays data, but the actual cryptographic and network work stays in the main process.
|
||||
|
||||
### Android client
|
||||
|
||||
The Android app reuses the web UI in a Capacitor shell (`android/`, `capacitor.config.json`).
|
||||
|
||||
- The same browser UI runs inside the Android app.
|
||||
- Native Android services handle background sync, notification behavior, and secure storage.
|
||||
- The desktop and Android implementations intentionally share the same mail and account model so the feature surface stays aligned.
|
||||
|
||||
## 2. Core responsibilities
|
||||
|
||||
### Mail and account state
|
||||
|
||||
The main process owns the canonical account model and persists it in an encrypted store:
|
||||
|
||||
- `mail-account.enc` stores connected IMAP/SMTP accounts and their settings.
|
||||
- `dav-accounts.enc` stores CalDAV/CardDAV credentials and server config.
|
||||
- `pgp-keys.enc` stores OpenPGP keys and trust data.
|
||||
|
||||
All three stores are wrapped with Electron `safeStorage` where available. Linux checks explicitly reject the insecure `basic_text` backend before credentials or keys are persisted.
|
||||
|
||||
### Mail sync pipeline
|
||||
|
||||
The desktop app follows a background sync model:
|
||||
|
||||
1. The renderer asks the main process for a folder sync or inbox refresh.
|
||||
2. The main process opens an IMAP connection and fetches only the requested subset or page.
|
||||
3. Sync results are written back into the account state and sent to the renderer via IPC (`mail:sync-update`).
|
||||
4. Periodic background sync and IDLE watchers reduce polling and keep new-mail notifications timely.
|
||||
|
||||
A generation counter invalidates stale sync jobs when accounts are edited or removed, and concurrent syncs are prevented to avoid overlapping IMAP traffic.
|
||||
|
||||
### Message send path
|
||||
|
||||
The send flow is also centralized in the main process:
|
||||
|
||||
- the renderer calls `mail:send`
|
||||
- the main process resolves the account, checks the sender settings, and applies OpenPGP encryption/signing before sending
|
||||
- the message is either transmitted immediately or queued as an offline send when connectivity is unavailable
|
||||
|
||||
This prevents the renderer from silently bypassing critical security checks or storing plaintext in outbox data.
|
||||
|
||||
## 3. Security boundary
|
||||
|
||||
The current architecture takes a strict trust split:
|
||||
|
||||
- renderer: UI, user interaction, local conveniences
|
||||
- main process: network access, cryptographic operations, permission prompts, OS secure storage
|
||||
|
||||
This boundary is important for encryption and safety checks:
|
||||
|
||||
- OpenPGP key selection and trust updates are confirmed in the main process.
|
||||
- Key-server lookup results never elevate trust; only the public key is sent during a separately confirmed publication.
|
||||
- Send-time downgrade checks happen in the main process rather than only in UI logic.
|
||||
- External links open only after a native confirmation dialog.
|
||||
- Credentials and private keys are stored with the OS keyring, not in plain JSON files.
|
||||
|
||||
## 4. OpenPGP subsystem
|
||||
|
||||
The OpenPGP implementation is split into focused modules:
|
||||
|
||||
- `desktop/pgp-keystore.cjs` stores contacts, trust, key material, and settings.
|
||||
- `desktop/pgp-mail.cjs` handles message detection, decryption, verification, encryption, and signature checks.
|
||||
- `desktop/pgp-keyservers.cjs` implements bounded HTTPS lookup and publication for VKS and HKP-compatible servers.
|
||||
- `desktop/main.cjs` bridges those services into the Electron IPC API.
|
||||
|
||||
This keeps the cryptographic logic separate from the UI and gives the app a single place to enforce trust rules, passphrase checks, and recipient validation.
|
||||
|
||||
Key-server searches and publication requests are initiated from Settings and resolved by the main process. The renderer selects a configured server by ID rather than supplying an arbitrary request URL. 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 for each publication.
|
||||
|
||||
## 5. Data flow patterns
|
||||
|
||||
- Account setup and edits flow from the UI into IPC, then into the encrypted main-process storage.
|
||||
- Mail content is fetched by the main process and served to the renderer in a sanitized, parsed form.
|
||||
- Attachments, decrypted bodies, and external links are all checked before user-visible actions are allowed.
|
||||
- Search, folder listing, and draft operations reuse the same account model across both desktop and Android versions.
|
||||
|
||||
## 6. Release and packaging model
|
||||
|
||||
The project packages multiple platforms from the same codebase:
|
||||
|
||||
- `npm run dist:win` for Windows installer/portable builds
|
||||
- `npm run dist:linux` for Linux AppImage and Debian builds
|
||||
- Android builds via Capacitor (`npm run android:apk`)
|
||||
|
||||
The app version is managed through package metadata and the Electron build config in `package.json`.
|
||||
|
||||
## 7. Key architectural principles
|
||||
|
||||
- Keep privileged operations in the main process.
|
||||
- Keep security rules in trusted code rather than the UI.
|
||||
- Store secrets in OS-backed secure storage whenever the platform supports it.
|
||||
- Share the same account and sync model between desktop and Android where possible.
|
||||
- Treat mail encryption and secure key handling as first-class product features, not optional extras.
|
||||
|
||||
This architecture is intentionally built for a mail client that must handle privacy-sensitive data, background sync, and cross-platform parity without exposing the network or crypto stack to the renderer.
|
||||
@@ -0,0 +1,99 @@
|
||||
# Encryption plan: OpenPGP mail encryption for ep-mail
|
||||
|
||||
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)
|
||||
|
||||
| Option | Pros | Cons |
|
||||
|---|---|---|
|
||||
| **OpenPGP** | Interoperates with Thunderbird, Proton, Mailvelope, GnuPG and K-9/OpenKeychain. No certificate authority needed. | Key verification is manual. |
|
||||
| S/MIME | Native in Outlook and Apple Mail. | Needs CA-issued certificates; poor fit for personal accounts. |
|
||||
|
||||
Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
|
||||
- Library: [OpenPGP.js](https://github.com/openpgpjs/openpgpjs) (`openpgp`), pure JS, usable in Electron and the Android WebView.
|
||||
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
|
||||
- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used.
|
||||
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
|
||||
- Out of scope for v1: Autocrypt headers and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
|
||||
|
||||
## 2. Key handling
|
||||
|
||||
**Private keys**
|
||||
- One or more keys per account; never stored unprotected and never sent anywhere.
|
||||
- Always protected by a passphrase (minimum 8 characters). On desktop the whole key store is also encrypted with Electron `safeStorage` (the OS credential store).
|
||||
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4).
|
||||
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk.
|
||||
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
|
||||
- Deleting or exporting a private key requires the passphrase.
|
||||
|
||||
**Public keys**
|
||||
- Per-account contact keyring: address, fingerprint, trust level, source.
|
||||
- Sources: file import, attached to received mail, key-server lookup, and own key attached to outgoing mail.
|
||||
- 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
|
||||
|
||||
- Compose: lock toggle, on by default when every recipient has a key. Never silently downgrade; offer to send unencrypted or cancel.
|
||||
- Reader: status line such as "Encrypted and signed by X (verified)" or a warning for bad/unknown signatures.
|
||||
- Message list: lock icon for encrypted mail.
|
||||
- Settings: **Encryption keys** (Phase 1) for create, import, export, delete.
|
||||
- Interactions: search and rules cannot read encrypted bodies (subject/sender stay plaintext); do not cache decrypted bodies; run link warnings and attachment previews only after decryption; encrypt the Sent copy to the sender's own key too.
|
||||
|
||||
## 4. Threat model and limits
|
||||
|
||||
- Protects content from the mail server and network observers.
|
||||
- Does not protect metadata (sender, recipients, subject, timestamps).
|
||||
- A compromised device, or a stolen key plus passphrase, defeats it.
|
||||
- Losing the key means losing access to old encrypted mail; backups are the user's responsibility.
|
||||
|
||||
## 5. Phases
|
||||
|
||||
| Phase | Scope | Status |
|
||||
|---|---|---|
|
||||
| 1 | Foundation: OpenPGP.js, passphrase-protected key store (OS credential store on desktop), generate/import/export/delete, revocation certificate, unit tests, Settings UI | 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) |
|
||||
| 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, GnuPG and manual Thunderbird interop checks done |
|
||||
| 6 | Docs, security review, release | Docs and release done; independent review open |
|
||||
|
||||
## 6. Phase 1 implementation notes
|
||||
|
||||
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): platform-independent key store with an injected storage backend.
|
||||
- [desktop/main.cjs](./desktop/main.cjs): wraps the store with `safeStorage` (`pgp-keys.enc` in the user data folder) and exposes `pgp:*` IPC handlers; key files are saved through native dialogs.
|
||||
- [desktop/preload.cjs](./desktop/preload.cjs): exposes `daybreakMail.pgp`.
|
||||
- [pgp-ui.js](./pgp-ui.js): Settings → **Encryption keys**. Hidden on platforms without a key store (Android until Phase 4).
|
||||
- Tests: `npm test` ([tests/pgp-keystore.test.cjs](./tests/pgp-keystore.test.cjs)).
|
||||
|
||||
## 7. Phases 2–5 implementation notes
|
||||
|
||||
- [desktop/pgp-mail.cjs](./desktop/pgp-mail.cjs): detects PGP/MIME and inline PGP, decrypts, verifies signatures (inside encrypted mail, `multipart/signed` and cleartext), builds encrypted/signed PGP/MIME messages, and keeps an in-memory passphrase cache.
|
||||
- [desktop/pgp-keystore.cjs](./desktop/pgp-keystore.cjs): also stores contact public keys with trust levels (`unknown`, `trusted`, `verified`) and the passphrase-memory setting.
|
||||
- Encrypted messages appear in the list as "Encrypted message"; they are decrypted on demand (`pgp:decrypt-message`) and the plaintext is never cached on disk. Attachments are read from the decrypted payload.
|
||||
- Compose shows Encrypt and Sign options. Encrypt turns on by default when every recipient has a key; if a key is missing the app asks before sending unencrypted. Encryption happens before the message is sent or queued offline, so passphrases and plaintext never enter the outbox. The Sent copy is also encrypted to the sender's own key.
|
||||
- A signature from a key that differs from the one on file for the sender is flagged as a changed key.
|
||||
- Interop: [tests/pgp-gnupg-interop.test.cjs](./tests/pgp-gnupg-interop.test.cjs) runs against a real GnuPG (skipped when it is not installed).
|
||||
- Tests: [tests/pgp-mail.test.cjs](./tests/pgp-mail.test.cjs) (round trips, several recipients, tampering, key changes, large attachments, inline PGP).
|
||||
- Limits: subjects and headers are not encrypted; drafts are stored unencrypted; opening encrypted attachments requires the passphrase to be remembered (see Settings → Encryption keys).
|
||||
## 8. Risks
|
||||
|
||||
- Android WebView performance with large attachments (may need native handling).
|
||||
- Key loss (backup flow, revocation certificate).
|
||||
- User confusion about trust; keep states simple: unknown, trusted, verified.
|
||||
- Decrypted HTML must not leak through remote content; blocking remote images by default should land first.
|
||||
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
|
||||
|
||||
## 9. Public key servers (desktop)
|
||||
|
||||
The desktop Settings → Encryption keys view can search and publish through:
|
||||
|
||||
- **keys.openpgp.org** using its [VKS API](https://keys.openpgp.org/about/api/). Email lookup only returns keys whose email addresses have been verified. After an upload, ep-mail requests verification for the key's primary email address and reports whether verification is pending or already complete.
|
||||
- **keys.mailvelope.com** using HKP over HTTPS as documented by the [Mailvelope key server](https://github.com/mailvelope/keyserver#hkp-api). The server sends its own email-verification message after accepting a key upload.
|
||||
- **Custom servers** using an explicitly selected HKP or VKS protocol and an HTTPS base URL. Custom server configuration is saved with the encrypted OpenPGP settings.
|
||||
|
||||
Searching is user-triggered; ep-mail does not perform background lookups while composing. Search addresses are disclosed to the selected server. 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.
|
||||
|
||||
Every publication requires a native confirmation that identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is not included because Android OpenPGP support is not implemented.
|
||||
|
||||
Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key.
|
||||
@@ -8,6 +8,8 @@ The Electron app runs in its own window. With Node.js installed, run `npm instal
|
||||
|
||||
The `.github/workflows/desktop-build.yml` workflow builds both Windows and Linux artifacts on their native GitHub-hosted runners when manually started from the Actions tab. Snoozed messages return to their original mailbox with a reminder; desktop reminders are checked while the app is running, and Android uses its periodic background worker.
|
||||
|
||||
See the project architecture overview in [ARCHITECTURE.md](./ARCHITECTURE.md).
|
||||
|
||||
## Android app
|
||||
|
||||
The Android app reuses the web interface in a Capacitor shell and implements mail, DAV, secure account storage, and background sync with native Android services. Per-account signatures, notification preferences, and incoming-mail rules are respected; configured sync intervals apply to IDLE fallback polling, while Android's periodic background worker has a 15-minute platform minimum. Recent message content, drafts, and queued actions/sends are stored in the encrypted Android account vault for offline access and retry. Search filters use the same criteria and online scan limit as desktop. Install Node.js, Android Studio with the Android SDK, and JDK 21. Set `JAVA_HOME` and `ANDROID_HOME` if they are not configured by Android Studio, then run:
|
||||
@@ -31,4 +33,4 @@ On Windows, `py -m http.server 8000` is also available on many Python installati
|
||||
|
||||
## Current scope
|
||||
|
||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder.
|
||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. CalDAV and CardDAV servers can be added from the Calendar and Contacts views; credentials are kept in the OS-encrypted credential store, and events and contacts can sync and be edited on the server. Local contacts and events remain available without a DAV connection. Your display name is saved locally and appears in the greeting. Use the **+** beside **Folders** in the sidebar to create IMAP folders on the server; your custom folders appear in the sidebar and can be opened like any other folder. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys stored encrypted by the operating system; you can import contact keys, discover keys through keys.openpgp.org and keys.mailvelope.com or configured HTTPS HKP/VKS servers, and publish public keys after a per-action native confirmation. 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`.
|
||||
|
||||
@@ -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,8 +15,8 @@
|
||||
- [x] Improve mail search with sender, subject, date, folder, and attachment filters.
|
||||
- [x] Cache recent messages and save drafts offline; queue supported sends and message actions for retry when connectivity returns.
|
||||
- [ ] Group related messages into conversations, with controls to expand or collapse threads.
|
||||
- [ ] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
||||
- [ ] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
|
||||
- [x] Add attachment previews and a dedicated view to find and manage attachments across mailboxes.
|
||||
- [x] Add configurable keyboard shortcuts for common actions such as compose, archive, reply, and search.
|
||||
- [x] Warn about suspicious sender addresses and links; require confirmation before opening external links.
|
||||
- [x] Add per-account rules to sort, archive, label, or flag new incoming messages by sender and/or subject.
|
||||
- [x] Add per-account signatures, notification preferences, and sync settings.
|
||||
@@ -25,7 +25,17 @@
|
||||
|
||||
## Mail security
|
||||
|
||||
- [ ] Add support for encrypting and decrypting mail with private/public keys or a suitable standard. Decide on the encryption format, key storage and exchange flow, and compatibility requirements before implementation.
|
||||
- [ ] Add support for encrypting and decrypting mail with OpenPGP (PGP/MIME). See [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md).
|
||||
- [x] Phase 1: foundation — OpenPGP.js, passphrase-protected key store (desktop), generate/import/export/delete keys, revocation certificate, tests, Settings UI.
|
||||
- [x] Phase 2: receive — detect PGP/MIME and inline PGP mail, decrypt on open, verify signatures, show encryption/signature status, handle missing keys and wrong passphrases.
|
||||
- [x] Phase 3: send — public-key keyring and key import from contacts/messages, encrypt and sign when composing, encrypted copy in Sent, warn instead of silently downgrading.
|
||||
- [x] Phase 4 (desktop): trust levels and fingerprint verification, key-change warnings, passphrase cache timeout.
|
||||
- [ ] Phase 4 (Android): Android Keystore key storage, biometric unlock, and the reading/sending bridge (encryption is desktop-only until then).
|
||||
- [x] Phase 5 (automated): large attachments, multiple recipients, corrupted/tampered payloads, inline PGP and PGP/MIME tests.
|
||||
- [x] Phase 5 (GnuPG): automated interoperability tests with GnuPG 2.5 (both directions: PGP/MIME, inline, clear-signed, detached signatures).
|
||||
- [x] Phase 6: documentation and release.
|
||||
- [x] Manual interoperability check with Thunderbird.
|
||||
- [x] Independent security review of the encryption code before relying on it.
|
||||
|
||||
## Appearance and settings
|
||||
|
||||
@@ -50,3 +60,14 @@
|
||||
- [x] Keep general Settings focused on appearance and other app-wide preferences rather than the display name.
|
||||
- [x] Display name must be set per account.
|
||||
- [x] Remove the display name initials from the bottom-left corner.
|
||||
- [x] Add the ability to delete draft mails.
|
||||
- [x] Fix IMAP folder creation, which does not work.
|
||||
- [ ] Give the sidebar (Inbox, Folders, etc.) more room so every item fits on screen: make the box scrollable with a slider, or remove or collapse less-used items.
|
||||
- [ ] Make labels work and add the ability to create more labels.
|
||||
- [x] Fix created IMAP folders not showing in the mail rules folder list; only Inbox, Archive and Trash are shown.
|
||||
- [x] Fix draft mail deletion to work like the Inbox: select multiple drafts and delete the selected drafts at once.
|
||||
- [x] Show created IMAP folders in the same list as Inbox and the other folders, and move the folder list and the add-folder button to the top row above Inbox. Add scrolling to the IMAP folders area.
|
||||
- [x] Add desktop public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKP over HTTPS), and user-defined HTTPS HKP/VKS servers. Discovered keys remain unverified until fingerprint verification.
|
||||
- [ ] Add the ability to attach files to outgoing mails.
|
||||
- [x] Fix security review findings: confirm key replacement in the main process, enforce the plaintext-send check in the main process, and handle the Linux safeStorage basic_text backend. See SECURITY_REVIEW.md.
|
||||
- [ ] Add the ability to change the passphrase of an encryption key.
|
||||
|
||||
@@ -345,6 +345,40 @@ internal object AndroidMailService {
|
||||
}
|
||||
}
|
||||
|
||||
fun previewAttachment(account: JSONObject, input: JSONObject): JSONObject =
|
||||
withStore(account) { _, store ->
|
||||
val folder = resolveFolder(store, input.optString("folder", "Inbox"))
|
||||
?: throw IllegalStateException("That mail folder could not be found.")
|
||||
folder.open(Folder.READ_ONLY)
|
||||
try {
|
||||
val message = (folder as? UIDFolder)?.getMessageByUID(input.optLong("uid"))
|
||||
?: throw IllegalStateException("The message is no longer available.")
|
||||
val filename = input.optString("filename")
|
||||
val part = findAttachment(message, filename)
|
||||
?: throw IllegalStateException("No attachment was found in this message.")
|
||||
val mimeType = part.contentType.substringBefore(';').trim().lowercase(Locale.ROOT)
|
||||
val none = JSONObject().put("kind", "none")
|
||||
.put("reason", "No preview is available for this file type. Download it to open it.")
|
||||
if (Regex("image/(png|jpe?g|gif|webp|bmp|svg\\+xml)").matches(mimeType)) {
|
||||
val bytes = part.inputStream.use { it.readBytes() }
|
||||
if (bytes.size > 5 * 1048576) {
|
||||
none.put("reason", "This image is too large to preview. Download it instead.")
|
||||
} else {
|
||||
JSONObject().put("kind", "image").put(
|
||||
"dataUrl", "data:$mimeType;base64," + android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP)
|
||||
)
|
||||
}
|
||||
} else if (mimeType.startsWith("text/") || mimeType == "application/json" || mimeType == "application/xml") {
|
||||
val bytes = part.inputStream.use { it.readBytes() }
|
||||
JSONObject().put("kind", "text")
|
||||
.put("text", String(bytes.copyOf(minOf(bytes.size, 100000)), Charsets.UTF_8))
|
||||
.put("truncated", bytes.size > 100000)
|
||||
} else none
|
||||
} finally {
|
||||
folder.close(false)
|
||||
}
|
||||
}
|
||||
|
||||
fun checkForNewMail(account: JSONObject): Int {
|
||||
flushOutbox(account)
|
||||
return withStore(account) { _, store ->
|
||||
|
||||
@@ -248,6 +248,17 @@ class EpMailPlugin : Plugin() {
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun previewAttachment(call: PluginCall) {
|
||||
try {
|
||||
val account = AndroidAccountVault.account()
|
||||
?: throw IllegalStateException("Add a mail account before previewing attachments.")
|
||||
call.resolve(AndroidMailService.previewAttachment(account, JSONObject(call.data.toString())).toJSObject())
|
||||
} catch (error: Exception) {
|
||||
call.reject(error.message ?: "Could not preview the attachment.")
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod
|
||||
fun openExternal(call: PluginCall) {
|
||||
val raw = call.getString("url").orEmpty()
|
||||
@@ -486,8 +497,8 @@ class EpMailPlugin : Plugin() {
|
||||
require(action != "move" || !value.any { it == '\r' || it == '\n' || it == '\u0000' }) {
|
||||
"Mail rule ${index + 1} has an invalid destination folder."
|
||||
}
|
||||
require(action != "move" || value in setOf("Inbox", "Archive", "Trash")) {
|
||||
"Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash."
|
||||
require(action != "move" || value in setOf("Inbox", "Archive", "Trash") || AndroidMailService.isCustomFolder(value)) {
|
||||
"Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders."
|
||||
}
|
||||
result.put(JSONObject()
|
||||
.put("id", rule.optString("id").ifBlank { UUID.randomUUID().toString() })
|
||||
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||
let attachmentItems = [];
|
||||
|
||||
function attachmentKind(filename) {
|
||||
const ext = String(filename).toLowerCase().split('.').pop();
|
||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||
return 'Other';
|
||||
}
|
||||
|
||||
function attachmentSize(size) {
|
||||
if (!size) return '';
|
||||
if (typeof size === 'string') return size;
|
||||
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
async function previewAttachment(target, details) {
|
||||
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||
return;
|
||||
}
|
||||
target.textContent = 'Loading preview…';
|
||||
try {
|
||||
const result = await window.daybreakMail.previewAttachment(details);
|
||||
target.replaceChildren();
|
||||
if (result.kind === 'image') {
|
||||
const image = document.createElement('img');
|
||||
image.className = 'attachment-preview-image';
|
||||
image.alt = details.filename;
|
||||
image.src = result.dataUrl;
|
||||
target.append(image);
|
||||
} else if (result.kind === 'text') {
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'attachment-preview-text';
|
||||
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||
target.append(pre);
|
||||
} else {
|
||||
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||
}
|
||||
} catch (error) {
|
||||
target.textContent = error.message || 'Could not load the preview.';
|
||||
}
|
||||
}
|
||||
|
||||
function downloadAttachment(details) {
|
||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
|
||||
window.daybreakMail.saveAttachment(details)
|
||||
.then(result => { if (result.saved) toast('Attachment saved'); })
|
||||
.catch(error => toast(error.message || 'Could not save attachment'));
|
||||
}
|
||||
|
||||
// Add a Preview button to each attachment in the reader.
|
||||
if (typeof openMessage === 'function') {
|
||||
const baseOpenMessage = openMessage;
|
||||
openMessage = function (id) {
|
||||
baseOpenMessage(id);
|
||||
const message = messages.find(item => item.id === id);
|
||||
if (!message?.uid) return;
|
||||
$$('#reader-pane .attachment').forEach(row => {
|
||||
const download = row.querySelector('.download');
|
||||
if (!download || row.querySelector('.preview-attachment')) return;
|
||||
const button = document.createElement('button');
|
||||
button.className = 'preview-attachment icon-button';
|
||||
button.title = 'Preview';
|
||||
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||
button.textContent = '👁';
|
||||
button.addEventListener('click', event => {
|
||||
event.stopPropagation();
|
||||
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||
if (panel) { panel.remove(); return; }
|
||||
panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
row.after(panel);
|
||||
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
||||
});
|
||||
download.before(button);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async function collectAttachments() {
|
||||
const items = [];
|
||||
for (const folder of attachmentFolders) {
|
||||
let offset = 0;
|
||||
for (let page = 0; page < 5; page += 1) {
|
||||
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||
for (const message of result.messages || []) {
|
||||
for (const file of message.attachments || []) {
|
||||
items.push({
|
||||
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||
kind: attachmentKind(file.filename)
|
||||
});
|
||||
}
|
||||
}
|
||||
offset += (result.messages || []).length;
|
||||
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||
}
|
||||
}
|
||||
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||
}
|
||||
|
||||
async function openAttachmentsView() {
|
||||
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
||||
const root = $('#modal-root');
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
root.querySelector('.modal-close').onclick = close;
|
||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||
const list = $('#attachment-list');
|
||||
const render = () => {
|
||||
const text = $('#attachment-search').value.trim().toLowerCase();
|
||||
const type = $('#attachment-type').value;
|
||||
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||
list.replaceChildren();
|
||||
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||
shown.forEach(item => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'attachment-row';
|
||||
const info = document.createElement('div');
|
||||
info.className = 'attachment-row-info';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = item.filename;
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||
info.append(name, meta);
|
||||
const preview = document.createElement('button');
|
||||
preview.className = 'discard';
|
||||
preview.textContent = 'Preview';
|
||||
const save = document.createElement('button');
|
||||
save.className = 'discard';
|
||||
save.textContent = 'Download';
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
panel.hidden = true;
|
||||
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||
preview.onclick = () => {
|
||||
panel.hidden = !panel.hidden;
|
||||
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||
};
|
||||
save.onclick = () => downloadAttachment(details);
|
||||
row.append(info, preview, save, panel);
|
||||
list.append(row);
|
||||
});
|
||||
};
|
||||
$('#attachment-search').oninput = render;
|
||||
$('#attachment-type').onchange = render;
|
||||
try {
|
||||
attachmentItems = await collectAttachments();
|
||||
if ($('#attachment-list')) render();
|
||||
} catch (error) {
|
||||
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||
});
|
||||
+428
-18
@@ -7,6 +7,8 @@ const { simpleParser } = require('mailparser');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { createDAVClient } = require('tsdav');
|
||||
const ICAL = require('ical.js');
|
||||
const openpgp = require('openpgp');
|
||||
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
|
||||
|
||||
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
|
||||
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
||||
@@ -193,8 +195,37 @@ async function reconcileIdleWatchers() {
|
||||
for (const account of desiredAccounts) startIdleWatcher(account);
|
||||
}
|
||||
|
||||
const { createKeyStore } = require('./pgp-keystore.cjs');
|
||||
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
|
||||
|
||||
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
|
||||
const pgpKeys = createKeyStore({
|
||||
async load() {
|
||||
try {
|
||||
assertSecureStorage();
|
||||
const { result } = await safeStorage.decryptStringAsync(await fs.readFile(pgpKeysPath()));
|
||||
return JSON.parse(result);
|
||||
} catch (error) {
|
||||
if (error.code === 'ENOENT') return { keys: [] };
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
async save(data) {
|
||||
assertSecureStorage();
|
||||
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.');
|
||||
await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true });
|
||||
await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 });
|
||||
await fs.rename(`${pgpKeysPath()}.tmp`, pgpKeysPath());
|
||||
}
|
||||
});
|
||||
|
||||
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
|
||||
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
|
||||
const pgpKeyServers = createKeyServerService();
|
||||
|
||||
async function readDavStore() {
|
||||
try {
|
||||
assertSecureStorage();
|
||||
const encrypted = await fs.readFile(davCredentialsPath());
|
||||
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
||||
return JSON.parse(result);
|
||||
@@ -205,6 +236,7 @@ async function readDavStore() {
|
||||
}
|
||||
|
||||
async function saveDavStore(store) {
|
||||
assertSecureStorage();
|
||||
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure credential storage is unavailable.');
|
||||
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
|
||||
await fs.mkdir(path.dirname(davCredentialsPath()), { recursive: true });
|
||||
@@ -269,8 +301,8 @@ function normalizeAccount(input) {
|
||||
if ((action === 'move' || action === 'label') && !value) {
|
||||
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
|
||||
}
|
||||
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value)) {
|
||||
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, or Trash.`);
|
||||
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, Trash, or one of your folders.`);
|
||||
}
|
||||
return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value };
|
||||
});
|
||||
@@ -315,9 +347,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() {
|
||||
try {
|
||||
if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.');
|
||||
assertSecureStorage();
|
||||
const encrypted = await fs.readFile(credentialsPath());
|
||||
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
||||
const stored = JSON.parse(result);
|
||||
@@ -336,6 +378,7 @@ async function readAccountStore() {
|
||||
}
|
||||
|
||||
async function saveAccountStore(store) {
|
||||
assertSecureStorage();
|
||||
if (!await safeStorage.isAsyncEncryptionAvailable()) {
|
||||
throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.');
|
||||
}
|
||||
@@ -538,14 +581,14 @@ async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, f
|
||||
async function toUiMessage(item, folder) {
|
||||
const parsed = await simpleParser(item.source);
|
||||
const sender = parsed.from?.value?.[0];
|
||||
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
|
||||
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
|
||||
const pgpKind = pgpMail.detect(parsed);
|
||||
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
|
||||
const content = encrypted
|
||||
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
|
||||
: mailContent(parsed);
|
||||
const { bodyText, body, links } = content;
|
||||
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
|
||||
const date = parsed.date || item.internalDate || new Date();
|
||||
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
|
||||
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
|
||||
.map(match => (match[1] || match[2] || match[3] || '').replace(/&/gi, '&').replace(///gi, '/'))
|
||||
.filter(Boolean)
|
||||
.slice(0, 30);
|
||||
return {
|
||||
id: Number(item.uid),
|
||||
initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(),
|
||||
@@ -553,7 +596,9 @@ async function toUiMessage(item, folder) {
|
||||
sender: sender?.name || sender?.address || 'Unknown sender',
|
||||
email: sender?.address || '',
|
||||
subject: parsed.subject || '(no subject)',
|
||||
snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
||||
snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180),
|
||||
encrypted,
|
||||
pgpSignatures,
|
||||
time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date),
|
||||
date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date),
|
||||
timestamp: date.getTime(),
|
||||
@@ -567,9 +612,28 @@ async function toUiMessage(item, folder) {
|
||||
body,
|
||||
links,
|
||||
uid: Number(item.uid),
|
||||
attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
||||
attachment: parsed.attachments?.[0]?.filename || null,
|
||||
size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : ''
|
||||
attachments: content.attachments,
|
||||
attachment: content.attachment,
|
||||
size: content.size
|
||||
};
|
||||
}
|
||||
|
||||
function mailContent(parsed) {
|
||||
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
|
||||
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
|
||||
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
|
||||
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
|
||||
.map(match => (match[1] || match[2] || match[3] || '').replace(/&/gi, '&').replace(///gi, '/'))
|
||||
.filter(Boolean)
|
||||
.slice(0, 30);
|
||||
const files = (parsed.attachments || []).filter(file => !/^application\/pgp-(signature|encrypted)/i.test(file.contentType || ''));
|
||||
return {
|
||||
bodyText,
|
||||
body,
|
||||
links,
|
||||
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
|
||||
attachment: files[0]?.filename || null,
|
||||
size: files[0]?.size ? `${(files[0].size / 1048576).toFixed(1)} MB` : ''
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1137,6 +1201,18 @@ ipcMain.handle('mail:update-message', async (_event, input) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Encrypted messages keep their attachments inside the encrypted payload.
|
||||
async function parseForAttachments(source) {
|
||||
const parsed = await simpleParser(source);
|
||||
const kind = pgpMail.detect(parsed);
|
||||
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed;
|
||||
try {
|
||||
return (await pgpMail.decrypt(parsed)).parsed;
|
||||
} catch (error) {
|
||||
if (error instanceof PgpError) throw new Error(error.code === 'PASSPHRASE_REQUIRED' ? 'Open the message and unlock it before using its attachments.' : error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
ipcMain.handle('mail:save-attachment', async (event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before downloading attachments.');
|
||||
@@ -1154,7 +1230,7 @@ ipcMain.handle('mail:save-attachment', async (event, input) => {
|
||||
try {
|
||||
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
||||
if (!item?.source) throw new Error('The message is no longer available.');
|
||||
const parsed = await simpleParser(item.source);
|
||||
const parsed = await parseForAttachments(item.source);
|
||||
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename) || parsed.attachments?.[0];
|
||||
if (!attachment) throw new Error('No attachment was found in this message.');
|
||||
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_') });
|
||||
@@ -1169,6 +1245,294 @@ ipcMain.handle('mail:save-attachment', async (event, input) => {
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('mail:preview-attachment', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before previewing attachments.');
|
||||
const uid = Number(input?.uid);
|
||||
const folder = String(input?.folder || 'Inbox');
|
||||
const filename = String(input?.filename || 'attachment');
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const mailboxPath = await folderPath(client, folder);
|
||||
if (!mailboxPath) throw new Error('That mail folder could not be found.');
|
||||
const lock = await client.getMailboxLock(mailboxPath);
|
||||
try {
|
||||
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
||||
if (!item?.source) throw new Error('The message is no longer available.');
|
||||
const parsed = await parseForAttachments(item.source);
|
||||
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename);
|
||||
if (!attachment) throw new Error('No attachment was found in this message.');
|
||||
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
|
||||
const size = attachment.content.length;
|
||||
if (/^image\/(png|jpe?g|gif|webp|bmp|svg\+xml)$/.test(mimeType)) {
|
||||
if (size > 5 * 1048576) return { kind: 'none', reason: 'This image is too large to preview. Download it instead.' };
|
||||
return { kind: 'image', dataUrl: `data:${mimeType};base64,${attachment.content.toString('base64')}` };
|
||||
}
|
||||
if (mimeType.startsWith('text/') || ['application/json', 'application/xml'].includes(mimeType)) {
|
||||
return { kind: 'text', text: attachment.content.subarray(0, 100000).toString('utf8'), truncated: size > 100000 };
|
||||
}
|
||||
return { kind: 'none', reason: 'No preview is available for this file type. Download it to open it.' };
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('pgp:list', () => pgpKeys.list());
|
||||
ipcMain.handle('pgp:generate', (_event, input) => pgpKeys.generate({
|
||||
name: input?.name, email: input?.email, passphrase: input?.passphrase, accountId: input?.accountId || null
|
||||
}));
|
||||
ipcMain.handle('pgp:import', async (event, input) => {
|
||||
let armoredKey = input?.armoredKey;
|
||||
if (!armoredKey) {
|
||||
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
|
||||
properties: ['openFile'], filters: [{ name: 'OpenPGP keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
|
||||
});
|
||||
if (result.canceled || !result.filePaths[0]) return { canceled: true };
|
||||
const stat = await fs.stat(result.filePaths[0]);
|
||||
if (stat.size > 200000) throw new Error('That key file is too large.');
|
||||
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
|
||||
}
|
||||
return { key: await pgpKeys.import({ armoredKey, passphrase: input?.passphrase, accountId: input?.accountId || null }) };
|
||||
});
|
||||
|
||||
async function saveKeyFile(event, defaultName, content) {
|
||||
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: defaultName });
|
||||
if (result.canceled || !result.filePath) return { canceled: true };
|
||||
await fs.writeFile(result.filePath, content, { mode: 0o600 });
|
||||
return { saved: true };
|
||||
}
|
||||
const pgpFingerprint = value => {
|
||||
const fingerprint = String(value || '').toUpperCase();
|
||||
if (!/^[0-9A-F]{40,64}$/.test(fingerprint)) throw new Error('That key could not be identified.');
|
||||
return fingerprint;
|
||||
};
|
||||
ipcMain.handle('pgp:export-public', async (event, fingerprint) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
return saveKeyFile(event, `ep-mail-public-${id.slice(-16)}.asc`, await pgpKeys.exportPublic(id));
|
||||
});
|
||||
ipcMain.handle('pgp:export-private', async (event, fingerprint, passphrase) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
return saveKeyFile(event, `ep-mail-private-${id.slice(-16)}.asc`, await pgpKeys.exportPrivate(id, passphrase));
|
||||
});
|
||||
ipcMain.handle('pgp:export-revocation', async (event, fingerprint, passphrase) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase));
|
||||
});
|
||||
ipcMain.handle('pgp:delete', async (_event, fingerprint, passphrase) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
const result = await pgpKeys.remove(id, passphrase);
|
||||
pgpCache.clear(id);
|
||||
return result;
|
||||
});
|
||||
|
||||
async function fetchMessageSource(account, folder, uid) {
|
||||
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
const mailboxPath = await folderPath(client, folder);
|
||||
if (!mailboxPath) throw new Error('That mail folder could not be found.');
|
||||
const lock = await client.getMailboxLock(mailboxPath);
|
||||
try {
|
||||
const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true });
|
||||
if (!item?.source) throw new Error('The message is no longer available.');
|
||||
return item.source;
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
const pgpFailure = error => ({
|
||||
failed: true,
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
fingerprint: error.details?.fingerprint || null,
|
||||
email: error.details?.email || null,
|
||||
missing: error.details?.missing || []
|
||||
});
|
||||
|
||||
ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before opening messages.');
|
||||
const source = await fetchMessageSource(account, String(input?.folder || 'Inbox'), Number(input?.uid));
|
||||
const outer = await simpleParser(source);
|
||||
try {
|
||||
const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null });
|
||||
const content = mailContent(result.parsed);
|
||||
return {
|
||||
ok: true,
|
||||
body: content.body,
|
||||
links: content.links,
|
||||
attachments: content.attachments,
|
||||
attachment: content.attachment,
|
||||
size: content.size,
|
||||
signatures: result.signatures,
|
||||
attachedKeys: result.attachedKeys.map(key => ({ fingerprint: key.fingerprint, emails: key.emails, armoredKey: key.armoredKey }))
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof PgpError) return pgpFailure(error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.handle('pgp:check-send', async (_event, input) => {
|
||||
const account = await readAccount();
|
||||
return pgpMail.recipientStatus([input?.to, input?.cc], { sign: Boolean(input?.sign), from: account?.email || '' });
|
||||
});
|
||||
|
||||
ipcMain.handle('pgp:contacts', () => pgpKeys.listContacts());
|
||||
ipcMain.handle('pgp:add-contact', async (event, input) => {
|
||||
let armoredKey = typeof input?.armoredKey === 'string' ? input.armoredKey : '';
|
||||
if (!armoredKey) {
|
||||
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
|
||||
properties: ['openFile'], filters: [{ name: 'OpenPGP public keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }]
|
||||
});
|
||||
if (result.canceled || !result.filePaths[0]) return { canceled: true };
|
||||
if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.');
|
||||
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
|
||||
}
|
||||
const key = await openpgp.readKey({ armoredKey }).catch(() => {
|
||||
throw new Error('That is not a valid OpenPGP public key.');
|
||||
});
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
const emails = [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||
const existing = await pgpKeys.listContacts();
|
||||
const overlaps = existing.filter(item => (item.emails || []).some(email => emails.includes(String(email).toLowerCase())));
|
||||
if (overlaps.length) {
|
||||
const detail = overlaps.map(item => {
|
||||
const name = item.name || 'Unknown contact';
|
||||
const addresses = (item.emails || []).join(', ') || 'no address';
|
||||
const fp = String(item.fingerprint || '').replace(/(.{4})/g, '$1 ').trim();
|
||||
return `${name} (${addresses})\nFingerprint: ${fp}`;
|
||||
}).join('\n\n');
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Replace key'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Confirm key replacement',
|
||||
message: 'A different public key already exists for this email address.',
|
||||
detail: `New key:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nExisting key(s):\n${detail}\n\nOnly continue if you verified the new fingerprint with the owner.`,
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) throw new Error('Key replacement cancelled.');
|
||||
}
|
||||
const source = ['message', 'keyserver', 'paste'].includes(input?.source) ? input.source : 'import';
|
||||
return pgpKeys.addContact({ armoredKey, source });
|
||||
});
|
||||
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:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
|
||||
ipcMain.handle('pgp:export-contact', async (event, fingerprint) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
return saveKeyFile(event, `ep-mail-contact-${id.slice(-16)}.asc`, await pgpKeys.exportContact(id));
|
||||
});
|
||||
ipcMain.handle('pgp:get-settings', () => pgpKeys.getSettings());
|
||||
ipcMain.handle('pgp:set-settings', async (_event, input) => {
|
||||
const settings = await pgpKeys.setSettings({ cacheMinutes: input?.cacheMinutes });
|
||||
pgpCache.clear();
|
||||
return settings;
|
||||
});
|
||||
ipcMain.handle('pgp:key-servers', async () => {
|
||||
const settings = await pgpKeys.getSettings();
|
||||
return listServers(settings.customKeyServers);
|
||||
});
|
||||
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 });
|
||||
return { removed: true };
|
||||
});
|
||||
ipcMain.handle('pgp:find-key', async (_event, input) => {
|
||||
const settings = await pgpKeys.getSettings();
|
||||
const server = listServers(settings.customKeyServers).find(item => item.id === String(input?.serverId || ''));
|
||||
if (!server) throw new Error('Choose a configured key server.');
|
||||
return pgpKeyServers.lookup(server, 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).find(item => item.id === String(input?.serverId || ''));
|
||||
if (!server) throw new Error('Choose a configured key server.');
|
||||
const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
if (!entry.email) throw new Error('This key has no email address to publish.');
|
||||
const armoredKey = await pgpKeys.exportPublic(fingerprint);
|
||||
const publicKey = await openpgp.readKey({ armoredKey });
|
||||
const emails = [...new Set(publicKey.getUserIDs()
|
||||
.map(userId => (/<([^>]+)>/.exec(userId)?.[1] || (userId.includes('@') ? userId : '')).trim().toLowerCase())
|
||||
.filter(Boolean))];
|
||||
if (!emails.includes(entry.email.toLowerCase())) throw new Error('The selected key no longer matches its stored email address.');
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Publish public key'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Publish public key?',
|
||||
message: `Publish the public key for ${emails.join(', ')} to ${server.name}?`,
|
||||
detail: `Fingerprint:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly the public key will be sent. This exposes the email address(es) in the key to the server, which may retain them. The server may send a verification email before the key becomes searchable.`,
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) return { canceled: true };
|
||||
return pgpKeyServers.publish(server, entry.email, armoredKey, fingerprint);
|
||||
});
|
||||
ipcMain.handle('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
|
||||
|
||||
ipcMain.handle('mail:open-external', async (event, rawUrl) => {
|
||||
let target;
|
||||
try {
|
||||
@@ -1217,15 +1581,17 @@ async function sendMailNow(account, message) {
|
||||
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
||||
messageId: sentMessageId
|
||||
};
|
||||
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
|
||||
try {
|
||||
await transport.sendMail(messageOptions);
|
||||
if (rawMessage) await transport.sendMail({ envelope: message.envelope, raw: rawMessage });
|
||||
else await transport.sendMail(messageOptions);
|
||||
} finally {
|
||||
transport.close();
|
||||
}
|
||||
let savedToSent = false;
|
||||
const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
|
||||
try {
|
||||
const rendered = await copy.sendMail(messageOptions);
|
||||
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
|
||||
const client = imapClient(account);
|
||||
try {
|
||||
await client.connect();
|
||||
@@ -1247,10 +1613,54 @@ async function sendMailNow(account, message) {
|
||||
return { ok: true, savedToSent };
|
||||
}
|
||||
|
||||
ipcMain.handle('mail:send', async (_event, message) => {
|
||||
ipcMain.handle('mail:send', async (event, message) => {
|
||||
const account = await readAccount();
|
||||
if (!account) throw new Error('Add a mail account before sending.');
|
||||
const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null;
|
||||
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
|
||||
delete queuedMessage.pgp;
|
||||
if (!pgpOptions?.encrypt) {
|
||||
const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean);
|
||||
const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email });
|
||||
if (status.recipients.length && !status.missing.length) {
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Send anyway'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Send without encryption?',
|
||||
message: 'Public keys are available for all recipients.',
|
||||
detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.',
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) throw new Error('Plaintext send cancelled.');
|
||||
}
|
||||
}
|
||||
if (pgpOptions) {
|
||||
// Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox.
|
||||
const signature = String(account.signature || '').slice(0, 5000);
|
||||
const body = String(queuedMessage.text || '').slice(0, 500000);
|
||||
const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
|
||||
try {
|
||||
const built = await pgpMail.build({
|
||||
from: { name: fromName, address: account.email },
|
||||
to: queuedMessage.to,
|
||||
cc: queuedMessage.cc,
|
||||
subject: String(queuedMessage.subject || '(no subject)').slice(0, 998),
|
||||
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
|
||||
messageId: queuedMessage.messageId,
|
||||
encrypt: Boolean(pgpOptions.encrypt),
|
||||
sign: Boolean(pgpOptions.sign),
|
||||
passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null
|
||||
});
|
||||
queuedMessage.rawBase64 = built.raw.toString('base64');
|
||||
queuedMessage.envelope = built.envelope;
|
||||
queuedMessage.text = '';
|
||||
} catch (error) {
|
||||
if (error instanceof PgpError) return pgpFailure(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
try {
|
||||
return await sendMailNow(account, queuedMessage);
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
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 = []) {
|
||||
return [
|
||||
...BUILTIN_SERVERS.map(server => ({ ...server })),
|
||||
...customServers.map(server => normalizeCustomServer(server))
|
||||
];
|
||||
}
|
||||
|
||||
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 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, publish };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BUILTIN_SERVERS,
|
||||
MAX_CUSTOM_SERVERS,
|
||||
createKeyServerService,
|
||||
listServers,
|
||||
normalizeBaseUrl,
|
||||
normalizeCustomServer
|
||||
};
|
||||
@@ -0,0 +1,318 @@
|
||||
const openpgp = require('openpgp');
|
||||
|
||||
const MAX_KEY_LENGTH = 200000;
|
||||
|
||||
function publicInfo(entry) {
|
||||
return {
|
||||
fingerprint: entry.fingerprint,
|
||||
name: entry.name,
|
||||
email: entry.email,
|
||||
accountId: entry.accountId || null,
|
||||
createdAt: entry.createdAt,
|
||||
algorithm: entry.algorithm,
|
||||
hasRevocationCertificate: Boolean(entry.revocationCertificate)
|
||||
};
|
||||
}
|
||||
|
||||
function requirePassphrase(passphrase) {
|
||||
if (typeof passphrase !== 'string' || passphrase.length < 8) {
|
||||
throw new Error('Use a passphrase of at least 8 characters.');
|
||||
}
|
||||
return passphrase;
|
||||
}
|
||||
|
||||
function readArmored(value) {
|
||||
const armored = String(value || '').trim();
|
||||
if (!armored || armored.length > MAX_KEY_LENGTH) throw new Error('That key file is empty or too large.');
|
||||
return armored;
|
||||
}
|
||||
|
||||
async function unlock(armoredPrivateKey, passphrase) {
|
||||
try {
|
||||
return await openpgp.decryptKey({
|
||||
privateKey: await openpgp.readPrivateKey({ armoredKey: armoredPrivateKey }),
|
||||
passphrase
|
||||
});
|
||||
} catch {
|
||||
throw new Error('The passphrase is incorrect.');
|
||||
}
|
||||
}
|
||||
|
||||
const TRUST_LEVELS = ['unknown', 'trusted', 'verified'];
|
||||
const DEFAULT_CACHE_MINUTES = 10;
|
||||
|
||||
function contactInfo(entry) {
|
||||
return {
|
||||
fingerprint: entry.fingerprint,
|
||||
name: entry.name,
|
||||
emails: entry.emails,
|
||||
trust: entry.trust,
|
||||
source: entry.source,
|
||||
addedAt: entry.addedAt
|
||||
};
|
||||
}
|
||||
|
||||
async function readPublicOnly(value) {
|
||||
const armored = readArmored(value);
|
||||
if (/BEGIN PGP PRIVATE KEY BLOCK/.test(armored)) throw new Error('That file contains a private key. Import public keys only.');
|
||||
const key = await openpgp.readKey({ armoredKey: armored }).catch(() => {
|
||||
throw new Error('That is not a valid OpenPGP public key.');
|
||||
});
|
||||
await key.getPrimaryUser().catch(() => {
|
||||
throw new Error('That key is expired, revoked or has no valid user ID.');
|
||||
});
|
||||
return key;
|
||||
}
|
||||
|
||||
async function keyEmails(key) {
|
||||
return [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||
}
|
||||
// Passphrase-protected OpenPGP key storage. `storage` persists one JSON object
|
||||
// (the desktop app wraps it with the OS credential store before writing it).
|
||||
function createKeyStore(storage) {
|
||||
async function read() {
|
||||
const data = await storage.load();
|
||||
return {
|
||||
keys: Array.isArray(data?.keys) ? data.keys : [],
|
||||
contacts: Array.isArray(data?.contacts) ? data.contacts : [],
|
||||
settings: data?.settings && typeof data.settings === 'object' ? data.settings : {}
|
||||
};
|
||||
}
|
||||
|
||||
async function add(entry) {
|
||||
const data = await read();
|
||||
if (data.keys.some(key => key.fingerprint === entry.fingerprint)) {
|
||||
throw new Error('That key is already in your keyring.');
|
||||
}
|
||||
data.keys.push(entry);
|
||||
await storage.save(data);
|
||||
}
|
||||
|
||||
return {
|
||||
async listContacts() {
|
||||
return (await read()).contacts.map(contactInfo);
|
||||
},
|
||||
|
||||
async addContact({ armoredKey, source = 'import' }) {
|
||||
const key = await readPublicOnly(armoredKey);
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
const emails = await keyEmails(key);
|
||||
const data = await read();
|
||||
if (data.keys.some(entry => entry.fingerprint === fingerprint)) throw new Error('That is one of your own keys.');
|
||||
if (data.contacts.some(entry => entry.fingerprint === fingerprint)) throw new Error('That public key is already in your contacts.');
|
||||
const user = await key.getPrimaryUser();
|
||||
const replaces = data.contacts
|
||||
.filter(entry => entry.emails.some(email => emails.includes(email)))
|
||||
.map(entry => entry.fingerprint);
|
||||
const entry = {
|
||||
fingerprint,
|
||||
name: user.user.userID?.name || '',
|
||||
emails,
|
||||
trust: 'unknown',
|
||||
source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import',
|
||||
addedAt: Date.now(),
|
||||
publicKey: key.armor()
|
||||
};
|
||||
data.contacts.push(entry);
|
||||
await storage.save(data);
|
||||
return { contact: contactInfo(entry), keyChangedFrom: replaces };
|
||||
},
|
||||
|
||||
async setTrust(fingerprint, trust) {
|
||||
if (!TRUST_LEVELS.includes(trust)) throw new Error('Unknown trust level.');
|
||||
const data = await read();
|
||||
const entry = data.contacts.find(item => item.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That contact key was not found.');
|
||||
entry.trust = trust;
|
||||
await storage.save(data);
|
||||
return contactInfo(entry);
|
||||
},
|
||||
|
||||
async removeContact(fingerprint) {
|
||||
const data = await read();
|
||||
if (!data.contacts.some(item => item.fingerprint === fingerprint)) throw new Error('That contact key was not found.');
|
||||
data.contacts = data.contacts.filter(item => item.fingerprint !== fingerprint);
|
||||
await storage.save(data);
|
||||
return { removed: true };
|
||||
},
|
||||
|
||||
async exportContact(fingerprint) {
|
||||
const entry = (await read()).contacts.find(item => item.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That contact key was not found.');
|
||||
return entry.publicKey;
|
||||
},
|
||||
|
||||
// Resolves public keys for recipient addresses (contacts and own keys).
|
||||
async findRecipientKeys(addresses) {
|
||||
const data = await read();
|
||||
const pool = [
|
||||
...data.contacts.map(entry => ({ ...entry, own: false })),
|
||||
...data.keys.map(entry => ({ fingerprint: entry.fingerprint, emails: [String(entry.email).toLowerCase()], trust: 'verified', addedAt: entry.createdAt, publicKey: entry.publicKey, own: true }))
|
||||
];
|
||||
const keys = [];
|
||||
const missing = [];
|
||||
for (const address of addresses.map(value => String(value).trim().toLowerCase())) {
|
||||
const candidates = pool
|
||||
.filter(entry => entry.emails.includes(address))
|
||||
.sort((a, b) => TRUST_LEVELS.indexOf(b.trust) - TRUST_LEVELS.indexOf(a.trust) || b.addedAt - a.addedAt);
|
||||
let usable = null;
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const key = await openpgp.readKey({ armoredKey: candidate.publicKey });
|
||||
await key.getEncryptionKey();
|
||||
usable = { key, fingerprint: candidate.fingerprint, trust: candidate.trust };
|
||||
break;
|
||||
} catch { /* expired or revoked: try the next key */ }
|
||||
}
|
||||
if (usable) keys.push({ address, ...usable });
|
||||
else missing.push(address);
|
||||
}
|
||||
return { keys, missing };
|
||||
},
|
||||
|
||||
async verificationKeys() {
|
||||
const data = await read();
|
||||
const result = [];
|
||||
for (const entry of [...data.contacts.map(item => ({ ...item, own: false })), ...data.keys.map(item => ({ ...item, trust: 'verified', emails: [String(item.email).toLowerCase()], own: true }))]) {
|
||||
try {
|
||||
result.push({ key: await openpgp.readKey({ armoredKey: entry.publicKey }), fingerprint: entry.fingerprint, trust: entry.trust, emails: entry.emails, own: entry.own });
|
||||
} catch { /* skip unreadable entries */ }
|
||||
}
|
||||
return result;
|
||||
},
|
||||
|
||||
async privateEntries() {
|
||||
return (await read()).keys.map(entry => ({ fingerprint: entry.fingerprint, email: entry.email, name: entry.name, privateKey: entry.privateKey, publicKey: entry.publicKey }));
|
||||
},
|
||||
|
||||
async unlockKey(fingerprint, passphrase) {
|
||||
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
return unlock(entry.privateKey, passphrase);
|
||||
},
|
||||
|
||||
async getSettings() {
|
||||
const settings = (await read()).settings;
|
||||
return {
|
||||
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
|
||||
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : []
|
||||
};
|
||||
},
|
||||
|
||||
async setSettings({ cacheMinutes, customKeyServers }) {
|
||||
const minutes = Number(cacheMinutes);
|
||||
if (!Number.isFinite(minutes) || minutes < 0 || minutes > 1440) throw new Error('Choose between 0 and 1440 minutes.');
|
||||
const data = await read();
|
||||
data.settings.cacheMinutes = Math.round(minutes);
|
||||
if (customKeyServers !== undefined) {
|
||||
if (!Array.isArray(customKeyServers) || customKeyServers.length > 10 || customKeyServers.some(server => !server || typeof server !== 'object')) {
|
||||
throw new Error('You can configure up to 10 valid custom key servers.');
|
||||
}
|
||||
data.settings.customKeyServers = customKeyServers.map(server => ({
|
||||
id: String(server.id || ''),
|
||||
name: String(server.name || '').slice(0, 60),
|
||||
url: String(server.url || '').slice(0, 300),
|
||||
protocol: String(server.protocol || '')
|
||||
}));
|
||||
}
|
||||
await storage.save(data);
|
||||
return {
|
||||
cacheMinutes: data.settings.cacheMinutes,
|
||||
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : []
|
||||
};
|
||||
},
|
||||
|
||||
async list() {
|
||||
return (await read()).keys.map(publicInfo);
|
||||
},
|
||||
|
||||
async generate({ name, email, passphrase, accountId = null }) {
|
||||
const cleanName = String(name || '').trim().slice(0, 100);
|
||||
const cleanEmail = String(email || '').trim();
|
||||
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(cleanEmail)) throw new Error('Enter a valid email address for the key.');
|
||||
requirePassphrase(passphrase);
|
||||
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
|
||||
type: 'ecc',
|
||||
curve: 'curve25519Legacy',
|
||||
userIDs: [{ name: cleanName || undefined, email: cleanEmail }],
|
||||
passphrase,
|
||||
format: 'armored'
|
||||
});
|
||||
const key = await openpgp.readKey({ armoredKey: publicKey });
|
||||
const entry = {
|
||||
fingerprint: key.getFingerprint().toUpperCase(),
|
||||
name: cleanName,
|
||||
email: cleanEmail,
|
||||
accountId,
|
||||
createdAt: Date.now(),
|
||||
algorithm: 'Curve25519',
|
||||
privateKey,
|
||||
publicKey,
|
||||
revocationCertificate
|
||||
};
|
||||
await add(entry);
|
||||
return { key: publicInfo(entry), revocationCertificate };
|
||||
},
|
||||
|
||||
async import({ armoredKey, passphrase, accountId = null }) {
|
||||
const parsed = await openpgp.readPrivateKey({ armoredKey: readArmored(armoredKey) }).catch(() => {
|
||||
throw new Error('That is not a valid OpenPGP private key.');
|
||||
});
|
||||
requirePassphrase(passphrase);
|
||||
let protectedKey;
|
||||
if (parsed.isDecrypted()) {
|
||||
protectedKey = await openpgp.encryptKey({ privateKey: parsed, passphrase });
|
||||
} else {
|
||||
await unlock(parsed.armor(), passphrase);
|
||||
protectedKey = parsed;
|
||||
}
|
||||
const user = await protectedKey.getPrimaryUser().catch(() => null);
|
||||
const entry = {
|
||||
fingerprint: protectedKey.getFingerprint().toUpperCase(),
|
||||
name: user?.user?.userID?.name || '',
|
||||
email: user?.user?.userID?.email || '',
|
||||
accountId,
|
||||
createdAt: protectedKey.getCreationTime().getTime(),
|
||||
algorithm: protectedKey.getAlgorithmInfo().algorithm,
|
||||
privateKey: protectedKey.armor(),
|
||||
publicKey: protectedKey.toPublic().armor(),
|
||||
revocationCertificate: null
|
||||
};
|
||||
await add(entry);
|
||||
return publicInfo(entry);
|
||||
},
|
||||
|
||||
async exportPublic(fingerprint) {
|
||||
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
return entry.publicKey;
|
||||
},
|
||||
|
||||
async exportPrivate(fingerprint, passphrase) {
|
||||
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
await unlock(entry.privateKey, passphrase);
|
||||
return entry.privateKey;
|
||||
},
|
||||
|
||||
async exportRevocation(fingerprint, passphrase) {
|
||||
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
if (!entry.revocationCertificate) throw new Error('No revocation certificate is stored for this key.');
|
||||
await unlock(entry.privateKey, passphrase);
|
||||
return entry.revocationCertificate;
|
||||
},
|
||||
|
||||
async remove(fingerprint, passphrase) {
|
||||
const data = await read();
|
||||
const entry = data.keys.find(key => key.fingerprint === fingerprint);
|
||||
if (!entry) throw new Error('That key was not found.');
|
||||
await unlock(entry.privateKey, passphrase);
|
||||
data.keys = data.keys.filter(key => key.fingerprint !== fingerprint);
|
||||
await storage.save(data);
|
||||
return { removed: true };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createKeyStore };
|
||||
@@ -0,0 +1,361 @@
|
||||
const openpgp = require('openpgp');
|
||||
const { simpleParser } = require('mailparser');
|
||||
const addressParser = require('nodemailer/lib/addressparser');
|
||||
const { randomBytes } = require('node:crypto');
|
||||
|
||||
const ARMORED_MESSAGE = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/;
|
||||
const CLEARTEXT_SIGNED = /-----BEGIN PGP SIGNED MESSAGE-----[\s\S]+?-----END PGP SIGNATURE-----/;
|
||||
const MAX_ENCRYPTED_BYTES = 60 * 1048576;
|
||||
|
||||
class PgpError extends Error {
|
||||
constructor(code, message, details = {}) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.details = details;
|
||||
}
|
||||
}
|
||||
|
||||
// Remembers unlocked-key passphrases in memory only, for a limited time.
|
||||
function createPassphraseCache(getMinutes, now = () => Date.now()) {
|
||||
const entries = new Map();
|
||||
return {
|
||||
async remember(fingerprint, passphrase) {
|
||||
const minutes = await getMinutes();
|
||||
if (!minutes) { entries.delete(fingerprint); return; }
|
||||
entries.set(fingerprint, { passphrase, expires: now() + minutes * 60000 });
|
||||
},
|
||||
get(fingerprint) {
|
||||
const entry = entries.get(fingerprint);
|
||||
if (!entry) return null;
|
||||
if (entry.expires <= now()) { entries.delete(fingerprint); return null; }
|
||||
return entry.passphrase;
|
||||
},
|
||||
has(fingerprint) { return this.get(fingerprint) !== null; },
|
||||
clear(fingerprint) { if (fingerprint) entries.delete(fingerprint); else entries.clear(); }
|
||||
};
|
||||
}
|
||||
|
||||
function headerValue(parsed, name) {
|
||||
const value = parsed.headers?.get(name);
|
||||
return value && typeof value === 'object' ? value : { value: String(value || ''), params: {} };
|
||||
}
|
||||
|
||||
// Classifies a parsed message: encrypted/signed PGP/MIME or inline PGP.
|
||||
function detect(parsed) {
|
||||
const type = String(headerValue(parsed, 'content-type').value).toLowerCase();
|
||||
const protocol = String(headerValue(parsed, 'content-type').params?.protocol || '').toLowerCase();
|
||||
if (type === 'multipart/encrypted' && protocol === 'application/pgp-encrypted') return 'encrypted-mime';
|
||||
if (type === 'multipart/signed' && protocol === 'application/pgp-signature') return 'signed-mime';
|
||||
const text = String(parsed.text || '');
|
||||
if (ARMORED_MESSAGE.test(text)) return 'encrypted-inline';
|
||||
if (CLEARTEXT_SIGNED.test(text)) return 'signed-inline';
|
||||
return null;
|
||||
}
|
||||
|
||||
function encryptedArmor(parsed, kind) {
|
||||
if (kind === 'encrypted-inline') return ARMORED_MESSAGE.exec(String(parsed.text || ''))[0];
|
||||
for (const file of parsed.attachments || []) {
|
||||
const content = file.content.toString('latin1');
|
||||
const match = ARMORED_MESSAGE.exec(content);
|
||||
if (match) return match[0];
|
||||
}
|
||||
throw new PgpError('CORRUPT', 'The encrypted part of this message is missing or damaged.');
|
||||
}
|
||||
|
||||
function emailsOf(key) {
|
||||
return key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean);
|
||||
}
|
||||
|
||||
function fingerprintsByKeyId(verification) {
|
||||
const map = new Map();
|
||||
for (const item of verification) {
|
||||
for (const key of item.key.getKeys()) map.set(key.getKeyID().toHex().toUpperCase(), item);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// Interprets signature results and flags a sender whose key changed.
|
||||
async function describeSignatures(signatures, verification, senderEmail) {
|
||||
const byKeyId = fingerprintsByKeyId(verification);
|
||||
const sender = String(senderEmail || '').toLowerCase();
|
||||
const results = [];
|
||||
for (const signature of signatures) {
|
||||
const keyId = signature.keyID.toHex().toUpperCase();
|
||||
const known = byKeyId.get(keyId);
|
||||
let status;
|
||||
try {
|
||||
await signature.verified;
|
||||
status = 'valid';
|
||||
} catch (error) {
|
||||
status = /could not find signing key|no signing key|not found/i.test(String(error?.message)) || !known ? 'unknown-key' : 'invalid';
|
||||
}
|
||||
const result = { status, keyId, fingerprint: known?.fingerprint || null, trust: known?.trust || null, email: null, matchesSender: false, keyChanged: false };
|
||||
if (known) {
|
||||
result.email = known.emails[0] || null;
|
||||
result.matchesSender = Boolean(sender) && known.emails.includes(sender);
|
||||
}
|
||||
if (sender && status === 'valid' && known && !known.emails.includes(sender)) result.mismatch = true;
|
||||
if (sender && status !== 'unknown-key') {
|
||||
const others = verification.filter(item => !item.own && item.emails.includes(sender) && item.fingerprint !== known?.fingerprint);
|
||||
if (others.length && !result.matchesSender) result.keyChanged = true;
|
||||
}
|
||||
if (sender && status === 'unknown-key' && verification.some(item => !item.own && item.emails.includes(sender))) result.keyChanged = true;
|
||||
results.push(result);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
function chunkBase64(buffer) {
|
||||
return buffer.toString('base64').replace(/(.{76})/g, '$1\r\n').replace(/\r\n$/, '');
|
||||
}
|
||||
|
||||
function encodeHeader(value) {
|
||||
const clean = String(value).replace(/[\r\n]+/g, ' ').trim();
|
||||
if (/^[\x20-\x7e]*$/.test(clean) && clean.length <= 900) return clean;
|
||||
const chars = Array.from(clean);
|
||||
const words = [];
|
||||
for (let index = 0; index < chars.length; index += 24) {
|
||||
words.push(`=?UTF-8?B?${Buffer.from(chars.slice(index, index + 24).join(''), 'utf8').toString('base64')}?=`);
|
||||
}
|
||||
return words.join('\r\n ');
|
||||
}
|
||||
|
||||
function formatAddress(entry) {
|
||||
const address = String(entry.address || '').trim();
|
||||
if (!/^[^\s@<>"',;]+@[^\s@<>"',;]+$/.test(address)) throw new Error(`"${address || entry.name}" is not a valid email address.`);
|
||||
const name = String(entry.name || '').replace(/[\r\n"\\]+/g, ' ').trim();
|
||||
return name ? `${encodeHeader(`"${name}"`)} <${address}>` : address;
|
||||
}
|
||||
|
||||
function parseAddresses(value) {
|
||||
return addressParser(String(value || '')).filter(entry => entry.address || entry.name);
|
||||
}
|
||||
|
||||
function innerEntity(text) {
|
||||
const body = Buffer.from(String(text || ''), 'utf8');
|
||||
return Buffer.from(`Content-Type: text/plain; charset=utf-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${chunkBase64(body)}\r\n`, 'latin1');
|
||||
}
|
||||
|
||||
function boundary() {
|
||||
return `=_ep-${randomBytes(12).toString('hex')}`;
|
||||
}
|
||||
|
||||
function createPgpMail({ keyStore, cache }) {
|
||||
async function findDecryptionKey(message) {
|
||||
const wanted = new Set(message.getEncryptionKeyIDs().map(id => id.toHex().toUpperCase()));
|
||||
const entries = await keyStore.privateEntries();
|
||||
const candidates = [];
|
||||
for (const entry of entries) {
|
||||
const publicKey = await openpgp.readKey({ armoredKey: entry.publicKey });
|
||||
if (publicKey.getKeys().some(key => wanted.has(key.getKeyID().toHex().toUpperCase()))) candidates.push(entry);
|
||||
}
|
||||
if (!candidates.length) throw new PgpError('NO_KEY', 'None of your keys can decrypt this message.');
|
||||
return candidates;
|
||||
}
|
||||
|
||||
async function unlockAny(candidates, passphrase) {
|
||||
let lastError = null;
|
||||
for (const candidate of candidates) {
|
||||
const secret = passphrase || cache.get(candidate.fingerprint);
|
||||
if (!secret) continue;
|
||||
try {
|
||||
const key = await keyStore.unlockKey(candidate.fingerprint, secret);
|
||||
await cache.remember(candidate.fingerprint, secret);
|
||||
return key;
|
||||
} catch (error) {
|
||||
cache.clear(candidate.fingerprint);
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
if (lastError) throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: candidates[0].fingerprint });
|
||||
throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to read this message.', {
|
||||
fingerprint: candidates[0].fingerprint, email: candidates[0].email
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
detect,
|
||||
|
||||
async decrypt(parsed, { passphrase = null } = {}) {
|
||||
const kind = detect(parsed);
|
||||
if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') throw new PgpError('NOT_ENCRYPTED', 'This message is not encrypted.');
|
||||
const armored = encryptedArmor(parsed, kind);
|
||||
if (armored.length > MAX_ENCRYPTED_BYTES) throw new PgpError('TOO_LARGE', 'This encrypted message is too large to open.');
|
||||
let message;
|
||||
try {
|
||||
message = await openpgp.readMessage({ armoredMessage: armored });
|
||||
} catch {
|
||||
throw new PgpError('CORRUPT', 'The encrypted part of this message is damaged.');
|
||||
}
|
||||
const decryptionKey = await unlockAny(await findDecryptionKey(message), passphrase);
|
||||
const verification = await keyStore.verificationKeys();
|
||||
let result;
|
||||
try {
|
||||
result = await openpgp.decrypt({
|
||||
message,
|
||||
decryptionKeys: decryptionKey,
|
||||
verificationKeys: verification.map(item => item.key),
|
||||
format: 'binary'
|
||||
});
|
||||
} catch {
|
||||
throw new PgpError('CORRUPT', 'The message could not be decrypted. It may be damaged or altered.');
|
||||
}
|
||||
const data = Buffer.from(result.data);
|
||||
const sender = parsed.from?.value?.[0]?.address || '';
|
||||
const signatures = await describeSignatures(result.signatures, verification, sender);
|
||||
const inner = kind === 'encrypted-mime' ? await simpleParser(data) : await simpleParser(Buffer.concat([
|
||||
Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\n'), data
|
||||
]));
|
||||
return { parsed: inner, signatures, attachedKeys: await this.attachedKeys(inner) };
|
||||
},
|
||||
|
||||
// Public keys attached to a message (offered to the user, never added silently).
|
||||
async attachedKeys(parsed) {
|
||||
const keys = [];
|
||||
for (const file of parsed.attachments || []) {
|
||||
const type = String(file.contentType || '').toLowerCase();
|
||||
if (type !== 'application/pgp-keys' && !/\.asc$/i.test(file.filename || '')) continue;
|
||||
const armored = file.content.toString('utf8');
|
||||
if (!/BEGIN PGP PUBLIC KEY BLOCK/.test(armored) || armored.length > 200000) continue;
|
||||
try {
|
||||
const key = await openpgp.readKey({ armoredKey: armored });
|
||||
keys.push({ armoredKey: armored, fingerprint: key.getFingerprint().toUpperCase(), emails: emailsOf(key) });
|
||||
} catch { /* ignore unreadable attachments */ }
|
||||
}
|
||||
return keys.slice(0, 5);
|
||||
},
|
||||
|
||||
// Verifies PGP/MIME (multipart/signed) and cleartext signatures on unencrypted mail.
|
||||
async verifySigned(parsed, source) {
|
||||
const kind = detect(parsed);
|
||||
const verification = await keyStore.verificationKeys();
|
||||
const sender = parsed.from?.value?.[0]?.address || '';
|
||||
try {
|
||||
if (kind === 'signed-inline') {
|
||||
const message = await openpgp.readCleartextMessage({ cleartextMessage: CLEARTEXT_SIGNED.exec(String(parsed.text))[0] });
|
||||
const result = await openpgp.verify({ message, verificationKeys: verification.map(item => item.key) });
|
||||
return describeSignatures(result.signatures, verification, sender);
|
||||
}
|
||||
if (kind !== 'signed-mime') return null;
|
||||
const parts = splitSigned(source, headerValue(parsed, 'content-type').params?.boundary);
|
||||
if (!parts) return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
|
||||
const signature = await openpgp.readSignature({ armoredSignature: parts.signature });
|
||||
const result = await openpgp.verify({
|
||||
message: await openpgp.createMessage({ binary: parts.signed }),
|
||||
signature,
|
||||
verificationKeys: verification.map(item => item.key)
|
||||
});
|
||||
return describeSignatures(result.signatures, verification, sender);
|
||||
} catch {
|
||||
return [{ status: 'invalid', keyId: '', fingerprint: null, trust: null, email: null, matchesSender: false, keyChanged: false }];
|
||||
}
|
||||
},
|
||||
|
||||
// Builds a complete RFC 3156 message. Returns { raw, envelope }.
|
||||
async build({ from, to, cc, subject, text, messageId, date = new Date(), encrypt, sign, passphrase, signerFingerprint }) {
|
||||
const toList = parseAddresses(to);
|
||||
const ccList = parseAddresses(cc);
|
||||
if (!toList.length) throw new Error('Add at least one recipient.');
|
||||
const everyone = [...toList, ...ccList];
|
||||
everyone.forEach(entry => formatAddress(entry));
|
||||
let signingKey = null;
|
||||
let signerEntry = null;
|
||||
if (sign) {
|
||||
const entries = await keyStore.privateEntries();
|
||||
signerEntry = entries.find(entry => entry.fingerprint === signerFingerprint)
|
||||
|| entries.find(entry => entry.email.toLowerCase() === String(from.address).toLowerCase());
|
||||
if (!signerEntry) throw new PgpError('NO_SIGNING_KEY', 'Create or import an encryption key for this address first.');
|
||||
const secret = passphrase || cache.get(signerEntry.fingerprint);
|
||||
if (!secret) throw new PgpError('PASSPHRASE_REQUIRED', 'Enter your key passphrase to sign this message.', { fingerprint: signerEntry.fingerprint, email: signerEntry.email });
|
||||
try {
|
||||
signingKey = await keyStore.unlockKey(signerEntry.fingerprint, secret);
|
||||
} catch {
|
||||
cache.clear(signerEntry.fingerprint);
|
||||
throw new PgpError('BAD_PASSPHRASE', 'The passphrase is incorrect.', { fingerprint: signerEntry.fingerprint });
|
||||
}
|
||||
await cache.remember(signerEntry.fingerprint, secret);
|
||||
}
|
||||
const headers = [
|
||||
`From: ${formatAddress(from)}`,
|
||||
`To: ${toList.map(formatAddress).join(', ')}`,
|
||||
...(ccList.length ? [`Cc: ${ccList.map(formatAddress).join(', ')}`] : []),
|
||||
`Subject: ${encodeHeader(subject || '(no subject)')}`,
|
||||
`Date: ${date.toUTCString().replace('GMT', '+0000')}`,
|
||||
`Message-ID: ${String(messageId).replace(/[\r\n<>\s]/g, '').replace(/^/, '<').replace(/$/, '>')}`,
|
||||
'MIME-Version: 1.0'
|
||||
];
|
||||
const inner = innerEntity(text);
|
||||
const mark = boundary();
|
||||
let body;
|
||||
let contentType;
|
||||
if (encrypt) {
|
||||
const { keys, missing } = await keyStore.findRecipientKeys(everyone.map(entry => entry.address));
|
||||
if (missing.length) throw new PgpError('NO_RECIPIENT_KEY', `No public key for ${missing.join(', ')}.`, { missing });
|
||||
const own = signerEntry ? [await openpgp.readKey({ armoredKey: signerEntry.publicKey })] : [];
|
||||
const ownKeys = own.length ? own : (await keyStore.findRecipientKeys([from.address])).keys.map(item => item.key);
|
||||
const armored = await openpgp.encrypt({
|
||||
message: await openpgp.createMessage({ binary: inner }),
|
||||
encryptionKeys: [...keys.map(item => item.key), ...ownKeys],
|
||||
signingKeys: signingKey || undefined,
|
||||
format: 'armored'
|
||||
});
|
||||
contentType = `multipart/encrypted; protocol="application/pgp-encrypted"; boundary="${mark}"`;
|
||||
body = [
|
||||
`--${mark}`, 'Content-Type: application/pgp-encrypted', 'Content-Description: PGP/MIME version identification', '', 'Version: 1', '',
|
||||
`--${mark}`, 'Content-Type: application/octet-stream; name="encrypted.asc"', 'Content-Description: OpenPGP encrypted message',
|
||||
'Content-Disposition: inline; filename="encrypted.asc"', '', String(armored).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
|
||||
].join('\r\n');
|
||||
} else if (sign) {
|
||||
const signedBytes = inner.subarray(0, inner.length - 2);
|
||||
const detached = await openpgp.sign({ message: await openpgp.createMessage({ binary: signedBytes }), signingKeys: signingKey, detached: true, format: 'armored' });
|
||||
contentType = `multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha256; boundary="${mark}"`;
|
||||
const signedPart = signedBytes.toString('latin1');
|
||||
body = [
|
||||
`--${mark}`, signedPart, `--${mark}`, 'Content-Type: application/pgp-signature; name="signature.asc"',
|
||||
'Content-Description: OpenPGP digital signature', 'Content-Disposition: attachment; filename="signature.asc"', '',
|
||||
String(detached).replace(/\r?\n/g, '\r\n').trim(), '', `--${mark}--`, ''
|
||||
].join('\r\n');
|
||||
} else {
|
||||
throw new Error('Choose encryption or signing for this message.');
|
||||
}
|
||||
const raw = Buffer.from(`${headers.join('\r\n')}\r\nContent-Type: ${contentType}\r\n\r\n${body}`, 'latin1');
|
||||
return { raw, envelope: { from: from.address, to: everyone.map(entry => entry.address) }, signerFingerprint: signerEntry?.fingerprint || null };
|
||||
},
|
||||
|
||||
async recipientStatus(addresses, { sign = false, from = '' } = {}) {
|
||||
const list = addresses.flatMap(value => parseAddresses(value)).map(entry => entry.address).filter(Boolean);
|
||||
const { keys, missing } = await keyStore.findRecipientKeys(list);
|
||||
let signer = null;
|
||||
if (sign) {
|
||||
const entries = await keyStore.privateEntries();
|
||||
const entry = entries.find(item => item.email.toLowerCase() === String(from).toLowerCase()) || null;
|
||||
if (entry) signer = { fingerprint: entry.fingerprint, email: entry.email, name: entry.name, unlocked: cache.has(entry.fingerprint) };
|
||||
}
|
||||
return {
|
||||
recipients: keys.map(item => ({ address: item.address, fingerprint: item.fingerprint, trust: item.trust })),
|
||||
missing,
|
||||
signer
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Extracts the signed part and detached signature from a multipart/signed source.
|
||||
function splitSigned(source, boundaryValue) {
|
||||
if (!boundaryValue) return null;
|
||||
const text = Buffer.from(source).toString('latin1');
|
||||
const escaped = String(boundaryValue).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const delimiter = new RegExp(`(?:^|\\r?\\n)--${escaped}(--)?[ \\t]*(?=\\r?\\n|$)`, 'g');
|
||||
const marks = [...text.matchAll(delimiter)];
|
||||
if (marks.length < 3) return null;
|
||||
const contentAfter = mark => {
|
||||
const lineEnd = text.indexOf('\n', mark.index + mark[0].length);
|
||||
return lineEnd < 0 ? text.length : lineEnd + 1;
|
||||
};
|
||||
const signed = text.slice(contentAfter(marks[0]), marks[1].index).replace(/\r?\n/g, '\r\n');
|
||||
const signaturePart = text.slice(contentAfter(marks[1]), marks[2].index);
|
||||
const armored = /-----BEGIN PGP SIGNATURE-----[\s\S]+?-----END PGP SIGNATURE-----/.exec(signaturePart)?.[0];
|
||||
if (!armored) return null;
|
||||
return { signed: Buffer.from(signed, 'latin1'), signature: armored };
|
||||
}
|
||||
module.exports = { createPgpMail, createPassphraseCache, detect, PgpError, splitSigned };
|
||||
@@ -18,10 +18,35 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
||||
onSyncUpdate: callback => ipcRenderer.on('mail:sync-update', (_event, update) => callback(update)),
|
||||
updateMessage: details => ipcRenderer.invoke('mail:update-message', details),
|
||||
setSnooze: details => ipcRenderer.invoke('mail:set-snooze', details),
|
||||
previewAttachment: details => ipcRenderer.invoke('mail:preview-attachment', details),
|
||||
saveAttachment: details => ipcRenderer.invoke('mail:save-attachment', details),
|
||||
openExternal: url => ipcRenderer.invoke('mail:open-external', url),
|
||||
send: message => ipcRenderer.invoke('mail:send', message),
|
||||
disconnect: id => ipcRenderer.invoke('mail:disconnect', id),
|
||||
pgp: {
|
||||
list: () => ipcRenderer.invoke('pgp:list'),
|
||||
generate: details => ipcRenderer.invoke('pgp:generate', details),
|
||||
importKey: details => ipcRenderer.invoke('pgp:import', details),
|
||||
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
|
||||
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
|
||||
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
|
||||
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
|
||||
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
|
||||
checkSend: details => ipcRenderer.invoke('pgp:check-send', details),
|
||||
contacts: () => ipcRenderer.invoke('pgp:contacts'),
|
||||
addContact: details => ipcRenderer.invoke('pgp:add-contact', details),
|
||||
setTrust: (fingerprint, trust) => ipcRenderer.invoke('pgp:set-trust', fingerprint, trust),
|
||||
removeContact: fingerprint => ipcRenderer.invoke('pgp:remove-contact', fingerprint),
|
||||
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
|
||||
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
|
||||
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
|
||||
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases'),
|
||||
keyServers: () => ipcRenderer.invoke('pgp:key-servers'),
|
||||
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'),
|
||||
davConnect: config => ipcRenderer.invoke('dav:connect', config),
|
||||
davActivate: (type, id) => ipcRenderer.invoke('dav:activate', { type, id }),
|
||||
|
||||
+7
-2
@@ -24,6 +24,7 @@
|
||||
<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="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">
|
||||
<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>
|
||||
@@ -32,9 +33,9 @@
|
||||
<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="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
||||
<div id="custom-folders"></div>
|
||||
</nav>
|
||||
<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>
|
||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||
<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>
|
||||
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
||||
@@ -70,5 +71,9 @@
|
||||
<script src="snooze-ui.js"></script>
|
||||
<script src="account-ui.js"></script>
|
||||
<script src="dav-ui.js"></script>
|
||||
<script src="shortcuts.js"></script>
|
||||
<script src="attachments.js"></script>
|
||||
<script src="pgp-ui.js"></script>
|
||||
<script src="pgp-mail-ui.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+94
-8
@@ -140,9 +140,38 @@ async function loadCustomFolders() {
|
||||
} 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() {
|
||||
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;
|
||||
try {
|
||||
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('')}
|
||||
</select>
|
||||
${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':''}>`}
|
||||
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
||||
</div>`).join('');
|
||||
@@ -212,8 +241,8 @@ function openMailAccount(existingAccount = null) {
|
||||
const row = event.target.closest('.mail-rule-row');
|
||||
const value = row.querySelector('.mail-rule-value');
|
||||
if (event.target.value === 'move') {
|
||||
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? 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>`;
|
||||
const selected = value.value || 'Inbox';
|
||||
value.outerHTML = ruleFolderSelect(selected);
|
||||
} else if (value.tagName === 'SELECT') {
|
||||
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) {
|
||||
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 => ({
|
||||
id: draft.id,
|
||||
sender: 'Draft',
|
||||
@@ -302,14 +361,28 @@ function renderDrafts(drafts) {
|
||||
draft
|
||||
})));
|
||||
$('#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-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>';
|
||||
const start = $('#start-draft');
|
||||
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;
|
||||
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);
|
||||
});
|
||||
$('#reader-pane').innerHTML = emptyReader();
|
||||
@@ -584,13 +657,26 @@ if (window.daybreakMail) {
|
||||
sendButton.disabled = true;
|
||||
sendButton.textContent = 'Sending…';
|
||||
try {
|
||||
const pgp = window.pgpPrepareSend ? await window.pgpPrepareSend(recipient, $('#compose-cc').value) : null;
|
||||
if (pgp === false) {
|
||||
sendButton.disabled = false;
|
||||
sendButton.textContent = 'Send ↗';
|
||||
return;
|
||||
}
|
||||
const result = await window.daybreakMail.send({
|
||||
to: recipient,
|
||||
cc: $('#compose-cc').value,
|
||||
subject: $('#compose-subject').value.trim(),
|
||||
text: $('#compose-body').value,
|
||||
displayName: connectedMailAccount.displayName || profileSettings.name
|
||||
displayName: connectedMailAccount.displayName || profileSettings.name,
|
||||
...(pgp ? { pgp } : {})
|
||||
});
|
||||
if (result.failed) {
|
||||
sendButton.disabled = false;
|
||||
sendButton.textContent = 'Send ↗';
|
||||
toast(result.message || 'Message could not be encrypted');
|
||||
return;
|
||||
}
|
||||
if (result.queued) {
|
||||
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
|
||||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
||||
|
||||
Generated
+21
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ep-mail",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.6",
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^8.5.2",
|
||||
"@capacitor/core": "^8.5.2",
|
||||
@@ -14,6 +14,7 @@
|
||||
"imapflow": "2.2.1",
|
||||
"mailparser": "3.9.33",
|
||||
"nodemailer": "10.0.9",
|
||||
"openpgp": "^6.3.2",
|
||||
"tsdav": "^2.3.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -3976,6 +3977,24 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/openpgp": {
|
||||
"version": "6.3.2",
|
||||
"resolved": "https://registry.npmjs.org/openpgp/-/openpgp-6.3.2.tgz",
|
||||
"integrity": "sha512-wcZTzHz41LV8Y48zH/JlD1JT8YdNmpWOuMAjQ/podvvCwsjBEU37K3znJh4UQcj3hksE5z9TzvhbUbwzsGvlLQ==",
|
||||
"license": "LGPL-3.0+",
|
||||
"engines": {
|
||||
"node": ">= 18.0.0",
|
||||
"typescript": ">= 5.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openpgp/web-stream-tools": "~0.3.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@openpgp/web-stream-tools": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/p-cancelable": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
|
||||
|
||||
+9
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.6",
|
||||
"private": true,
|
||||
"description": "Eternity Project mail client",
|
||||
"author": "Eternity Project",
|
||||
@@ -16,10 +16,12 @@
|
||||
"dist:linux:appimage": "electron-builder --linux AppImage",
|
||||
"dist:linux:deb": "electron-builder --linux deb",
|
||||
"bump:build": "npm version patch --no-git-tag-version",
|
||||
"test": "node --test tests/",
|
||||
"build:android-web": "node scripts/prepare-android-web.cjs",
|
||||
"android:sync": "npm run build:android-web && cap sync 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": {
|
||||
"@capacitor/cli": "^8.5.2",
|
||||
@@ -41,6 +43,10 @@
|
||||
"productivity.js",
|
||||
"account-ui.js",
|
||||
"dav-ui.js",
|
||||
"shortcuts.js",
|
||||
"attachments.js",
|
||||
"pgp-ui.js",
|
||||
"pgp-mail-ui.js",
|
||||
"icon.svg",
|
||||
"logo-ep-daylight.svg",
|
||||
"logo-ep-wasteland.svg",
|
||||
@@ -85,6 +91,7 @@
|
||||
"imapflow": "2.2.1",
|
||||
"mailparser": "3.9.33",
|
||||
"nodemailer": "10.0.9",
|
||||
"openpgp": "^6.3.2",
|
||||
"tsdav": "^2.3.4"
|
||||
}
|
||||
}
|
||||
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
|
||||
const pgpApi = () => window.daybreakMail?.pgp;
|
||||
|
||||
function pgpAskPassphrase(title, detail) {
|
||||
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"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
||||
overlay.querySelector('.modal-head span').textContent = title;
|
||||
overlay.querySelector('.account-note').textContent = detail;
|
||||
const finish = value => { overlay.remove(); resolve(value); };
|
||||
overlay.querySelector('form').onsubmit = event => {
|
||||
event.preventDefault();
|
||||
const value = overlay.querySelector('input').value;
|
||||
if (value) finish(value);
|
||||
};
|
||||
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
||||
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
||||
document.body.append(overlay);
|
||||
overlay.querySelector('input').focus();
|
||||
});
|
||||
}
|
||||
|
||||
function pgpFormatFingerprint(value) {
|
||||
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
||||
}
|
||||
|
||||
function pgpSignatureHtml(signatures, encrypted) {
|
||||
const items = Array.isArray(signatures) ? signatures : [];
|
||||
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
||||
if (!items.length) {
|
||||
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
||||
}
|
||||
return items.map(signature => {
|
||||
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
||||
const notes = [];
|
||||
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
||||
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
||||
if (signature.status === 'valid') {
|
||||
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
||||
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${esc(signature.email || 'a known key')}</strong><span>${esc(trust)} · ${esc(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
|
||||
}
|
||||
if (signature.status === 'unknown-key') {
|
||||
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${esc(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
|
||||
}
|
||||
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function pgpAddAttachedKey(key) {
|
||||
const emails = key.emails.join(', ') || 'unknown address';
|
||||
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
||||
try {
|
||||
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
||||
toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
||||
} catch (error) {
|
||||
toast(error.message || 'Could not add the key');
|
||||
}
|
||||
}
|
||||
|
||||
function pgpRenderReaderState(message) {
|
||||
const reader = $('#reader-pane');
|
||||
const header = reader.querySelector('.reader-header');
|
||||
if (!header) return;
|
||||
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
||||
let html = '';
|
||||
if (message.encrypted && !message.pgpDecrypted) {
|
||||
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
||||
} else if (message.encrypted) {
|
||||
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
||||
} else if (message.pgpSignatures) {
|
||||
html = pgpSignatureHtml(message.pgpSignatures, false);
|
||||
}
|
||||
const keys = message.pgpResult?.attachedKeys || [];
|
||||
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${esc(key.emails.join(', ') || 'unknown address')} · ${esc(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
||||
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
||||
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
||||
});
|
||||
const unlock = $('#pgp-unlock');
|
||||
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
||||
}
|
||||
|
||||
async function pgpUnlockMessage(message, interactive) {
|
||||
let passphrase = null;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
let result;
|
||||
try {
|
||||
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
||||
} catch (error) {
|
||||
toast(error.message || 'Could not open this message');
|
||||
return;
|
||||
}
|
||||
if (result.ok) {
|
||||
Object.assign(message, {
|
||||
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
||||
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
||||
});
|
||||
if (activeMessage === message.id) openMessage(message.id);
|
||||
return;
|
||||
}
|
||||
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
|
||||
if (!interactive) { pgpRenderReaderState(message); return; }
|
||||
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
||||
if (passphrase === null) return;
|
||||
continue;
|
||||
}
|
||||
const text = $('#pgp-banner-text');
|
||||
if (text) text.textContent = result.message;
|
||||
else toast(result.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof openMessage === 'function') {
|
||||
const baseOpenMessage = openMessage;
|
||||
openMessage = function (id) {
|
||||
baseOpenMessage(id);
|
||||
const message = messages.find(item => item.id === id);
|
||||
if (!message || !pgpApi()) return;
|
||||
pgpRenderReaderState(message);
|
||||
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
||||
message.pgpAutoTried = true;
|
||||
void pgpUnlockMessage(message, false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Compose: encrypt/sign options.
|
||||
if (typeof showCompose === 'function') {
|
||||
const baseShowCompose = showCompose;
|
||||
showCompose = function (reply, forward = false) {
|
||||
baseShowCompose(reply, forward);
|
||||
const footer = $('#modal-root .compose-footer');
|
||||
if (!footer || !pgpApi()) return;
|
||||
const box = document.createElement('div');
|
||||
box.className = 'pgp-compose';
|
||||
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
||||
footer.prepend(box);
|
||||
let touched = false;
|
||||
const encrypt = $('#pgp-encrypt');
|
||||
const sign = $('#pgp-sign');
|
||||
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
||||
if (touched) encrypt.dataset.touched = '1';
|
||||
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
||||
let timer = null;
|
||||
const refresh = async () => {
|
||||
const to = $('#compose-to')?.value || '';
|
||||
const cc = $('#compose-cc')?.value || '';
|
||||
const hint = $('#pgp-hint');
|
||||
if (!hint) return;
|
||||
if (!to.trim()) { hint.textContent = ''; return; }
|
||||
try {
|
||||
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
||||
if (!$('#pgp-hint')) return;
|
||||
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
||||
else {
|
||||
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
||||
if (!touched && !encrypt.checked) encrypt.checked = true;
|
||||
}
|
||||
} catch { hint.textContent = ''; }
|
||||
};
|
||||
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
||||
['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule));
|
||||
sign.addEventListener('change', schedule);
|
||||
schedule();
|
||||
};
|
||||
}
|
||||
|
||||
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
||||
window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
|
||||
if (!pgpApi()) return null;
|
||||
let encrypt = Boolean($('#pgp-encrypt')?.checked);
|
||||
const sign = Boolean($('#pgp-sign')?.checked);
|
||||
if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
|
||||
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) {
|
||||
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;
|
||||
encrypt = false;
|
||||
if (!sign) return null;
|
||||
}
|
||||
let passphrase = null;
|
||||
if (sign) {
|
||||
if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; }
|
||||
if (!status.signer.unlocked) {
|
||||
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
||||
if (passphrase === null) return false;
|
||||
}
|
||||
}
|
||||
return { encrypt, sign, passphrase };
|
||||
};
|
||||
@@ -0,0 +1,331 @@
|
||||
// Encryption key management (desktop). Hidden where the platform has no key store yet.
|
||||
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
||||
|
||||
function openEncryptionKeys() {
|
||||
const root = $('#modal-root');
|
||||
const account = connectedMailAccount || {};
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
||||
<p class="account-note">OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered. Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
||||
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
||||
<h3 class="pgp-heading">Contact public keys</h3>
|
||||
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
||||
<h3 class="pgp-heading">Public key servers</h3>
|
||||
<p class="account-note">Search only contacts you request; the server can learn which email address you search for. Discovered keys are 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>Search server</span><select id="pgp-search-server"></select></label>
|
||||
<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">Find public key</button></div>
|
||||
<div id="pgp-found-keys" class="attachment-list"></div>
|
||||
<h4 class="pgp-heading">Add a custom HTTPS server</h4>
|
||||
<label class="compose-line"><span>Name</span><input id="pgp-server-name" maxlength="60" placeholder="My key server"></label>
|
||||
<label class="compose-line"><span>HTTPS base URL</span><input id="pgp-server-url" type="url" placeholder="https://keys.example.org"></label>
|
||||
<label class="compose-line"><span>Protocol</span><select id="pgp-server-protocol"><option value="hkp">HKP</option><option value="vks">VKS</option></select></label>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-add-server">Add custom server…</button></div>
|
||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
||||
<h3 class="pgp-heading">Create a key</h3>
|
||||
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label>
|
||||
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${esc(account.email || '')}"></label>
|
||||
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div>
|
||||
<p class="account-note" id="pgp-status" role="status"></p>
|
||||
</div></div></div>`;
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
root.querySelector('.modal-close').onclick = close;
|
||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||
const status = message => { $('#pgp-status').textContent = message; };
|
||||
const passphraseField = () => $('#pgp-passphrase');
|
||||
let keyServers = [];
|
||||
const needPassphrase = () => {
|
||||
const value = passphraseField().value;
|
||||
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
||||
return value;
|
||||
};
|
||||
|
||||
async function render() {
|
||||
const list = $('#pgp-key-list');
|
||||
let keys = [];
|
||||
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
||||
list.replaceChildren();
|
||||
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
||||
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.email || 'OpenPGP key';
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
||||
const fingerprint = document.createElement('small');
|
||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||
info.append(title, meta, fingerprint);
|
||||
row.append(info);
|
||||
const actions = [
|
||||
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
||||
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
||||
];
|
||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||
actions.push(['Delete', async () => {
|
||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
||||
await render();
|
||||
return { deleted: true };
|
||||
}, true]);
|
||||
actions.forEach(([label, run, secret]) => {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'discard';
|
||||
button.textContent = label;
|
||||
button.onclick = async () => {
|
||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||
try {
|
||||
const result = await run();
|
||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||
} catch (error) { status(error.message || 'That action failed.'); }
|
||||
};
|
||||
row.append(button);
|
||||
});
|
||||
const publish = document.createElement('button');
|
||||
publish.className = 'discard';
|
||||
publish.textContent = 'Publish public key…';
|
||||
publish.onclick = async () => {
|
||||
const serverId = $('#pgp-search-server').value;
|
||||
if (!serverId) { status('Choose a key server first.'); return; }
|
||||
publish.disabled = true;
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId });
|
||||
if (result.canceled) return;
|
||||
if (result.warning) status(result.warning);
|
||||
else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${keyServers.find(server => server.id === serverId)?.name || 'the key server'}. 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 this server.');
|
||||
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(`The server accepted the key. Check ${key.email || 'your email'} for a verification message. ${result.message || ''}`.trim());
|
||||
else status(`The server accepted the key. ${result.message || ''}`.trim());
|
||||
} catch (error) { status(error.message || 'Could not publish the public key.'); }
|
||||
finally { publish.disabled = false; }
|
||||
};
|
||||
row.append(publish);
|
||||
list.append(row);
|
||||
});
|
||||
}
|
||||
|
||||
$('#pgp-generate').onclick = async () => {
|
||||
const button = $('#pgp-generate');
|
||||
button.disabled = true;
|
||||
status('Creating key…');
|
||||
try {
|
||||
await window.daybreakMail.pgp.generate({
|
||||
name: $('#pgp-name').value, email: $('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
||||
});
|
||||
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
||||
await render();
|
||||
} catch (error) { status(error.message || 'Could not create the key.'); }
|
||||
button.disabled = false;
|
||||
};
|
||||
$('#pgp-import').onclick = async () => {
|
||||
const passphrase = needPassphrase();
|
||||
if (!passphrase) return;
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
||||
status(result.canceled ? '' : 'Key imported.');
|
||||
await render();
|
||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||
};
|
||||
async function renderContacts() {
|
||||
const list = $('#pgp-contact-list');
|
||||
let contacts = [];
|
||||
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
||||
list.replaceChildren();
|
||||
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
||||
contacts.forEach(contact => {
|
||||
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 = contact.emails.join(', ') || contact.name || 'Public key';
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
||||
const fingerprint = document.createElement('small');
|
||||
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||
info.append(title, meta, fingerprint);
|
||||
const trust = document.createElement('select');
|
||||
trust.className = 'pgp-trust';
|
||||
trust.setAttribute('aria-label', 'Key trust');
|
||||
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
||||
const option = document.createElement('option');
|
||||
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
||||
trust.append(option);
|
||||
});
|
||||
trust.onchange = async () => {
|
||||
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
||||
trust.value = contact.trust;
|
||||
return;
|
||||
}
|
||||
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
||||
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
||||
};
|
||||
const actions = [
|
||||
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
||||
['Remove', async () => {
|
||||
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
||||
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
||||
await renderContacts();
|
||||
return { deleted: true };
|
||||
}]
|
||||
];
|
||||
row.append(info, trust);
|
||||
actions.forEach(([label, run]) => {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'discard';
|
||||
button.textContent = label;
|
||||
button.onclick = async () => {
|
||||
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||
catch (error) { status(error.message || 'That action failed.'); }
|
||||
};
|
||||
row.append(button);
|
||||
});
|
||||
list.append(row);
|
||||
});
|
||||
}
|
||||
|
||||
$('#pgp-add-contact').onclick = async () => {
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.addContact({});
|
||||
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
||||
await renderContacts();
|
||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||
};
|
||||
async function renderKeyServers() {
|
||||
const list = $('#pgp-server-list');
|
||||
const selector = $('#pgp-search-server');
|
||||
try { keyServers = await window.daybreakMail.pgp.keyServers(); }
|
||||
catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; }
|
||||
selector.replaceChildren();
|
||||
keyServers.forEach(server => {
|
||||
const option = document.createElement('option');
|
||||
option.value = server.id;
|
||||
option.textContent = `${server.name} (${server.protocol.toUpperCase()})`;
|
||||
selector.append(option);
|
||||
});
|
||||
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);
|
||||
row.append(info);
|
||||
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({
|
||||
serverId: $('#pgp-search-server').value,
|
||||
email: $('#pgp-search-email').value
|
||||
});
|
||||
results.replaceChildren();
|
||||
if (!found.length) { results.textContent = 'No matching public key was found.'; return; }
|
||||
found.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 ${keyServers.find(server => server.id === $('#pgp-search-server').value)?.name || 'key server'} · 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);
|
||||
});
|
||||
status(`Found ${found.length} public key(s). They remain unverified until you check their fingerprints independently.`);
|
||||
} catch (error) {
|
||||
results.textContent = '';
|
||||
status(error.message || 'Could not search the key server.');
|
||||
} finally { button.disabled = false; }
|
||||
};
|
||||
$('#pgp-add-server').onclick = async () => {
|
||||
const button = $('#pgp-add-server');
|
||||
button.disabled = true;
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.addKeyServer({
|
||||
name: $('#pgp-server-name').value,
|
||||
url: $('#pgp-server-url').value,
|
||||
protocol: $('#pgp-server-protocol').value
|
||||
});
|
||||
if (result.canceled) return;
|
||||
$('#pgp-server-name').value = '';
|
||||
$('#pgp-server-url').value = '';
|
||||
await renderKeyServers();
|
||||
status('Custom key server added.');
|
||||
} catch (error) { status(error.message || 'Could not add the key server.'); }
|
||||
finally { button.disabled = false; }
|
||||
};
|
||||
window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||
$('#pgp-save-cache').onclick = async () => {
|
||||
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number($('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||
};
|
||||
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||
void renderKeyServers();
|
||||
void renderContacts();
|
||||
void render();
|
||||
}
|
||||
|
||||
if (typeof openPreferences === 'function') {
|
||||
const baseOpenPreferences = openPreferences;
|
||||
openPreferences = function () {
|
||||
baseOpenPreferences();
|
||||
const fields = $('#modal-root .compose-fields');
|
||||
if (!fields || !pgpAvailable()) return;
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'discard';
|
||||
button.id = 'open-encryption-keys';
|
||||
button.textContent = 'Encryption keys…';
|
||||
button.onclick = openEncryptionKeys;
|
||||
fields.append(button);
|
||||
};
|
||||
}
|
||||
@@ -530,6 +530,7 @@
|
||||
updateMessage: (details) => EpMail.updateMessage(details),
|
||||
setSnooze: (details) => EpMail.setSnooze(details),
|
||||
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
||||
previewAttachment: (details) => EpMail.previewAttachment(details),
|
||||
saveAttachment: (details) => EpMail.saveAttachment(details),
|
||||
openExternal: (url) => EpMail.openExternal({ url }),
|
||||
send: (message) => EpMail.send(message),
|
||||
|
||||
@@ -22,6 +22,7 @@ if (Capacitor.isNativePlatform() && Capacitor.getPlatform() === 'android') {
|
||||
updateMessage: details => EpMail.updateMessage(details),
|
||||
setSnooze: details => EpMail.setSnooze(details),
|
||||
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
||||
previewAttachment: details => EpMail.previewAttachment(details),
|
||||
saveAttachment: details => EpMail.saveAttachment(details),
|
||||
openExternal: url => EpMail.openExternal({ url }),
|
||||
send: message => EpMail.send(message),
|
||||
|
||||
@@ -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)" }
|
||||
@@ -13,6 +13,10 @@ const assets = [
|
||||
'productivity.js',
|
||||
'account-ui.js',
|
||||
'dav-ui.js',
|
||||
'shortcuts.js',
|
||||
'attachments.js',
|
||||
'pgp-ui.js',
|
||||
'pgp-mail-ui.js',
|
||||
'icon.svg',
|
||||
'logo-ep-daylight.svg',
|
||||
'logo-ep-wasteland.svg',
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
const CACHE='ep-mail-v3';
|
||||
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','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
const CACHE='ep-mail-v7';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
||||
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
// Configurable keyboard shortcuts for common mail actions.
|
||||
const shortcutStorageKey = 'daybreak-shortcuts';
|
||||
const shortcutActions = [
|
||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
|
||||
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
|
||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
|
||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
|
||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
|
||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
|
||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
|
||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
|
||||
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
|
||||
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
|
||||
];
|
||||
|
||||
function normalizeShortcut(value) {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return '';
|
||||
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
|
||||
const key = parts.pop() || '+';
|
||||
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
|
||||
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
|
||||
}
|
||||
|
||||
function loadShortcuts() {
|
||||
let saved = {};
|
||||
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
|
||||
return Object.fromEntries(shortcutActions.map(action => [
|
||||
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
|
||||
]));
|
||||
}
|
||||
|
||||
function eventShortcut(event) {
|
||||
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
|
||||
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
|
||||
const printable = event.key.length === 1;
|
||||
if (event.shiftKey && !printable) mods.push('Shift');
|
||||
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
|
||||
}
|
||||
|
||||
function moveMessageSelection(step) {
|
||||
if (!messages.length) return;
|
||||
const index = messages.findIndex(message => message.id === activeMessage);
|
||||
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
|
||||
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
|
||||
const target = event.target;
|
||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
|
||||
const pressed = eventShortcut(event);
|
||||
if (!pressed) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
|
||||
if (!action) return;
|
||||
event.preventDefault();
|
||||
action.run();
|
||||
});
|
||||
|
||||
if (typeof openPreferences === 'function') {
|
||||
const baseOpenPreferences = openPreferences;
|
||||
openPreferences = function () {
|
||||
baseOpenPreferences();
|
||||
const fields = $('#modal-root .compose-fields');
|
||||
const save = $('#save-appearance');
|
||||
if (!fields || !save) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
const section = document.createElement('div');
|
||||
section.className = 'shortcut-settings';
|
||||
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
||||
fields.append(section);
|
||||
section.addEventListener('keydown', event => {
|
||||
const input = event.target.closest('.shortcut-input');
|
||||
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
||||
const combo = eventShortcut(event);
|
||||
if (combo) input.value = combo;
|
||||
});
|
||||
$('#reset-shortcuts').onclick = () => {
|
||||
section.querySelectorAll('.shortcut-input').forEach(input => {
|
||||
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
||||
});
|
||||
};
|
||||
const baseSave = save.onclick;
|
||||
save.onclick = event => {
|
||||
const values = {};
|
||||
const used = new Map();
|
||||
for (const input of section.querySelectorAll('.shortcut-input')) {
|
||||
const value = normalizeShortcut(input.value);
|
||||
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
||||
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||
if (value) used.set(value, label);
|
||||
values[input.dataset.action] = value;
|
||||
}
|
||||
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
||||
baseSave?.call(save, event);
|
||||
};
|
||||
};
|
||||
}
|
||||
+14
@@ -126,3 +126,17 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
|
||||
|
||||
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
|
||||
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
||||
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
|
||||
|
||||
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
|
||||
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
|
||||
.pgp-status small{opacity:.85}.pgp-ok{border-color:#3d7a4f;background:rgba(61,122,79,.12)}.pgp-warn{border-color:#b8860b;background:rgba(184,134,11,.14)}.pgp-bad{border-color:#b3261e;background:rgba(179,38,30,.14)}
|
||||
.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-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)}
|
||||
|
||||
.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}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { simpleParser } = require('mailparser');
|
||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||
const { createPgpMail, createPassphraseCache } = require('../desktop/pgp-mail.cjs');
|
||||
|
||||
const gpgPath = [process.env.GPG_PATH, 'gpg', 'C:\\Program Files\\GnuPG\\bin\\gpg.exe', 'C:\\Program Files (x86)\\GnuPG\\bin\\gpg.exe']
|
||||
.filter(Boolean).find(candidate => spawnSync(candidate, ['--version']).status === 0);
|
||||
const skip = gpgPath ? false : 'GnuPG is not installed';
|
||||
const PASS = 'interop passphrase';
|
||||
|
||||
function gpgIn(home) {
|
||||
return (args, input) => {
|
||||
const result = spawnSync(gpgPath, ['--homedir', home, '--batch', '--yes', '--pinentry-mode', 'loopback', '--passphrase', PASS, '--trust-model', 'always', ...args], { input });
|
||||
if (result.status !== 0) throw new Error(`gpg ${args.join(' ')} failed: ${result.stderr}`);
|
||||
return { out: result.stdout, err: result.stderr.toString() };
|
||||
};
|
||||
}
|
||||
|
||||
async function setup() {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ep-gnupg-'));
|
||||
const gpg = gpgIn(home);
|
||||
gpg(['--quick-generate-key', 'Gina Gnu <gina@example.com>', 'ed25519', 'cert', 'never']);
|
||||
const fingerprint = /^fpr:::::::::([0-9A-F]+):/m.exec(gpg(['--list-keys', '--with-colons', 'gina@example.com']).out.toString())[1];
|
||||
gpg(['--quick-add-key', fingerprint, 'cv25519', 'encr', 'never']);
|
||||
gpg(['--quick-add-key', fingerprint, 'ed25519', 'sign', 'never']);
|
||||
let data = null;
|
||||
const keyStore = createKeyStore({ async load() { return data && JSON.parse(JSON.stringify(data)); }, async save(value) { data = JSON.parse(JSON.stringify(value)); } });
|
||||
const mail = createPgpMail({ keyStore, cache: createPassphraseCache(async () => 10) });
|
||||
const { key } = await keyStore.generate({ name: 'Eppu Mail', email: 'eppu@example.com', passphrase: PASS });
|
||||
gpg(['--import'], Buffer.from(await keyStore.exportPublic(key.fingerprint)));
|
||||
await keyStore.addContact({ armoredKey: gpg(['--armor', '--export', 'gina@example.com']).out.toString() });
|
||||
return { home, gpg, keyStore, mail };
|
||||
}
|
||||
|
||||
const options = extra => ({
|
||||
from: { name: 'Eppu Mail', address: 'eppu@example.com' }, to: 'Gina Gnu <gina@example.com>',
|
||||
subject: 'Interop', text: 'Hello from ep-mail ✓', messageId: '<interop@ep-mail.local>', passphrase: PASS, ...extra
|
||||
});
|
||||
|
||||
test('GnuPG decrypts and verifies mail encrypted and signed by ep-mail', { skip }, async () => {
|
||||
const { home, gpg, mail } = await setup();
|
||||
try {
|
||||
const { raw } = await mail.build(options({ encrypt: true, sign: true }));
|
||||
const parsed = await simpleParser(raw);
|
||||
const armored = /-----BEGIN PGP MESSAGE-----[\s\S]+?-----END PGP MESSAGE-----/.exec(parsed.attachments[1]?.content?.toString() || parsed.attachments[0].content.toString())[0];
|
||||
const { out, err } = gpg(['--decrypt'], Buffer.from(armored));
|
||||
assert.match((await simpleParser(out)).text, /Hello from ep-mail ✓/);
|
||||
assert.match(err, /Good signature from "Eppu Mail <eppu@example.com>"/);
|
||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('GnuPG verifies PGP/MIME signed-only mail from ep-mail', { skip }, async () => {
|
||||
const { home, gpg, mail } = await setup();
|
||||
try {
|
||||
const { raw } = await mail.build(options({ sign: true }));
|
||||
const text = raw.toString('latin1');
|
||||
const { splitSigned } = require('../desktop/pgp-mail.cjs');
|
||||
const boundary = /boundary="([^"]+)"/.exec(text)[1];
|
||||
const parts = splitSigned(raw, boundary);
|
||||
const signaturePath = path.join(home, 'sig.asc');
|
||||
const dataPath = path.join(home, 'data.bin');
|
||||
fs.writeFileSync(signaturePath, parts.signature);
|
||||
fs.writeFileSync(dataPath, parts.signed);
|
||||
const { err } = gpg(['--verify', signaturePath, dataPath]);
|
||||
assert.match(err, /Good signature from "Eppu Mail/);
|
||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('ep-mail decrypts GnuPG-encrypted PGP/MIME mail and verifies its signature', { skip }, async () => {
|
||||
const { home, gpg, mail, keyStore } = await setup();
|
||||
try {
|
||||
const inner = Buffer.from('Content-Type: text/plain; charset=utf-8\r\n\r\nHello from GnuPG ✓\r\n');
|
||||
const armored = gpg(['--armor', '--encrypt', '--sign', '--local-user', 'gina@example.com', '--recipient', 'eppu@example.com'], inner).out.toString();
|
||||
const source = Buffer.from(`From: Gina Gnu <gina@example.com>\r\nTo: eppu@example.com\r\nSubject: from gpg\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="gb"\r\n\r\n--gb\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--gb\r\nContent-Type: application/octet-stream; name="encrypted.asc"\r\n\r\n${armored}\r\n--gb--\r\n`);
|
||||
const result = await mail.decrypt(await simpleParser(source), { passphrase: PASS });
|
||||
assert.match(result.parsed.text, /Hello from GnuPG ✓/);
|
||||
assert.equal(result.signatures[0].status, 'valid');
|
||||
assert.equal(result.signatures[0].matchesSender, true);
|
||||
assert.ok(await keyStore.listContacts());
|
||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('ep-mail decrypts GnuPG inline PGP and verifies GnuPG clear-signed and PGP/MIME signed mail', { skip }, async () => {
|
||||
const { home, gpg, mail } = await setup();
|
||||
try {
|
||||
const inline = gpg(['--armor', '--encrypt', '--recipient', 'eppu@example.com'], Buffer.from('inline from gpg')).out.toString();
|
||||
const inlineSource = Buffer.from(`From: gina@example.com\r\nSubject: i\r\nContent-Type: text/plain\r\n\r\n${inline}\r\n`);
|
||||
assert.match((await mail.decrypt(await simpleParser(inlineSource), { passphrase: PASS })).parsed.text, /inline from gpg/);
|
||||
|
||||
const clear = gpg(['--clearsign', '--local-user', 'gina@example.com'], Buffer.from('clear signed text\n')).out.toString().replace(/\r?\n/g, '\r\n');
|
||||
const clearSource = Buffer.from(`From: gina@example.com\r\nSubject: c\r\nContent-Type: text/plain\r\n\r\n${clear}\r\n`);
|
||||
assert.equal((await mail.verifySigned(await simpleParser(clearSource), clearSource))[0].status, 'valid');
|
||||
|
||||
const signedPart = 'Content-Type: text/plain; charset=utf-8\r\n\r\nsigned by gpg';
|
||||
const detached = gpg(['--armor', '--detach-sign', '--local-user', 'gina@example.com'], Buffer.from(signedPart)).out.toString().replace(/\r?\n/g, '\r\n').trim();
|
||||
const mimeSource = Buffer.from(`From: gina@example.com\r\nSubject: m\r\nMIME-Version: 1.0\r\nContent-Type: multipart/signed; protocol="application/pgp-signature"; micalg=pgp-sha512; boundary="sb"\r\n\r\n--sb\r\n${signedPart}\r\n--sb\r\nContent-Type: application/pgp-signature\r\n\r\n${detached}\r\n--sb--\r\n`);
|
||||
assert.equal((await mail.verifySigned(await simpleParser(mimeSource), mimeSource))[0].status, 'valid');
|
||||
} finally { fs.rmSync(home, { recursive: true, force: true }); }
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const openpgp = require('openpgp');
|
||||
const { createKeyServerService, 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('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('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/);
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const openpgp = require('openpgp');
|
||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||
|
||||
function memoryStore() {
|
||||
let data = null;
|
||||
return { load: async () => data, save: async value => { data = JSON.parse(JSON.stringify(value)); } };
|
||||
}
|
||||
|
||||
const passphrase = 'correct horse battery';
|
||||
|
||||
test('generates a passphrase-protected key and never lists secrets', async () => {
|
||||
const storage = memoryStore();
|
||||
const keys = createKeyStore(storage);
|
||||
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||
assert.match(key.fingerprint, /^[0-9A-F]{40,64}$/);
|
||||
assert.ok(revocationCertificate.includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
||||
const listed = await keys.list();
|
||||
assert.equal(listed.length, 1);
|
||||
assert.equal(JSON.stringify(listed).includes('PRIVATE'), false);
|
||||
const stored = (await storage.load()).keys[0];
|
||||
const parsed = await openpgp.readPrivateKey({ armoredKey: stored.privateKey });
|
||||
assert.equal(parsed.isDecrypted(), false);
|
||||
});
|
||||
|
||||
test('rejects weak passphrases and bad addresses', async () => {
|
||||
const keys = createKeyStore(memoryStore());
|
||||
await assert.rejects(keys.generate({ name: 'A', email: 'a@example.com', passphrase: 'short' }), /at least 8/);
|
||||
await assert.rejects(keys.generate({ name: 'A', email: 'nope', passphrase }), /valid email/);
|
||||
});
|
||||
|
||||
test('export requires the right passphrase and round-trips through import', async () => {
|
||||
const first = createKeyStore(memoryStore());
|
||||
const { key } = await first.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
|
||||
await assert.rejects(first.exportPrivate(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
||||
const armored = await first.exportPrivate(key.fingerprint, passphrase);
|
||||
const second = createKeyStore(memoryStore());
|
||||
const imported = await second.import({ armoredKey: armored, passphrase });
|
||||
assert.equal(imported.fingerprint, key.fingerprint);
|
||||
assert.equal(imported.email, 'ada@example.com');
|
||||
await assert.rejects(second.import({ armoredKey: armored, passphrase }), /already/);
|
||||
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
||||
});
|
||||
|
||||
test('imports an unprotected key by encrypting it with the given passphrase', async () => {
|
||||
const { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
|
||||
const keys = createKeyStore(memoryStore());
|
||||
const imported = await keys.import({ armoredKey: privateKey, passphrase });
|
||||
const exported = await keys.exportPrivate(imported.fingerprint, passphrase);
|
||||
assert.equal((await openpgp.readPrivateKey({ armoredKey: exported })).isDecrypted(), false);
|
||||
});
|
||||
|
||||
test('rejects invalid key material and a wrong passphrase on import', async () => {
|
||||
const keys = createKeyStore(memoryStore());
|
||||
await assert.rejects(keys.import({ armoredKey: 'not a key', passphrase }), /valid OpenPGP/);
|
||||
const source = createKeyStore(memoryStore());
|
||||
const { key } = await source.generate({ name: 'C', email: 'c@example.com', passphrase });
|
||||
const armored = await source.exportPrivate(key.fingerprint, passphrase);
|
||||
await assert.rejects(keys.import({ armoredKey: armored, passphrase: 'another passphrase' }), /incorrect/);
|
||||
});
|
||||
|
||||
test('deleting a key needs the passphrase', async () => {
|
||||
const keys = createKeyStore(memoryStore());
|
||||
const { key } = await keys.generate({ name: 'D', email: 'd@example.com', passphrase });
|
||||
await assert.rejects(keys.remove(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
||||
assert.equal((await keys.list()).length, 1);
|
||||
await keys.remove(key.fingerprint, passphrase);
|
||||
assert.equal((await keys.list()).length, 0);
|
||||
});
|
||||
|
||||
test('stored revocation certificate is returned only after unlocking', async () => {
|
||||
const keys = createKeyStore(memoryStore());
|
||||
const { key } = await keys.generate({ name: 'E', email: 'e@example.com', passphrase });
|
||||
await assert.rejects(keys.exportRevocation(key.fingerprint, 'wrong passphrase'), /incorrect/);
|
||||
assert.ok((await keys.exportRevocation(key.fingerprint, passphrase)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
|
||||
});
|
||||
@@ -0,0 +1,184 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const openpgp = require('openpgp');
|
||||
const MailComposer = require('nodemailer/lib/mail-composer');
|
||||
const { simpleParser } = require('mailparser');
|
||||
const { createKeyStore } = require('../desktop/pgp-keystore.cjs');
|
||||
const { createPgpMail, createPassphraseCache, detect } = require('../desktop/pgp-mail.cjs');
|
||||
|
||||
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 actor(name, email, passphrase = 'correct horse') {
|
||||
const keyStore = createKeyStore(memoryStore());
|
||||
const cache = createPassphraseCache(async () => 10);
|
||||
const mail = createPgpMail({ keyStore, cache });
|
||||
const { key } = await keyStore.generate({ name, email, passphrase });
|
||||
return { keyStore, cache, mail, key, email, passphrase, name };
|
||||
}
|
||||
|
||||
async function exchange(a, b) {
|
||||
await a.keyStore.addContact({ armoredKey: await b.keyStore.exportPublic(b.key.fingerprint) });
|
||||
await b.keyStore.addContact({ armoredKey: await a.keyStore.exportPublic(a.key.fingerprint) });
|
||||
}
|
||||
|
||||
const sendOptions = (from, to, extra = {}) => ({
|
||||
from: { name: from.name, address: from.email }, to, subject: 'Héllo secrèt', text: 'Top secret ✓\nline two', messageId: '<abc@ep-mail.local>', ...extra
|
||||
});
|
||||
|
||||
test('encrypts and signs for a recipient and the sender can read the copy', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
await exchange(alice, bob);
|
||||
const { raw, envelope } = await alice.mail.build(sendOptions(alice, 'Bob <bob@example.com>', { encrypt: true, sign: true, passphrase: alice.passphrase }));
|
||||
assert.deepEqual(envelope.to, ['bob@example.com']);
|
||||
assert.ok(!raw.toString('latin1').includes('Top secret'));
|
||||
const parsed = await simpleParser(raw);
|
||||
assert.equal(parsed.subject, 'Héllo secrèt');
|
||||
assert.equal(detect(parsed), 'encrypted-mime');
|
||||
await assert.rejects(() => bob.mail.decrypt(parsed), error => error.code === 'PASSPHRASE_REQUIRED');
|
||||
await assert.rejects(() => bob.mail.decrypt(parsed, { passphrase: 'wrong wrong' }), error => error.code === 'BAD_PASSPHRASE');
|
||||
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
||||
assert.equal(result.parsed.text.trim(), 'Top secret ✓\nline two');
|
||||
assert.equal(result.signatures[0].status, 'valid');
|
||||
assert.equal(result.signatures[0].matchesSender, true);
|
||||
const again = await bob.mail.decrypt(await simpleParser(raw));
|
||||
assert.equal(again.signatures.length, 1);
|
||||
const own = await alice.mail.decrypt(parsed, { passphrase: alice.passphrase });
|
||||
assert.match(own.parsed.text, /Top secret/);
|
||||
});
|
||||
|
||||
test('refuses to encrypt without a recipient key instead of downgrading', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
await assert.rejects(
|
||||
() => alice.mail.build(sendOptions(alice, 'carol@example.com', { encrypt: true })),
|
||||
error => error.code === 'NO_RECIPIENT_KEY' && error.details.missing[0] === 'carol@example.com'
|
||||
);
|
||||
const status = await alice.mail.recipientStatus(['carol@example.com'], { sign: true, from: 'alice@example.com' });
|
||||
assert.deepEqual(status.missing, ['carol@example.com']);
|
||||
assert.equal(status.signer.email, 'alice@example.com');
|
||||
});
|
||||
|
||||
test('encrypts to several recipients and each can decrypt', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
const carol = await actor('Carol', 'carol@example.com');
|
||||
for (const other of [bob, carol]) await alice.keyStore.addContact({ armoredKey: await other.keyStore.exportPublic(other.key.fingerprint) });
|
||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { cc: 'carol@example.com', encrypt: true }));
|
||||
const parsed = await simpleParser(raw);
|
||||
for (const reader of [bob, carol]) {
|
||||
const result = await reader.mail.decrypt(parsed, { passphrase: reader.passphrase });
|
||||
assert.match(result.parsed.text, /Top secret/);
|
||||
assert.equal(result.signatures.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('detects tampered and corrupted encrypted messages', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
await exchange(alice, bob);
|
||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { encrypt: true, sign: true, passphrase: alice.passphrase }));
|
||||
const text = raw.toString('latin1');
|
||||
const lines = text.split('\r\n');
|
||||
const at = lines.findIndex((line, index) => index > 5 && line.length >= 60 && !line.startsWith('-') && !line.includes(':'));
|
||||
lines[at] = lines[at].slice(0, 20) + (lines[at][20] === 'A' ? 'B' : 'A') + lines[at].slice(21);
|
||||
const broken = await simpleParser(Buffer.from(lines.join('\r\n'), 'latin1'));
|
||||
await assert.rejects(() => bob.mail.decrypt(broken, { passphrase: bob.passphrase }), error => ['CORRUPT'].includes(error.code));
|
||||
const empty = await simpleParser(Buffer.from(text.replace(/-----BEGIN PGP MESSAGE-----[\s\S]*-----END PGP MESSAGE-----/, 'nothing'), 'latin1'));
|
||||
await assert.rejects(() => bob.mail.decrypt(empty), error => error.code === 'CORRUPT');
|
||||
});
|
||||
|
||||
test('reports unknown signers and a changed key for a known sender', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
|
||||
await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
||||
const impostor = await actor('Alice', 'alice@example.com');
|
||||
await impostor.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
||||
const { raw } = await impostor.mail.build(sendOptions(impostor, 'bob@example.com', { encrypt: true, sign: true, passphrase: impostor.passphrase }));
|
||||
const result = await bob.mail.decrypt(await simpleParser(raw), { passphrase: bob.passphrase });
|
||||
assert.equal(result.signatures[0].status, 'unknown-key');
|
||||
assert.equal(result.signatures[0].keyChanged, true);
|
||||
const added = await bob.keyStore.addContact({ armoredKey: await impostor.keyStore.exportPublic(impostor.key.fingerprint) });
|
||||
assert.deepEqual(added.keyChangedFrom, [alice.key.fingerprint]);
|
||||
const second = await bob.mail.decrypt(await simpleParser(raw));
|
||||
assert.equal(second.signatures[0].status, 'valid');
|
||||
assert.equal(second.signatures[0].keyChanged, false);
|
||||
});
|
||||
|
||||
test('signs without encrypting and verifies PGP/MIME signatures', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
await bob.keyStore.addContact({ armoredKey: await alice.keyStore.exportPublic(alice.key.fingerprint) });
|
||||
const { raw } = await alice.mail.build(sendOptions(alice, 'bob@example.com', { sign: true, passphrase: alice.passphrase }));
|
||||
const parsed = await simpleParser(raw);
|
||||
assert.equal(detect(parsed), 'signed-mime');
|
||||
assert.match(parsed.text, /Top secret/);
|
||||
const [signature] = await bob.mail.verifySigned(parsed, raw);
|
||||
assert.equal(signature.status, 'valid');
|
||||
const altered = Buffer.from(raw.toString('latin1').replace('Content-Type: text/plain', 'Content-Type: text/plain'), 'latin1');
|
||||
const [bad] = await bob.mail.verifySigned(await simpleParser(altered), altered);
|
||||
assert.equal(bad.status, 'invalid');
|
||||
});
|
||||
|
||||
test('reads inline PGP messages and cleartext signatures', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
await exchange(alice, bob);
|
||||
const bobKey = (await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }));
|
||||
const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ text: 'inline body' }), encryptionKeys: bobKey });
|
||||
const source = Buffer.from(`From: Alice <alice@example.com>\r\nTo: bob@example.com\r\nSubject: inline\r\nContent-Type: text/plain\r\n\r\n${armored}\r\n`);
|
||||
const parsed = await simpleParser(source);
|
||||
assert.equal(detect(parsed), 'encrypted-inline');
|
||||
const result = await bob.mail.decrypt(parsed, { passphrase: bob.passphrase });
|
||||
assert.equal(result.parsed.text.trim(), 'inline body');
|
||||
const aliceSigner = await alice.keyStore.unlockKey(alice.key.fingerprint, alice.passphrase);
|
||||
const cleartext = await openpgp.sign({ message: await openpgp.createCleartextMessage({ text: 'hello signed' }), signingKeys: aliceSigner });
|
||||
const signedSource = Buffer.from(`From: alice@example.com\r\nSubject: s\r\nContent-Type: text/plain\r\n\r\n${cleartext}\r\n`);
|
||||
const signedParsed = await simpleParser(signedSource);
|
||||
assert.equal(detect(signedParsed), 'signed-inline');
|
||||
assert.equal((await bob.mail.verifySigned(signedParsed, signedSource))[0].status, 'valid');
|
||||
});
|
||||
|
||||
test('decrypts large messages with attachments from other clients', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
const inner = await new Promise((resolve, reject) => new MailComposer({
|
||||
text: 'with attachment', attachments: [{ filename: 'big.bin', content: Buffer.alloc(8 * 1048576, 7) }]
|
||||
}).compile().build((error, message) => error ? reject(error) : resolve(message)));
|
||||
const bobKey = await openpgp.readKey({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) });
|
||||
const armored = await openpgp.encrypt({ message: await openpgp.createMessage({ binary: inner }), encryptionKeys: bobKey });
|
||||
const source = Buffer.from(`From: alice@example.com\r\nTo: bob@example.com\r\nSubject: big\r\nMIME-Version: 1.0\r\nContent-Type: multipart/encrypted; protocol="application/pgp-encrypted"; boundary="b1"\r\n\r\n--b1\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n--b1\r\nContent-Type: application/octet-stream\r\n\r\n${armored}\r\n--b1--\r\n`);
|
||||
const result = await bob.mail.decrypt(await simpleParser(source), { passphrase: bob.passphrase });
|
||||
assert.equal(result.parsed.attachments[0].filename, 'big.bin');
|
||||
assert.equal(result.parsed.attachments[0].content.length, 8 * 1048576);
|
||||
});
|
||||
|
||||
test('keyring: contacts, trust levels, expired passphrase cache and settings', async () => {
|
||||
const alice = await actor('Alice', 'alice@example.com');
|
||||
const bob = await actor('Bob', 'bob@example.com');
|
||||
const { contact } = await alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint), source: 'message' });
|
||||
assert.equal(contact.trust, 'unknown');
|
||||
assert.equal((await alice.keyStore.setTrust(contact.fingerprint, 'verified')).trust, 'verified');
|
||||
await assert.rejects(() => alice.keyStore.setTrust(contact.fingerprint, 'bogus'));
|
||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
|
||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
|
||||
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
|
||||
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [] });
|
||||
const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' };
|
||||
await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer] });
|
||||
assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0);
|
||||
await alice.keyStore.setSettings({ cacheMinutes: 5 });
|
||||
assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]);
|
||||
await alice.keyStore.removeContact(contact.fingerprint);
|
||||
assert.equal((await alice.keyStore.listContacts()).length, 0);
|
||||
|
||||
let clock = 1000;
|
||||
const cache = createPassphraseCache(async () => 1, () => clock);
|
||||
await cache.remember('F', 'secret');
|
||||
assert.equal(cache.get('F'), 'secret');
|
||||
clock += 61000;
|
||||
assert.equal(cache.get('F'), null);
|
||||
});
|
||||
@@ -0,0 +1,161 @@
|
||||
// Attachment previews and a dedicated view for finding and managing attachments across mailboxes.
|
||||
const attachmentFolders = ['Inbox', 'Sent', 'Archive', 'Trash'];
|
||||
let attachmentItems = [];
|
||||
|
||||
function attachmentKind(filename) {
|
||||
const ext = String(filename).toLowerCase().split('.').pop();
|
||||
if (['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'].includes(ext)) return 'Images';
|
||||
if (['pdf', 'doc', 'docx', 'odt', 'txt', 'rtf', 'md', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) return 'Documents';
|
||||
if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) return 'Archives';
|
||||
return 'Other';
|
||||
}
|
||||
|
||||
function attachmentSize(size) {
|
||||
if (!size) return '';
|
||||
if (typeof size === 'string') return size;
|
||||
return size < 1048576 ? `${Math.max(1, Math.round(size / 1024))} KB` : `${(size / 1048576).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
async function previewAttachment(target, details) {
|
||||
if (!details.uid || !window.daybreakMail?.previewAttachment) {
|
||||
target.textContent = 'Previews are available for connected mailbox messages.';
|
||||
return;
|
||||
}
|
||||
target.textContent = 'Loading preview…';
|
||||
try {
|
||||
const result = await window.daybreakMail.previewAttachment(details);
|
||||
target.replaceChildren();
|
||||
if (result.kind === 'image') {
|
||||
const image = document.createElement('img');
|
||||
image.className = 'attachment-preview-image';
|
||||
image.alt = details.filename;
|
||||
image.src = result.dataUrl;
|
||||
target.append(image);
|
||||
} else if (result.kind === 'text') {
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'attachment-preview-text';
|
||||
pre.textContent = result.text + (result.truncated ? '\n… (preview truncated)' : '');
|
||||
target.append(pre);
|
||||
} else {
|
||||
target.textContent = result.reason || 'No preview is available for this file type.';
|
||||
}
|
||||
} catch (error) {
|
||||
target.textContent = error.message || 'Could not load the preview.';
|
||||
}
|
||||
}
|
||||
|
||||
function downloadAttachment(details) {
|
||||
if (!details.uid || !window.daybreakMail?.saveAttachment) { toast('Attachment download is available for connected mailbox messages'); return; }
|
||||
window.daybreakMail.saveAttachment(details)
|
||||
.then(result => { if (result.saved) toast('Attachment saved'); })
|
||||
.catch(error => toast(error.message || 'Could not save attachment'));
|
||||
}
|
||||
|
||||
// Add a Preview button to each attachment in the reader.
|
||||
if (typeof openMessage === 'function') {
|
||||
const baseOpenMessage = openMessage;
|
||||
openMessage = function (id) {
|
||||
baseOpenMessage(id);
|
||||
const message = messages.find(item => item.id === id);
|
||||
if (!message?.uid) return;
|
||||
$$('#reader-pane .attachment').forEach(row => {
|
||||
const download = row.querySelector('.download');
|
||||
if (!download || row.querySelector('.preview-attachment')) return;
|
||||
const button = document.createElement('button');
|
||||
button.className = 'preview-attachment icon-button';
|
||||
button.title = 'Preview';
|
||||
button.setAttribute('aria-label', `Preview ${download.dataset.filename}`);
|
||||
button.textContent = '👁';
|
||||
button.addEventListener('click', event => {
|
||||
event.stopPropagation();
|
||||
let panel = row.nextElementSibling?.classList.contains('attachment-preview') ? row.nextElementSibling : null;
|
||||
if (panel) { panel.remove(); return; }
|
||||
panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
row.after(panel);
|
||||
void previewAttachment(panel, { uid: message.uid, folder: message.sourceFolder || activeFolder, filename: download.dataset.filename });
|
||||
});
|
||||
download.before(button);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
async function collectAttachments() {
|
||||
const items = [];
|
||||
for (const folder of attachmentFolders) {
|
||||
let offset = 0;
|
||||
for (let page = 0; page < 5; page += 1) {
|
||||
const result = await window.daybreakMail.syncFolder(folder, offset, { hasAttachments: true });
|
||||
for (const message of result.messages || []) {
|
||||
for (const file of message.attachments || []) {
|
||||
items.push({
|
||||
uid: message.uid, folder, filename: file.filename, size: file.size,
|
||||
subject: message.subject, sender: message.sender, date: message.date, timestamp: Number(message.timestamp || 0),
|
||||
kind: attachmentKind(file.filename)
|
||||
});
|
||||
}
|
||||
}
|
||||
offset += (result.messages || []).length;
|
||||
if (!result.messages?.length || offset >= (result.total || 0)) break;
|
||||
}
|
||||
}
|
||||
return items.sort((a, b) => b.timestamp - a.timestamp);
|
||||
}
|
||||
|
||||
async function openAttachmentsView() {
|
||||
if (!connectedMailAccount || !window.daybreakMail) { openMailAccount(); return; }
|
||||
const root = $('#modal-root');
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Attachments</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields"><div class="attachment-toolbar"><input id="attachment-search" placeholder="Search file, subject, or sender"><select id="attachment-type" aria-label="File type"><option value="">All types</option><option>Images</option><option>Documents</option><option>Archives</option><option>Other</option></select></div><div id="attachment-list" class="attachment-list">Loading attachments…</div></div></div></div>`;
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
root.querySelector('.modal-close').onclick = close;
|
||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||
const list = $('#attachment-list');
|
||||
const render = () => {
|
||||
const text = $('#attachment-search').value.trim().toLowerCase();
|
||||
const type = $('#attachment-type').value;
|
||||
const shown = attachmentItems.filter(item => (!type || item.kind === type) &&
|
||||
(!text || `${item.filename} ${item.subject} ${item.sender}`.toLowerCase().includes(text)));
|
||||
list.replaceChildren();
|
||||
if (!shown.length) { list.textContent = attachmentItems.length ? 'No attachments match.' : 'No attachments found.'; return; }
|
||||
shown.forEach(item => {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'attachment-row';
|
||||
const info = document.createElement('div');
|
||||
info.className = 'attachment-row-info';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = item.filename;
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = [attachmentSize(item.size), item.sender, item.subject, item.folder, item.date].filter(Boolean).join(' · ');
|
||||
info.append(name, meta);
|
||||
const preview = document.createElement('button');
|
||||
preview.className = 'discard';
|
||||
preview.textContent = 'Preview';
|
||||
const save = document.createElement('button');
|
||||
save.className = 'discard';
|
||||
save.textContent = 'Download';
|
||||
const panel = document.createElement('div');
|
||||
panel.className = 'attachment-preview';
|
||||
panel.hidden = true;
|
||||
const details = { uid: item.uid, folder: item.folder, filename: item.filename };
|
||||
preview.onclick = () => {
|
||||
panel.hidden = !panel.hidden;
|
||||
if (!panel.hidden && !panel.childElementCount && !panel.textContent) void previewAttachment(panel, details);
|
||||
};
|
||||
save.onclick = () => downloadAttachment(details);
|
||||
row.append(info, preview, save, panel);
|
||||
list.append(row);
|
||||
});
|
||||
};
|
||||
$('#attachment-search').oninput = render;
|
||||
$('#attachment-type').onchange = render;
|
||||
try {
|
||||
attachmentItems = await collectAttachments();
|
||||
if ($('#attachment-list')) render();
|
||||
} catch (error) {
|
||||
if ($('#attachment-list')) $('#attachment-list').textContent = error.message || 'Could not load attachments.';
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
$('#attachments-nav')?.addEventListener('click', openAttachmentsView);
|
||||
});
|
||||
+7
-2
@@ -24,6 +24,7 @@
|
||||
<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="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">
|
||||
<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>
|
||||
@@ -32,9 +33,9 @@
|
||||
<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="Trash"><span class="nav-glyph">⌫</span><span>Trash</span></button>
|
||||
<div id="custom-folders"></div>
|
||||
</nav>
|
||||
<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>
|
||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||
<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>
|
||||
<button class="label-link" data-label="Design"><i class="label-dot dot-amber"></i>Design</button>
|
||||
@@ -70,5 +71,9 @@
|
||||
<script src="snooze-ui.js"></script>
|
||||
<script src="account-ui.js"></script>
|
||||
<script src="dav-ui.js"></script>
|
||||
<script src="shortcuts.js"></script>
|
||||
<script src="attachments.js"></script>
|
||||
<script src="pgp-ui.js"></script>
|
||||
<script src="pgp-mail-ui.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+94
-8
@@ -140,9 +140,38 @@ async function loadCustomFolders() {
|
||||
} 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() {
|
||||
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;
|
||||
try {
|
||||
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('')}
|
||||
</select>
|
||||
${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':''}>`}
|
||||
<button type="button" class="discard remove-mail-rule" aria-label="Remove rule">Remove</button>
|
||||
</div>`).join('');
|
||||
@@ -212,8 +241,8 @@ function openMailAccount(existingAccount = null) {
|
||||
const row = event.target.closest('.mail-rule-row');
|
||||
const value = row.querySelector('.mail-rule-value');
|
||||
if (event.target.value === 'move') {
|
||||
const selected = ['Inbox', 'Archive', 'Trash'].includes(value.value) ? 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>`;
|
||||
const selected = value.value || 'Inbox';
|
||||
value.outerHTML = ruleFolderSelect(selected);
|
||||
} else if (value.tagName === 'SELECT') {
|
||||
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) {
|
||||
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 => ({
|
||||
id: draft.id,
|
||||
sender: 'Draft',
|
||||
@@ -302,14 +361,28 @@ function renderDrafts(drafts) {
|
||||
draft
|
||||
})));
|
||||
$('#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-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>';
|
||||
const start = $('#start-draft');
|
||||
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;
|
||||
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);
|
||||
});
|
||||
$('#reader-pane').innerHTML = emptyReader();
|
||||
@@ -584,13 +657,26 @@ if (window.daybreakMail) {
|
||||
sendButton.disabled = true;
|
||||
sendButton.textContent = 'Sending…';
|
||||
try {
|
||||
const pgp = window.pgpPrepareSend ? await window.pgpPrepareSend(recipient, $('#compose-cc').value) : null;
|
||||
if (pgp === false) {
|
||||
sendButton.disabled = false;
|
||||
sendButton.textContent = 'Send ↗';
|
||||
return;
|
||||
}
|
||||
const result = await window.daybreakMail.send({
|
||||
to: recipient,
|
||||
cc: $('#compose-cc').value,
|
||||
subject: $('#compose-subject').value.trim(),
|
||||
text: $('#compose-body').value,
|
||||
displayName: connectedMailAccount.displayName || profileSettings.name
|
||||
displayName: connectedMailAccount.displayName || profileSettings.name,
|
||||
...(pgp ? { pgp } : {})
|
||||
});
|
||||
if (result.failed) {
|
||||
sendButton.disabled = false;
|
||||
sendButton.textContent = 'Send ↗';
|
||||
toast(result.message || 'Message could not be encrypted');
|
||||
return;
|
||||
}
|
||||
if (result.queued) {
|
||||
const draftId = $('#modal-root .compose-modal')?.dataset.draftId;
|
||||
if (draftId) await window.daybreakMail.deleteDraft(draftId);
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
// Reading and sending OpenPGP mail (desktop). Inert where there is no key store.
|
||||
const pgpApi = () => window.daybreakMail?.pgp;
|
||||
|
||||
function pgpAskPassphrase(title, detail) {
|
||||
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"><p class="account-note"></p><label class="compose-line"><span>Passphrase</span><input type="password" id="pgp-prompt-input" autocomplete="current-password"></label></div><div class="compose-footer"><button type="button" class="discard" data-cancel>Cancel</button><button type="submit" class="send-button">Unlock</button></div></form>`;
|
||||
overlay.querySelector('.modal-head span').textContent = title;
|
||||
overlay.querySelector('.account-note').textContent = detail;
|
||||
const finish = value => { overlay.remove(); resolve(value); };
|
||||
overlay.querySelector('form').onsubmit = event => {
|
||||
event.preventDefault();
|
||||
const value = overlay.querySelector('input').value;
|
||||
if (value) finish(value);
|
||||
};
|
||||
overlay.querySelector('[data-cancel]').onclick = () => finish(null);
|
||||
overlay.addEventListener('keydown', event => { if (event.key === 'Escape') { event.stopPropagation(); finish(null); } });
|
||||
document.body.append(overlay);
|
||||
overlay.querySelector('input').focus();
|
||||
});
|
||||
}
|
||||
|
||||
function pgpFormatFingerprint(value) {
|
||||
return String(value || '').match(/.{1,4}/g)?.join(' ') || '';
|
||||
}
|
||||
|
||||
function pgpSignatureHtml(signatures, encrypted) {
|
||||
const items = Array.isArray(signatures) ? signatures : [];
|
||||
const lock = encrypted ? '🔒 Encrypted. ' : '';
|
||||
if (!items.length) {
|
||||
return encrypted ? `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Not signed</strong><span>The sender is not authenticated: anyone with your public key could have written this.</span></section>` : '';
|
||||
}
|
||||
return items.map(signature => {
|
||||
const trust = signature.trust === 'verified' ? 'verified key' : signature.trust === 'trusted' ? 'trusted key' : 'key not verified yet';
|
||||
const notes = [];
|
||||
if (signature.keyChanged) notes.push('The sender previously used a different key. Confirm the change with them before trusting this message.');
|
||||
if (signature.mismatch) notes.push('The signing key does not belong to the sender address.');
|
||||
if (signature.status === 'valid') {
|
||||
const level = signature.keyChanged || signature.mismatch ? 'bad' : signature.trust === 'unknown' ? 'warn' : 'ok';
|
||||
return `<section class="pgp-status pgp-${level}" role="status"><strong>${lock}Valid signature from ${esc(signature.email || 'a known key')}</strong><span>${esc(trust)} · ${esc(pgpFormatFingerprint(signature.fingerprint))}</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
|
||||
}
|
||||
if (signature.status === 'unknown-key') {
|
||||
return `<section class="pgp-status pgp-warn" role="status"><strong>${lock}Signed with an unknown key</strong><span>Key ID ${esc(signature.keyId)} is not in your contacts, so the signature cannot be checked.</span>${notes.map(note => `<small>${esc(note)}</small>`).join('')}</section>`;
|
||||
}
|
||||
return `<section class="pgp-status pgp-bad" role="alert"><strong>${lock}Invalid signature</strong><span>This message may have been altered or forged. Do not trust it.</span></section>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
async function pgpAddAttachedKey(key) {
|
||||
const emails = key.emails.join(', ') || 'unknown address';
|
||||
if (!confirm(`Add this public key for ${emails}?\nFingerprint: ${pgpFormatFingerprint(key.fingerprint)}\n\nCompare the fingerprint with the owner before relying on it.`)) return;
|
||||
try {
|
||||
const result = await pgpApi().addContact({ armoredKey: key.armoredKey, source: 'message' });
|
||||
toast(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address.' : 'Public key added to your contacts');
|
||||
} catch (error) {
|
||||
toast(error.message || 'Could not add the key');
|
||||
}
|
||||
}
|
||||
|
||||
function pgpRenderReaderState(message) {
|
||||
const reader = $('#reader-pane');
|
||||
const header = reader.querySelector('.reader-header');
|
||||
if (!header) return;
|
||||
reader.querySelectorAll('.pgp-status, .pgp-banner').forEach(node => node.remove());
|
||||
let html = '';
|
||||
if (message.encrypted && !message.pgpDecrypted) {
|
||||
html = `<section class="pgp-banner" role="status"><strong>🔒 This message is encrypted</strong><span id="pgp-banner-text">Unlock it with your key passphrase to read it.</span><button type="button" class="send-button" id="pgp-unlock">Unlock</button></section>`;
|
||||
} else if (message.encrypted) {
|
||||
html = pgpSignatureHtml(message.pgpResult?.signatures, true);
|
||||
} else if (message.pgpSignatures) {
|
||||
html = pgpSignatureHtml(message.pgpSignatures, false);
|
||||
}
|
||||
const keys = message.pgpResult?.attachedKeys || [];
|
||||
header.insertAdjacentHTML('afterend', html + keys.map((key, index) => `<section class="pgp-status pgp-warn"><strong>Public key attached</strong><span>${esc(key.emails.join(', ') || 'unknown address')} · ${esc(pgpFormatFingerprint(key.fingerprint))}</span><button type="button" class="discard" data-pgp-key="${index}">Add to contacts…</button></section>`).join(''));
|
||||
reader.querySelectorAll('[data-pgp-key]').forEach(button => {
|
||||
button.onclick = () => pgpAddAttachedKey(keys[Number(button.dataset.pgpKey)]);
|
||||
});
|
||||
const unlock = $('#pgp-unlock');
|
||||
if (unlock) unlock.onclick = () => pgpUnlockMessage(message, true);
|
||||
}
|
||||
|
||||
async function pgpUnlockMessage(message, interactive) {
|
||||
let passphrase = null;
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
let result;
|
||||
try {
|
||||
result = await pgpApi().decryptMessage({ folder: message.sourceFolder || 'Inbox', uid: message.uid, passphrase });
|
||||
} catch (error) {
|
||||
toast(error.message || 'Could not open this message');
|
||||
return;
|
||||
}
|
||||
if (result.ok) {
|
||||
Object.assign(message, {
|
||||
body: result.body, links: result.links, attachments: result.attachments, attachment: result.attachment, size: result.size,
|
||||
snippet: 'Encrypted message', pgpDecrypted: true, pgpResult: { signatures: result.signatures, attachedKeys: result.attachedKeys }
|
||||
});
|
||||
if (activeMessage === message.id) openMessage(message.id);
|
||||
return;
|
||||
}
|
||||
if (result.code === 'PASSPHRASE_REQUIRED' || result.code === 'BAD_PASSPHRASE') {
|
||||
if (!interactive) { pgpRenderReaderState(message); return; }
|
||||
passphrase = await pgpAskPassphrase('Unlock encrypted message', result.code === 'BAD_PASSPHRASE' ? 'That passphrase was incorrect. Try again.' : `Enter the passphrase for ${result.email || 'your key'}.`);
|
||||
if (passphrase === null) return;
|
||||
continue;
|
||||
}
|
||||
const text = $('#pgp-banner-text');
|
||||
if (text) text.textContent = result.message;
|
||||
else toast(result.message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof openMessage === 'function') {
|
||||
const baseOpenMessage = openMessage;
|
||||
openMessage = function (id) {
|
||||
baseOpenMessage(id);
|
||||
const message = messages.find(item => item.id === id);
|
||||
if (!message || !pgpApi()) return;
|
||||
pgpRenderReaderState(message);
|
||||
if (message.encrypted && !message.pgpDecrypted && !message.pgpAutoTried) {
|
||||
message.pgpAutoTried = true;
|
||||
void pgpUnlockMessage(message, false);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Compose: encrypt/sign options.
|
||||
if (typeof showCompose === 'function') {
|
||||
const baseShowCompose = showCompose;
|
||||
showCompose = function (reply, forward = false) {
|
||||
baseShowCompose(reply, forward);
|
||||
const footer = $('#modal-root .compose-footer');
|
||||
if (!footer || !pgpApi()) return;
|
||||
const box = document.createElement('div');
|
||||
box.className = 'pgp-compose';
|
||||
box.innerHTML = `<label><input type="checkbox" id="pgp-encrypt"> Encrypt</label><label><input type="checkbox" id="pgp-sign"> Sign</label><small id="pgp-hint"></small>`;
|
||||
footer.prepend(box);
|
||||
let touched = false;
|
||||
const encrypt = $('#pgp-encrypt');
|
||||
const sign = $('#pgp-sign');
|
||||
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
||||
if (touched) encrypt.dataset.touched = '1';
|
||||
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
||||
let timer = null;
|
||||
const refresh = async () => {
|
||||
const to = $('#compose-to')?.value || '';
|
||||
const cc = $('#compose-cc')?.value || '';
|
||||
const hint = $('#pgp-hint');
|
||||
if (!hint) return;
|
||||
if (!to.trim()) { hint.textContent = ''; return; }
|
||||
try {
|
||||
const status = await pgpApi().checkSend({ to, cc, sign: sign.checked });
|
||||
if (!$('#pgp-hint')) return;
|
||||
if (status.missing.length) hint.textContent = `No public key for ${status.missing.join(', ')}`;
|
||||
else {
|
||||
hint.textContent = status.recipients.some(item => item.trust === 'unknown') ? 'Keys found; some are not verified yet' : 'Keys found for all recipients';
|
||||
if (!touched && !encrypt.checked) encrypt.checked = true;
|
||||
}
|
||||
} catch { hint.textContent = ''; }
|
||||
};
|
||||
const schedule = () => { clearTimeout(timer); timer = setTimeout(refresh, 300); };
|
||||
['#compose-to', '#compose-cc'].forEach(selector => $(selector)?.addEventListener('input', schedule));
|
||||
sign.addEventListener('change', schedule);
|
||||
schedule();
|
||||
};
|
||||
}
|
||||
|
||||
// Called by the send handler. Returns null (plain mail), false (cancelled) or send options.
|
||||
window.pgpPrepareSend = async function pgpPrepareSend(to, cc) {
|
||||
if (!pgpApi()) return null;
|
||||
let encrypt = Boolean($('#pgp-encrypt')?.checked);
|
||||
const sign = Boolean($('#pgp-sign')?.checked);
|
||||
if (!encrypt && !sign && $('#pgp-encrypt')?.dataset.touched === '1') return null;
|
||||
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) {
|
||||
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;
|
||||
encrypt = false;
|
||||
if (!sign) return null;
|
||||
}
|
||||
let passphrase = null;
|
||||
if (sign) {
|
||||
if (!status.signer) { toast('Create or import an encryption key for your address before signing'); return false; }
|
||||
if (!status.signer.unlocked) {
|
||||
passphrase = await pgpAskPassphrase('Sign message', `Enter the passphrase for ${status.signer.email} to sign this message.`);
|
||||
if (passphrase === null) return false;
|
||||
}
|
||||
}
|
||||
return { encrypt, sign, passphrase };
|
||||
};
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
// Encryption key management (desktop). Hidden where the platform has no key store yet.
|
||||
function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); }
|
||||
|
||||
function openEncryptionKeys() {
|
||||
const root = $('#modal-root');
|
||||
const account = connectedMailAccount || {};
|
||||
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
|
||||
<p class="account-note">OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered. Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
|
||||
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
|
||||
<h3 class="pgp-heading">Contact public keys</h3>
|
||||
<div id="pgp-contact-list" class="attachment-list">Loading contacts…</div>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-add-contact">Import public key…</button></div>
|
||||
<h3 class="pgp-heading">Passphrase memory</h3>
|
||||
<label class="compose-line"><span>Minutes</span><input id="pgp-cache-minutes" type="number" min="0" max="1440" step="1"></label>
|
||||
<div class="pgp-actions"><button class="discard" id="pgp-save-cache">Save</button><button class="discard" id="pgp-forget">Forget passphrases now</button></div>
|
||||
<p class="account-note">Unlocked passphrases are kept in memory only, for this many minutes (0 asks every time). Opening encrypted attachments needs the passphrase to be remembered.</p>
|
||||
<h3 class="pgp-heading">Create a key</h3>
|
||||
<label class="compose-line"><span>Name</span><input id="pgp-name" maxlength="100" value="${esc(account.displayName || '')}"></label>
|
||||
<label class="compose-line"><span>Email</span><input id="pgp-email" type="email" value="${esc(account.email || '')}"></label>
|
||||
<label class="compose-line"><span>Passphrase</span><input id="pgp-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
|
||||
<div class="pgp-actions"><button class="send-button" id="pgp-generate">Create key</button><button class="discard" id="pgp-import">Import private key…</button></div>
|
||||
<p class="account-note" id="pgp-status" role="status"></p>
|
||||
</div></div></div>`;
|
||||
const close = () => { root.innerHTML = ''; };
|
||||
root.querySelector('.modal-close').onclick = close;
|
||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||
const status = message => { $('#pgp-status').textContent = message; };
|
||||
const passphraseField = () => $('#pgp-passphrase');
|
||||
const needPassphrase = () => {
|
||||
const value = passphraseField().value;
|
||||
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
||||
return value;
|
||||
};
|
||||
|
||||
async function render() {
|
||||
const list = $('#pgp-key-list');
|
||||
let keys = [];
|
||||
try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; }
|
||||
list.replaceChildren();
|
||||
if (!keys.length) { list.textContent = 'No keys yet.'; return; }
|
||||
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.email || 'OpenPGP key';
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`;
|
||||
const fingerprint = document.createElement('small');
|
||||
fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||
info.append(title, meta, fingerprint);
|
||||
row.append(info);
|
||||
const actions = [
|
||||
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
|
||||
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
|
||||
];
|
||||
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
|
||||
actions.push(['Delete', async () => {
|
||||
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
|
||||
await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase());
|
||||
await render();
|
||||
return { deleted: true };
|
||||
}, true]);
|
||||
actions.forEach(([label, run, secret]) => {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'discard';
|
||||
button.textContent = label;
|
||||
button.onclick = async () => {
|
||||
if (secret && !passphraseField().value) { needPassphrase(); return; }
|
||||
try {
|
||||
const result = await run();
|
||||
status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : '');
|
||||
} catch (error) { status(error.message || 'That action failed.'); }
|
||||
};
|
||||
row.append(button);
|
||||
});
|
||||
list.append(row);
|
||||
});
|
||||
}
|
||||
|
||||
$('#pgp-generate').onclick = async () => {
|
||||
const button = $('#pgp-generate');
|
||||
button.disabled = true;
|
||||
status('Creating key…');
|
||||
try {
|
||||
await window.daybreakMail.pgp.generate({
|
||||
name: $('#pgp-name').value, email: $('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null
|
||||
});
|
||||
status('Key created. Export your private key and revocation certificate now and keep them safe.');
|
||||
await render();
|
||||
} catch (error) { status(error.message || 'Could not create the key.'); }
|
||||
button.disabled = false;
|
||||
};
|
||||
$('#pgp-import').onclick = async () => {
|
||||
const passphrase = needPassphrase();
|
||||
if (!passphrase) return;
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null });
|
||||
status(result.canceled ? '' : 'Key imported.');
|
||||
await render();
|
||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||
};
|
||||
async function renderContacts() {
|
||||
const list = $('#pgp-contact-list');
|
||||
let contacts = [];
|
||||
try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; }
|
||||
list.replaceChildren();
|
||||
if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; }
|
||||
contacts.forEach(contact => {
|
||||
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 = contact.emails.join(', ') || contact.name || 'Public key';
|
||||
const meta = document.createElement('small');
|
||||
meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`;
|
||||
const fingerprint = document.createElement('small');
|
||||
fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`;
|
||||
info.append(title, meta, fingerprint);
|
||||
const trust = document.createElement('select');
|
||||
trust.className = 'pgp-trust';
|
||||
trust.setAttribute('aria-label', 'Key trust');
|
||||
[['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => {
|
||||
const option = document.createElement('option');
|
||||
option.value = value; option.textContent = label; option.selected = contact.trust === value;
|
||||
trust.append(option);
|
||||
});
|
||||
trust.onchange = async () => {
|
||||
if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) {
|
||||
trust.value = contact.trust;
|
||||
return;
|
||||
}
|
||||
try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); }
|
||||
catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); }
|
||||
};
|
||||
const actions = [
|
||||
['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)],
|
||||
['Remove', async () => {
|
||||
if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true };
|
||||
await window.daybreakMail.pgp.removeContact(contact.fingerprint);
|
||||
await renderContacts();
|
||||
return { deleted: true };
|
||||
}]
|
||||
];
|
||||
row.append(info, trust);
|
||||
actions.forEach(([label, run]) => {
|
||||
const button = document.createElement('button');
|
||||
button.className = 'discard';
|
||||
button.textContent = label;
|
||||
button.onclick = async () => {
|
||||
try { const result = await run(); status(result?.saved ? 'File saved.' : result?.deleted ? 'Contact key removed.' : ''); }
|
||||
catch (error) { status(error.message || 'That action failed.'); }
|
||||
};
|
||||
row.append(button);
|
||||
});
|
||||
list.append(row);
|
||||
});
|
||||
}
|
||||
|
||||
$('#pgp-add-contact').onclick = async () => {
|
||||
try {
|
||||
const result = await window.daybreakMail.pgp.addContact({});
|
||||
if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.');
|
||||
await renderContacts();
|
||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||
};
|
||||
window.daybreakMail.pgp.getSettings().then(settings => { $('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {});
|
||||
$('#pgp-save-cache').onclick = async () => {
|
||||
try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number($('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); }
|
||||
catch (error) { status(error.message || 'Could not save the setting.'); }
|
||||
};
|
||||
$('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); };
|
||||
void renderContacts();
|
||||
void render();
|
||||
}
|
||||
|
||||
if (typeof openPreferences === 'function') {
|
||||
const baseOpenPreferences = openPreferences;
|
||||
openPreferences = function () {
|
||||
baseOpenPreferences();
|
||||
const fields = $('#modal-root .compose-fields');
|
||||
if (!fields || !pgpAvailable()) return;
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.className = 'discard';
|
||||
button.id = 'open-encryption-keys';
|
||||
button.textContent = 'Encryption keys…';
|
||||
button.onclick = openEncryptionKeys;
|
||||
fields.append(button);
|
||||
};
|
||||
}
|
||||
@@ -530,6 +530,7 @@
|
||||
updateMessage: (details) => EpMail.updateMessage(details),
|
||||
setSnooze: (details) => EpMail.setSnooze(details),
|
||||
checkSnoozeReminders: () => EpMail.checkSnoozeReminders(),
|
||||
previewAttachment: (details) => EpMail.previewAttachment(details),
|
||||
saveAttachment: (details) => EpMail.saveAttachment(details),
|
||||
openExternal: (url) => EpMail.openExternal({ url }),
|
||||
send: (message) => EpMail.send(message),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
const CACHE='ep-mail-v3';
|
||||
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','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
const CACHE='ep-mail-v7';
|
||||
const FILES=['./','./index.html','./styles.css','./branding.css','./app.js','./platform-bridge.js','./mail-ui.js','./productivity.js','./snooze-ui.js','./account-ui.js','./dav-ui.js','./shortcuts.js','./attachments.js','./pgp-ui.js','./pgp-mail-ui.js','./manifest.webmanifest','./icon.svg','./logo-ep-daylight.svg','./logo-ep-wasteland.svg'];
|
||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(FILES))));
|
||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(k=>k!==CACHE).map(k=>caches.delete(k))))));
|
||||
self.addEventListener('fetch',event=>{if(event.request.method!=='GET')return;event.respondWith(caches.match(event.request).then(cached=>cached||fetch(event.request).then(response=>{if(new URL(event.request.url).origin===location.origin){const copy=response.clone();caches.open(CACHE).then(cache=>cache.put(event.request,copy))}return response}).catch(()=>caches.match('./index.html'))))});
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// Configurable keyboard shortcuts for common mail actions.
|
||||
const shortcutStorageKey = 'daybreak-shortcuts';
|
||||
const shortcutActions = [
|
||||
{ id: 'compose', label: 'Compose', fallback: 'c', run: () => $('#compose')?.click() },
|
||||
{ id: 'search', label: 'Search', fallback: '/', run: () => $('#search')?.focus() },
|
||||
{ id: 'refresh', label: 'Refresh', fallback: 'r', run: () => $('#refresh')?.click() },
|
||||
{ id: 'archive', label: 'Archive message', fallback: 'e', run: () => $('#reader-archive')?.click() },
|
||||
{ id: 'delete', label: 'Delete message', fallback: '#', run: () => $('#reader-delete')?.click() },
|
||||
{ id: 'star', label: 'Star message', fallback: 's', run: () => $('#reader-star')?.click() },
|
||||
{ id: 'reply', label: 'Reply', fallback: 'a', run: () => $('#reply')?.click() },
|
||||
{ id: 'forward', label: 'Forward', fallback: 'f', run: () => $('#forward')?.click() },
|
||||
{ id: 'next', label: 'Next message', fallback: 'j', run: () => moveMessageSelection(1) },
|
||||
{ id: 'previous', label: 'Previous message', fallback: 'k', run: () => moveMessageSelection(-1) }
|
||||
];
|
||||
|
||||
function normalizeShortcut(value) {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return '';
|
||||
const parts = text.split('+').map(part => part.trim()).filter(Boolean);
|
||||
const key = parts.pop() || '+';
|
||||
const mods = ['Ctrl', 'Alt', 'Shift'].filter(mod => parts.some(part => part.toLowerCase() === mod.toLowerCase()));
|
||||
return [...mods, key.length === 1 ? key.toLowerCase() : key].join('+');
|
||||
}
|
||||
|
||||
function loadShortcuts() {
|
||||
let saved = {};
|
||||
try { saved = JSON.parse(localStorage.getItem(shortcutStorageKey)) || {}; } catch {}
|
||||
return Object.fromEntries(shortcutActions.map(action => [
|
||||
action.id, typeof saved[action.id] === 'string' ? normalizeShortcut(saved[action.id]) : action.fallback
|
||||
]));
|
||||
}
|
||||
|
||||
function eventShortcut(event) {
|
||||
if (['Control', 'Alt', 'Shift', 'Meta'].includes(event.key)) return '';
|
||||
const mods = [event.ctrlKey || event.metaKey ? 'Ctrl' : '', event.altKey ? 'Alt' : ''];
|
||||
const printable = event.key.length === 1;
|
||||
if (event.shiftKey && !printable) mods.push('Shift');
|
||||
return normalizeShortcut([...mods.filter(Boolean), event.key === ' ' ? 'Space' : event.key].join('+'));
|
||||
}
|
||||
|
||||
function moveMessageSelection(step) {
|
||||
if (!messages.length) return;
|
||||
const index = messages.findIndex(message => message.id === activeMessage);
|
||||
const next = messages[Math.min(messages.length - 1, Math.max(0, index + step))];
|
||||
if (next) { openMessage(next.id); $(`.message[data-id="${next.id}"]`)?.scrollIntoView({ block: 'nearest' }); }
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', event => {
|
||||
if (event.defaultPrevented || event.isComposing || event.key === 'Escape') return;
|
||||
const target = event.target;
|
||||
if (target?.closest?.('input, textarea, select, [contenteditable="true"]') || $('#modal-root')?.children.length) return;
|
||||
const pressed = eventShortcut(event);
|
||||
if (!pressed) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
const action = shortcutActions.find(item => shortcuts[item.id] && shortcuts[item.id] === pressed);
|
||||
if (!action) return;
|
||||
event.preventDefault();
|
||||
action.run();
|
||||
});
|
||||
|
||||
if (typeof openPreferences === 'function') {
|
||||
const baseOpenPreferences = openPreferences;
|
||||
openPreferences = function () {
|
||||
baseOpenPreferences();
|
||||
const fields = $('#modal-root .compose-fields');
|
||||
const save = $('#save-appearance');
|
||||
if (!fields || !save) return;
|
||||
const shortcuts = loadShortcuts();
|
||||
const section = document.createElement('div');
|
||||
section.className = 'shortcut-settings';
|
||||
section.innerHTML = `<h3>Keyboard shortcuts</h3><p class="account-note">Type a key or combination such as <code>c</code>, <code>Ctrl+Enter</code> or <code>Alt+n</code>. Leave blank to disable. Shortcuts are inactive while typing or in dialogs.</p>${shortcutActions.map(action =>
|
||||
`<label class="compose-line"><span>${action.label}</span><input class="shortcut-input" data-action="${action.id}" maxlength="24" value="${esc(shortcuts[action.id])}" placeholder="None"></label>`).join('')}<button type="button" class="discard" id="reset-shortcuts">Reset to defaults</button>`;
|
||||
fields.append(section);
|
||||
section.addEventListener('keydown', event => {
|
||||
const input = event.target.closest('.shortcut-input');
|
||||
if (!input || ['Tab', 'Escape'].includes(event.key)) return;
|
||||
event.preventDefault();
|
||||
if (['Backspace', 'Delete'].includes(event.key)) { input.value = ''; return; }
|
||||
const combo = eventShortcut(event);
|
||||
if (combo) input.value = combo;
|
||||
});
|
||||
$('#reset-shortcuts').onclick = () => {
|
||||
section.querySelectorAll('.shortcut-input').forEach(input => {
|
||||
input.value = shortcutActions.find(action => action.id === input.dataset.action).fallback;
|
||||
});
|
||||
};
|
||||
const baseSave = save.onclick;
|
||||
save.onclick = event => {
|
||||
const values = {};
|
||||
const used = new Map();
|
||||
for (const input of section.querySelectorAll('.shortcut-input')) {
|
||||
const value = normalizeShortcut(input.value);
|
||||
const label = shortcutActions.find(action => action.id === input.dataset.action).label;
|
||||
if (value && used.has(value)) { toast(`“${value}” is used by both ${used.get(value)} and ${label}`); return; }
|
||||
if (value) used.set(value, label);
|
||||
values[input.dataset.action] = value;
|
||||
}
|
||||
localStorage.setItem(shortcutStorageKey, JSON.stringify(values));
|
||||
baseSave?.call(save, event);
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -126,3 +126,17 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||
body.ep-daylight .mail-safety-warning{background:#fff6df;color:#5b3c17}body.ep-daylight .mail-link-risky{background:#fff8ea;border-color:#d69b43}
|
||||
|
||||
.folder-add{border:0;background:transparent;color:#929990;font-size:18px;cursor:pointer}.folder-add:hover{color:#487354}.section-label+.folder-nav:empty{display:none}.custom-folder span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.shortcut-settings h3{margin:16px 0 4px;font-size:13px}.shortcut-settings code{font-family:monospace}.shortcut-input{text-transform:none}.shortcut-settings #reset-shortcuts{margin-top:8px}
|
||||
.attachments-modal{width:min(720px,94vw)}.attachment-toolbar{display:flex;gap:8px;margin-bottom:10px}.attachment-toolbar input{flex:1}.attachment-list{max-height:60vh;overflow:auto;display:grid;gap:8px}.attachment-row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px;border:1px solid var(--line);border-radius:8px}.attachment-row-info{flex:1;min-width:0;display:flex;flex-direction:column;gap:2px}.attachment-row-info strong,.attachment-row-info small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.attachment-preview{flex-basis:100%;max-height:320px;overflow:auto;padding:8px;font-size:12px}.attachment-preview-image{max-width:100%;max-height:300px;display:block}.attachment-preview-text{margin:0;white-space:pre-wrap;word-break:break-word}.preview-attachment{font-size:14px}
|
||||
.pgp-heading{margin:16px 0 4px;font-size:13px}.pgp-actions{display:flex;gap:8px;margin-top:8px}#open-encryption-keys{margin-top:12px}
|
||||
|
||||
.pgp-prompt{z-index:2000}.pgp-prompt-box{max-width:420px}
|
||||
.pgp-status,.pgp-banner{display:flex;flex-direction:column;gap:2px;margin:10px 0;padding:10px 12px;border-radius:8px;border:1px solid var(--line,#c9d1c8);font-size:13px}
|
||||
.pgp-status small{opacity:.85}.pgp-ok{border-color:#3d7a4f;background:rgba(61,122,79,.12)}.pgp-warn{border-color:#b8860b;background:rgba(184,134,11,.14)}.pgp-bad{border-color:#b3261e;background:rgba(179,38,30,.14)}
|
||||
.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-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)}
|
||||
|
||||
.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}
|
||||
|
||||
Reference in New Issue
Block a user