Fix PGP security review items and add architecture docs
- Harden key replacement in the Electron main process with a confirmation dialog showing the old and new fingerprints before accepting a replacement. - Enforce plaintext-send checks in the main process before allowing a message to be sent without encryption when recipient keys exist. - Reject the insecure Linux safeStorage basic_text backend before writing mail credentials or OpenPGP keys. - Update the security review findings to reflect the fixes and mark the related TODO item as complete. - Add a project architecture overview and link it from the main README.
This commit is contained in:
+112
@@ -0,0 +1,112 @@
|
||||
# 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.
|
||||
- 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/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.
|
||||
|
||||
## 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.
|
||||
@@ -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:
|
||||
|
||||
+7
-7
@@ -48,11 +48,11 @@ Fresh review of the same scope after the first round of fixes. Tests: 20 passed,
|
||||
|
||||
| # | 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 | Open |
|
||||
| 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 | Open |
|
||||
| 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 | Open |
|
||||
| 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 |
|
||||
|
||||
Suggested fixes:
|
||||
- #3: native confirmation showing both fingerprints when a key overlaps existing contacts, and do not select the new key until confirmed.
|
||||
- #4: make the main process decide on plaintext sends when recipient keys exist, with a trusted confirmation.
|
||||
- #5: on Linux, reject or warn on `basic_text`, or add independent encryption.
|
||||
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.
|
||||
@@ -69,5 +69,5 @@
|
||||
- [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.
|
||||
- [ ] Add public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKPS), and user-defined custom key servers.
|
||||
- [ ] Add the ability to attach files to outgoing mails.
|
||||
- [ ] Fix security review findings: confirm key replacement in the main process, enforce the plaintext-send check in the main process, and handle the Linux safeStorage basic_text backend. See SECURITY_REVIEW.md.
|
||||
- [x] 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.
|
||||
|
||||
+61
-2
@@ -7,6 +7,7 @@ const { simpleParser } = require('mailparser');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const { createDAVClient } = require('tsdav');
|
||||
const ICAL = require('ical.js');
|
||||
const openpgp = require('openpgp');
|
||||
|
||||
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
|
||||
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
||||
@@ -200,6 +201,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 +210,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 });
|
||||
@@ -220,6 +223,7 @@ const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
|
||||
|
||||
async function readDavStore() {
|
||||
try {
|
||||
assertSecureStorage();
|
||||
const encrypted = await fs.readFile(davCredentialsPath());
|
||||
const { result } = await safeStorage.decryptStringAsync(encrypted);
|
||||
return JSON.parse(result);
|
||||
@@ -230,6 +234,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 });
|
||||
@@ -340,9 +345,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 +376,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,6 +1397,32 @@ ipcMain.handle('pgp:add-contact', async (event, input) => {
|
||||
if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.');
|
||||
armoredKey = await fs.readFile(result.filePaths[0], 'utf8');
|
||||
}
|
||||
const key = await openpgp.readKey({ armoredKey }).catch(() => {
|
||||
throw new Error('That is not a valid OpenPGP public key.');
|
||||
});
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
const emails = [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))];
|
||||
const existing = await pgpKeys.listContacts();
|
||||
const overlaps = existing.filter(item => (item.emails || []).some(email => emails.includes(String(email).toLowerCase())));
|
||||
if (overlaps.length) {
|
||||
const detail = overlaps.map(item => {
|
||||
const name = item.name || 'Unknown contact';
|
||||
const addresses = (item.emails || []).join(', ') || 'no address';
|
||||
const fp = String(item.fingerprint || '').replace(/(.{4})/g, '$1 ').trim();
|
||||
return `${name} (${addresses})\nFingerprint: ${fp}`;
|
||||
}).join('\n\n');
|
||||
const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), {
|
||||
type: 'warning',
|
||||
buttons: ['Cancel', 'Replace key'],
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
title: 'Confirm key replacement',
|
||||
message: 'A different public key already exists for this email address.',
|
||||
detail: `New key:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nExisting key(s):\n${detail}\n\nOnly continue if you verified the new fingerprint with the owner.`,
|
||||
noLink: true
|
||||
});
|
||||
if (response !== 1) throw new Error('Key replacement cancelled.');
|
||||
}
|
||||
return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' });
|
||||
});
|
||||
ipcMain.handle('pgp:set-trust', async (event, fingerprint, trust) => {
|
||||
@@ -1496,12 +1538,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);
|
||||
|
||||
Reference in New Issue
Block a user