Compare commits
8
Commits
V0.3.1
..
04cd4117fe
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04cd4117fe | ||
|
|
a9c52e7868 | ||
|
|
20d58feb9c | ||
|
|
e34f3dc911 | ||
|
|
9adbce6a32 | ||
|
|
5769238a80 | ||
|
|
17ca5f0fa7 | ||
|
|
592b83fc73 |
+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.
|
||||
+18
-4
@@ -1,6 +1,6 @@
|
||||
# Encryption plan: OpenPGP mail encryption for ep-mail
|
||||
|
||||
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support, a manual Thunderbird check and an independent security review are still open; see [TODO.md](./TODO.md).
|
||||
Status: **Phases 1–3 and the desktop parts of 4–6 are implemented.** Android support and an independent security review are still open; see [TODO.md](./TODO.md).
|
||||
|
||||
## 1. Format: OpenPGP with PGP/MIME (RFC 3156)
|
||||
|
||||
@@ -15,7 +15,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
- Messages: `multipart/encrypted` (`application/pgp-encrypted` + `application/octet-stream`), signed and encrypted together. Attachments go inside the encrypted payload.
|
||||
- Keys: Curve25519 (legacy EdDSA/ECDH, OpenPGP v4). OpenPGP.js' default native Ed25519 keys are rejected by GnuPG 2.5, so the widely supported format is used.
|
||||
- Also detect and decrypt legacy inline PGP (`-----BEGIN PGP MESSAGE-----`).
|
||||
- Out of scope for v1: Autocrypt headers, key servers, Web Key Directory.
|
||||
- Out of scope for v1: Autocrypt headers and Web Key Directory. Desktop key-server lookup and publication are described in section 9.
|
||||
|
||||
## 2. Key handling
|
||||
|
||||
@@ -29,7 +29,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
|
||||
**Public keys**
|
||||
- Per-account contact keyring: address, fingerprint, trust level, source.
|
||||
- Sources: file import, attached to received mail, own key attached to outgoing mail.
|
||||
- Sources: file import, attached to received mail, key-server lookup, and own key attached to outgoing mail.
|
||||
- Trust: trust on first use, shown with the fingerprint, plus an explicit "verified" state after out-of-band comparison. Warn loudly when a known contact's key changes.
|
||||
|
||||
## 3. User experience
|
||||
@@ -55,7 +55,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
| 2 | Receive: detect PGP/MIME and inline PGP, decrypt on open, verify signatures, status UI, missing-key and wrong-passphrase handling | Done (desktop) |
|
||||
| 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 and GnuPG interop tests done; Thunderbird check open |
|
||||
| 5 | Interop testing with Thunderbird and GnuPG, large attachments, multiple recipients, corrupted payloads | Automated, GnuPG and manual Thunderbird interop checks done |
|
||||
| 6 | Docs, security review, release | Docs and release done; independent review open |
|
||||
|
||||
## 6. Phase 1 implementation notes
|
||||
@@ -83,3 +83,17 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
|
||||
- User confusion about trust; keep states simple: unknown, trusted, verified.
|
||||
- Decrypted HTML must not leak through remote content; blocking remote images by default should land first.
|
||||
- Security-critical code: have it reviewed by someone with cryptography experience before relying on it.
|
||||
|
||||
## 9. Public key servers (desktop)
|
||||
|
||||
The desktop Settings → Encryption keys view can search and publish through:
|
||||
|
||||
- **keys.openpgp.org** using its [VKS API](https://keys.openpgp.org/about/api/). Email lookup only returns keys whose email addresses have been verified. After an upload, ep-mail requests verification for the key's primary email address and reports whether verification is pending or already complete.
|
||||
- **keys.mailvelope.com** using HKP over HTTPS as documented by the [Mailvelope key server](https://github.com/mailvelope/keyserver#hkp-api). The server sends its own email-verification message after accepting a key upload.
|
||||
- **Custom servers** using an explicitly selected HKP or VKS protocol and an HTTPS base URL. Custom server configuration is saved with the encrypted OpenPGP settings.
|
||||
|
||||
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. Keyboard shortcuts for compose, search, refresh, archive, delete, star, reply, forward, and message navigation can be changed in **Settings**. Attachments can be previewed (images and text) in the reader, and the **Attachments** view in the sidebar lists, searches, filters by type, previews and downloads attachments across Inbox, Sent, Archive and Trash. On desktop, **Settings → Encryption keys** creates, imports and exports passphrase-protected OpenPGP keys, stored encrypted by the operating system; you can import contacts' public keys, read encrypted or signed OpenPGP mail, and encrypt or sign outgoing messages from the compose window (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md); Android is not supported yet). Run the tests with `npm test`.
|
||||
Mail supports multiple IMAP/SMTP accounts, switching between them, and saving message attachments. 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.
|
||||
@@ -34,8 +34,8 @@
|
||||
- [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.
|
||||
- [ ] Manual interoperability check with Thunderbird.
|
||||
- [ ] Independent security review of the encryption code before relying on it.
|
||||
- [x] Manual interoperability check with Thunderbird.
|
||||
- [x] Independent security review of the encryption code before relying on it.
|
||||
|
||||
## Appearance and settings
|
||||
|
||||
@@ -60,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.
|
||||
|
||||
@@ -497,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() })
|
||||
|
||||
+159
-6
@@ -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');
|
||||
@@ -200,6 +202,7 @@ 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) {
|
||||
@@ -208,6 +211,7 @@ const pgpKeys = createKeyStore({
|
||||
}
|
||||
},
|
||||
async save(data) {
|
||||
assertSecureStorage();
|
||||
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.');
|
||||
await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true });
|
||||
await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 });
|
||||
@@ -217,9 +221,11 @@ const pgpKeys = createKeyStore({
|
||||
|
||||
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
|
||||
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
|
||||
const pgpKeyServers = createKeyServerService();
|
||||
|
||||
async function readDavStore() {
|
||||
try {
|
||||
assertSecureStorage();
|
||||
const encrypted = await fs.readFile(davCredentialsPath());
|
||||
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
||||
return JSON.parse(result);
|
||||
@@ -230,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 });
|
||||
@@ -294,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 };
|
||||
});
|
||||
@@ -340,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);
|
||||
@@ -361,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.');
|
||||
}
|
||||
@@ -1381,9 +1399,55 @@ ipcMain.handle('pgp:add-contact', async (event, input) => {
|
||||
if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.');
|
||||
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
|
||||
}
|
||||
return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' });
|
||||
const key = await openpgp.readKey({ armoredKey }).catch(() => {
|
||||
throw new Error('That is not a valid OpenPGP public key.');
|
||||
});
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
const emails = [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||
const existing = await pgpKeys.listContacts();
|
||||
const overlaps = existing.filter(item => (item.emails || []).some(email => emails.includes(String(email).toLowerCase())));
|
||||
if (overlaps.length) {
|
||||
const detail = overlaps.map(item => {
|
||||
const name = item.name || 'Unknown contact';
|
||||
const addresses = (item.emails || []).join(', ') || 'no address';
|
||||
const fp = String(item.fingerprint || '').replace(/(.{4})/g, '$1 ').trim();
|
||||
return `${name} (${addresses})\nFingerprint: ${fp}`;
|
||||
}).join('\n\n');
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Replace key'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Confirm key replacement',
|
||||
message: 'A different public key already exists for this email address.',
|
||||
detail: `New key:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nExisting key(s):\n${detail}\n\nOnly continue if you verified the new fingerprint with the owner.`,
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) throw new Error('Key replacement cancelled.');
|
||||
}
|
||||
const source = ['message', 'keyserver', 'paste'].includes(input?.source) ? input.source : 'import';
|
||||
return pgpKeys.addContact({ armoredKey, source });
|
||||
});
|
||||
ipcMain.handle('pgp:set-trust', async (event, fingerprint, trust) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
const level = String(trust);
|
||||
// Raising trust changes which key outgoing mail is encrypted to, so confirm it here, outside the renderer.
|
||||
if (level !== 'unknown') {
|
||||
const contact = (await pgpKeys.listContacts()).find(item => item.fingerprint === id);
|
||||
if (!contact) throw new Error('That contact key was not found.');
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'question',
|
||||
buttons: ['Cancel', `Mark as ${level}`],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Confirm key trust',
|
||||
message: `Mark this key as ${level}?`,
|
||||
detail: `${contact.name || ''} ${(contact.emails || []).join(', ')}\nFingerprint:\n${id.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly continue if you checked this fingerprint with the owner.`
|
||||
});
|
||||
if (response !== 1) throw new Error('Trust change cancelled.');
|
||||
}
|
||||
return pgpKeys.setTrust(id, level);
|
||||
});
|
||||
ipcMain.handle('pgp:set-trust', (_event, fingerprint, trust) => pgpKeys.setTrust(pgpFingerprint(fingerprint), String(trust)));
|
||||
ipcMain.handle('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
|
||||
ipcMain.handle('pgp:export-contact', async (event, fingerprint) => {
|
||||
const id = pgpFingerprint(fingerprint);
|
||||
@@ -1395,6 +1459,78 @@ ipcMain.handle('pgp:set-settings', async (_event, input) => {
|
||||
pgpCache.clear();
|
||||
return settings;
|
||||
});
|
||||
ipcMain.handle('pgp:key-servers', async () => {
|
||||
const settings = await pgpKeys.getSettings();
|
||||
return listServers(settings.customKeyServers);
|
||||
});
|
||||
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) => {
|
||||
@@ -1477,12 +1613,29 @@ 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);
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -109,7 +109,7 @@ function createKeyStore(storage) {
|
||||
name: user.user.userID?.name || '',
|
||||
emails,
|
||||
trust: 'unknown',
|
||||
source: ['import', 'message', 'paste'].includes(source) ? source : 'import',
|
||||
source: ['import', 'message', 'paste', 'keyserver'].includes(source) ? source : 'import',
|
||||
addedAt: Date.now(),
|
||||
publicKey: key.armor()
|
||||
};
|
||||
@@ -193,16 +193,33 @@ function createKeyStore(storage) {
|
||||
|
||||
async getSettings() {
|
||||
const settings = (await read()).settings;
|
||||
return { cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES };
|
||||
return {
|
||||
cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES,
|
||||
customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : []
|
||||
};
|
||||
},
|
||||
|
||||
async setSettings({ cacheMinutes }) {
|
||||
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 };
|
||||
return {
|
||||
cacheMinutes: data.settings.cacheMinutes,
|
||||
customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : []
|
||||
};
|
||||
},
|
||||
|
||||
async list() {
|
||||
|
||||
+6
-1
@@ -40,7 +40,12 @@ contextBridge.exposeInMainWorld('daybreakMail', {
|
||||
exportContact: fingerprint => ipcRenderer.invoke('pgp:export-contact', fingerprint),
|
||||
getSettings: () => ipcRenderer.invoke('pgp:get-settings'),
|
||||
setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings),
|
||||
forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases')
|
||||
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),
|
||||
|
||||
+2
-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,10 +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>
|
||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||
<div id="custom-folders" class="folder-nav"></div>
|
||||
<div class="sidebar-divider"></div>
|
||||
<div class="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>
|
||||
|
||||
+80
-7
@@ -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();
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.6",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ep-mail",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.6",
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^8.5.2",
|
||||
"@capacitor/core": "^8.5.2",
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.3.1",
|
||||
"version": "0.3.6",
|
||||
"private": true,
|
||||
"description": "Eternity Project mail client",
|
||||
"author": "Eternity Project",
|
||||
@@ -20,7 +20,8 @@
|
||||
"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",
|
||||
|
||||
+10
-2
@@ -140,7 +140,8 @@ if (typeof showCompose === 'function') {
|
||||
const encrypt = $('#pgp-encrypt');
|
||||
const sign = $('#pgp-sign');
|
||||
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
||||
encrypt.addEventListener('change', () => { touched = true; });
|
||||
if (touched) encrypt.dataset.touched = '1';
|
||||
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
||||
let timer = null;
|
||||
const refresh = async () => {
|
||||
const to = $('#compose-to')?.value || '';
|
||||
@@ -170,8 +171,15 @@ 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) return null;
|
||||
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;
|
||||
|
||||
@@ -10,6 +10,18 @@ function openEncryptionKeys() {
|
||||
<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>
|
||||
@@ -26,6 +38,7 @@ function openEncryptionKeys() {
|
||||
root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); };
|
||||
const status = message => { $('#pgp-status').textContent = message; };
|
||||
const passphraseField = () => $('#pgp-passphrase');
|
||||
let keyServers = [];
|
||||
const needPassphrase = () => {
|
||||
const value = passphraseField().value;
|
||||
if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); }
|
||||
@@ -75,6 +88,26 @@ function openEncryptionKeys() {
|
||||
};
|
||||
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);
|
||||
});
|
||||
}
|
||||
@@ -166,12 +199,117 @@ function openEncryptionKeys() {
|
||||
await renderContacts();
|
||||
} catch (error) { status(error.message || 'Could not import the key.'); }
|
||||
};
|
||||
async function renderKeyServers() {
|
||||
const list = $('#pgp-server-list');
|
||||
const selector = $('#pgp-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();
|
||||
}
|
||||
|
||||
@@ -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)" }
|
||||
@@ -136,3 +136,7 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||
.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,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/);
|
||||
});
|
||||
@@ -166,9 +166,12 @@ test('keyring: contacts, trust levels, expired passphrase cache and settings', a
|
||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/);
|
||||
await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/);
|
||||
await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/);
|
||||
assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10 });
|
||||
await alice.keyStore.setSettings({ cacheMinutes: 0 });
|
||||
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);
|
||||
|
||||
|
||||
+2
-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,10 +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>
|
||||
<button class="label-link" id="attachments-nav"><span class="nav-glyph">▤</span>Attachments</button>
|
||||
<div class="section-label"><span>FOLDERS</span><button class="folder-add" id="add-folder" aria-label="Create folder">+</button></div>
|
||||
<div id="custom-folders" class="folder-nav"></div>
|
||||
<div class="sidebar-divider"></div>
|
||||
<div class="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>
|
||||
|
||||
+80
-7
@@ -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();
|
||||
|
||||
+10
-2
@@ -140,7 +140,8 @@ if (typeof showCompose === 'function') {
|
||||
const encrypt = $('#pgp-encrypt');
|
||||
const sign = $('#pgp-sign');
|
||||
if (reply?.encrypted) { encrypt.checked = true; sign.checked = true; touched = true; }
|
||||
encrypt.addEventListener('change', () => { touched = true; });
|
||||
if (touched) encrypt.dataset.touched = '1';
|
||||
encrypt.addEventListener('change', () => { touched = true; encrypt.dataset.touched = '1'; });
|
||||
let timer = null;
|
||||
const refresh = async () => {
|
||||
const to = $('#compose-to')?.value || '';
|
||||
@@ -170,8 +171,15 @@ 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) return null;
|
||||
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;
|
||||
|
||||
@@ -136,3 +136,7 @@ body.ep-daylight .row-check:checked{accent-color:#526a2c}
|
||||
.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