diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b0b3fe1..0106346 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -70,6 +70,7 @@ The current architecture takes a strict trust split: 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. @@ -80,10 +81,13 @@ 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. diff --git a/ENCRYPTION_PLAN.md b/ENCRYPTION_PLAN.md index 12ebf79..fa09a2d 100644 --- a/ENCRYPTION_PLAN.md +++ b/ENCRYPTION_PLAN.md @@ -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 @@ -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. diff --git a/README.md b/README.md index 752ca91..681d8f6 100644 --- a/README.md +++ b/README.md @@ -33,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`. diff --git a/TODO.md b/TODO.md index 790f9e6..b000352 100644 --- a/TODO.md +++ b/TODO.md @@ -67,7 +67,7 @@ - [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. -- [ ] 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. +- [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. diff --git a/desktop/main.cjs b/desktop/main.cjs index 3cb0dde..bb66300 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -8,6 +8,7 @@ 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'); @@ -220,6 +221,7 @@ 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 { @@ -1423,7 +1425,8 @@ ipcMain.handle('pgp:add-contact', async (event, input) => { }); if (response !== 1) throw new Error('Key replacement cancelled.'); } - return pgpKeys.addContact({ armoredKey, source: input?.source === 'message' ? 'message' : 'import' }); + 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); @@ -1456,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) => { diff --git a/desktop/pgp-keyservers.cjs b/desktop/pgp-keyservers.cjs new file mode 100644 index 0000000..3ec0fa1 --- /dev/null +++ b/desktop/pgp-keyservers.cjs @@ -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 +}; diff --git a/desktop/pgp-keystore.cjs b/desktop/pgp-keystore.cjs index a0131ce..4eea882 100644 --- a/desktop/pgp-keystore.cjs +++ b/desktop/pgp-keystore.cjs @@ -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() { diff --git a/desktop/preload.cjs b/desktop/preload.cjs index 3772f96..2e6079f 100644 --- a/desktop/preload.cjs +++ b/desktop/preload.cjs @@ -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), diff --git a/pgp-ui.js b/pgp-ui.js index 80aa35d..d3626ca 100644 --- a/pgp-ui.js +++ b/pgp-ui.js @@ -10,6 +10,18 @@ function openEncryptionKeys() {
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.
+ + + + + +