diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 0106346..8041215 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -86,7 +86,7 @@ The OpenPGP implementation is split into focused modules: 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. +Key-server enablement is persisted in encrypted OpenPGP settings; all servers default to disabled, including custom servers already configured by older versions. The main process enforces enabled status for both lookup and publication. A lookup queries all enabled servers, reports partial failures, and merges duplicate fingerprints while retaining source names. The user chooses one enabled server as the publication target. Custom HTTPS endpoints require a native confirmation when added; redirects and oversized responses are rejected. Returned keys are validated and remain untrusted until the user verifies their fingerprints out of band. Publishing sends only public key material and requires a native confirmation naming the destination for each publication. ## 5. Data flow patterns diff --git a/ENCRYPTION_PLAN.md b/ENCRYPTION_PLAN.md index fa09a2d..e5c4f05 100644 --- a/ENCRYPTION_PLAN.md +++ b/ENCRYPTION_PLAN.md @@ -92,8 +92,8 @@ The desktop Settings → Encryption keys view can search and publish through: - **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. +All built-in and custom servers start disabled. Users enable each server explicitly; disabled servers are not contacted for lookup and cannot be used for publication. Searching is user-triggered and checks every enabled server; ep-mail does not perform background lookups while composing. Search addresses are disclosed to each enabled server. Results identify their source servers and duplicate keys are merged by fingerprint. The main process validates returned OpenPGP keys before showing them, and adding a result uses the existing key-replacement confirmation. Discovered keys enter the contact keyring with `unknown` trust; server publication or lookup is never treated as fingerprint verification. -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. +Publishing targets one explicitly selected enabled server, not all enabled servers. The destination is shown in the Settings control and named again in a native confirmation before upload. The confirmation identifies the server, email address, and fingerprint and explains that the email/key association becomes public and may be retained. Only the selected key's public material is uploaded; private keys and passphrases are never sent. A successful upload may still require the user to complete email verification before the key becomes searchable. Android key-server support is not included because Android OpenPGP support is not implemented. Custom servers are limited to HTTPS HKP/VKS endpoints, redirects are rejected, and lookup responses are size-limited. Key-server data remains subject to the server's availability, privacy practices, and verification policy; users should independently compare fingerprints before trusting a key. diff --git a/README.md b/README.md index 681d8f6..b67f0cc 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 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`. +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, enable selected key servers (all are disabled initially), search all enabled servers, and publish a key to one explicitly selected server after a native confirmation names the destination. Discovered keys remain unverified until you compare fingerprints independently. Desktop can read encrypted or signed OpenPGP mail and encrypt or sign outgoing messages (see [ENCRYPTION_PLAN.md](./ENCRYPTION_PLAN.md)); Android OpenPGP support is not available yet. Run the tests with `npm test`. diff --git a/TODO.md b/TODO.md index b000352..4fcdd2c 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. -- [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. +- [x] Add desktop public key server support for finding and publishing OpenPGP keys: keys.openpgp.org (VKS), keys.mailvelope.com (HKP over HTTPS), and user-defined HTTPS HKP/VKS servers. Servers are disabled until selected; lookup checks all enabled servers, and publishing requires one explicitly selected destination. Discovered keys remain unverified until fingerprint verification. - [ ] 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 bb66300..b903f92 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -1461,7 +1461,23 @@ ipcMain.handle('pgp:set-settings', async (_event, input) => { }); ipcMain.handle('pgp:key-servers', async () => { const settings = await pgpKeys.getSettings(); - return listServers(settings.customKeyServers); + return listServers(settings.customKeyServers, settings.enabledKeyServers); +}); +ipcMain.handle('pgp:set-key-server-enabled', async (_event, input) => { + if (typeof input?.enabled !== 'boolean') throw new Error('Choose whether to enable or disable this key server.'); + const settings = await pgpKeys.getSettings(); + const servers = listServers(settings.customKeyServers, settings.enabledKeyServers); + const serverId = String(input?.serverId || ''); + if (!servers.some(server => server.id === serverId)) throw new Error('That key server was not found.'); + const enabled = new Set(settings.enabledKeyServers); + if (input.enabled) enabled.add(serverId); + else enabled.delete(serverId); + await pgpKeys.setSettings({ + cacheMinutes: settings.cacheMinutes, + customKeyServers: settings.customKeyServers, + enabledKeyServers: [...enabled] + }); + return { serverId, enabled: input.enabled }; }); ipcMain.handle('pgp:add-key-server', async (event, input) => { const candidate = normalizeCustomServer(input); @@ -1495,20 +1511,24 @@ ipcMain.handle('pgp:remove-key-server', async (_event, 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 }); + await pgpKeys.setSettings({ + cacheMinutes: settings.cacheMinutes, + customKeyServers, + enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id) + }); return { removed: true }; }); ipcMain.handle('pgp:find-key', async (_event, input) => { const settings = await pgpKeys.getSettings(); - const 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); + const servers = listServers(settings.customKeyServers, settings.enabledKeyServers); + return pgpKeyServers.lookupEnabled(servers, input?.email); }); ipcMain.handle('pgp:publish-key', async (event, input) => { const fingerprint = pgpFingerprint(input?.fingerprint); const settings = await pgpKeys.getSettings(); - const server = listServers(settings.customKeyServers).find(item => item.id === String(input?.serverId || '')); + const server = listServers(settings.customKeyServers, settings.enabledKeyServers).find(item => item.id === String(input?.serverId || '')); if (!server) throw new Error('Choose a configured key server.'); + if (!server.enabled) throw new Error('Enable the selected key server before publishing to it.'); const entry = (await pgpKeys.list()).find(key => key.fingerprint === fingerprint); if (!entry) throw new Error('That key was not found.'); if (!entry.email) throw new Error('This key has no email address to publish.'); diff --git a/desktop/pgp-keyservers.cjs b/desktop/pgp-keyservers.cjs index 3ec0fa1..ee36f7c 100644 --- a/desktop/pgp-keyservers.cjs +++ b/desktop/pgp-keyservers.cjs @@ -40,10 +40,14 @@ function normalizeCustomServer(input) { }; } -function listServers(customServers = []) { +function listServers(customServers = [], enabledServerIds = []) { + const enabled = new Set(enabledServerIds); return [ - ...BUILTIN_SERVERS.map(server => ({ ...server })), - ...customServers.map(server => normalizeCustomServer(server)) + ...BUILTIN_SERVERS.map(server => ({ ...server, enabled: enabled.has(server.id) })), + ...customServers.map(server => { + const normalized = normalizeCustomServer(server); + return { ...normalized, enabled: enabled.has(normalized.id) }; + }) ]; } @@ -160,6 +164,36 @@ function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) { return parsePublicKeys(armored, email); } + async function lookupEnabled(serverInputs, emailInput) { + const servers = serverInputs.filter(server => server.enabled === true); + if (!servers.length) throw new Error('Enable at least one key server before searching.'); + const email = validateEmail(emailInput); + const lookups = await Promise.all(servers.map(async server => { + try { + return { server, keys: await lookup(server, email), error: null }; + } catch (error) { + return { server, keys: [], error: error.message }; + } + })); + const keysByFingerprint = new Map(); + for (const result of lookups) { + for (const key of result.keys) { + const existing = keysByFingerprint.get(key.fingerprint); + if (existing) existing.sources.push(result.server.name); + else keysByFingerprint.set(key.fingerprint, { ...key, sources: [result.server.name] }); + } + } + return { + keys: [...keysByFingerprint.values()], + searchedServers: lookups.map(({ server }) => ({ id: server.id, name: server.name })), + errors: lookups.filter(result => result.error).map(({ server, error }) => ({ + id: server.id, + name: server.name, + message: error + })) + }; + } + async function publishVks(server, email, armoredKey, expectedFingerprint) { const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), { method: 'POST', @@ -230,7 +264,7 @@ function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) { return publishHkp(server, keys[0].armoredKey); } - return { lookup, publish }; + return { lookup, lookupEnabled, publish }; } module.exports = { diff --git a/desktop/pgp-keystore.cjs b/desktop/pgp-keystore.cjs index 4eea882..d748276 100644 --- a/desktop/pgp-keystore.cjs +++ b/desktop/pgp-keystore.cjs @@ -195,11 +195,14 @@ function createKeyStore(storage) { const settings = (await read()).settings; return { cacheMinutes: Number.isFinite(settings.cacheMinutes) ? settings.cacheMinutes : DEFAULT_CACHE_MINUTES, - customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [] + customKeyServers: Array.isArray(settings.customKeyServers) ? settings.customKeyServers : [], + enabledKeyServers: Array.isArray(settings.enabledKeyServers) + ? [...new Set(settings.enabledKeyServers.filter(id => typeof id === 'string'))] + : [] }; }, - async setSettings({ cacheMinutes, customKeyServers }) { + async setSettings({ cacheMinutes, customKeyServers, enabledKeyServers }) { 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(); @@ -215,10 +218,17 @@ function createKeyStore(storage) { protocol: String(server.protocol || '') })); } + if (enabledKeyServers !== undefined) { + if (!Array.isArray(enabledKeyServers) || enabledKeyServers.length > 12 || enabledKeyServers.some(id => typeof id !== 'string' || !id.trim())) { + throw new Error('Choose no more than 12 valid enabled key servers.'); + } + data.settings.enabledKeyServers = [...new Set(enabledKeyServers)]; + } await storage.save(data); return { cacheMinutes: data.settings.cacheMinutes, - customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [] + customKeyServers: Array.isArray(data.settings.customKeyServers) ? data.settings.customKeyServers : [], + enabledKeyServers: Array.isArray(data.settings.enabledKeyServers) ? [...data.settings.enabledKeyServers] : [] }; }, diff --git a/desktop/preload.cjs b/desktop/preload.cjs index 2e6079f..d51ddf6 100644 --- a/desktop/preload.cjs +++ b/desktop/preload.cjs @@ -42,6 +42,7 @@ contextBridge.exposeInMainWorld('daybreakMail', { setSettings: settings => ipcRenderer.invoke('pgp:set-settings', settings), forgetPassphrases: () => ipcRenderer.invoke('pgp:forget-passphrases'), keyServers: () => ipcRenderer.invoke('pgp:key-servers'), + setKeyServerEnabled: (serverId, enabled) => ipcRenderer.invoke('pgp:set-key-server-enabled', { serverId, enabled }), addKeyServer: server => ipcRenderer.invoke('pgp:add-key-server', server), removeKeyServer: id => ipcRenderer.invoke('pgp:remove-key-server', id), findKey: details => ipcRenderer.invoke('pgp:find-key', details), diff --git a/pgp-ui.js b/pgp-ui.js index d3626ca..da93cff 100644 --- a/pgp-ui.js +++ b/pgp-ui.js @@ -11,12 +11,13 @@ function openEncryptionKeys() {
Loading contacts…

Public key servers

-

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.

+

Servers are disabled by default. Enable the servers you want to use; searching checks every enabled server, which can learn which email address you searched for. Discovered keys remain unverified until you check their fingerprints independently.

Loading key servers…
- -
+
+ +

Publishing targets only the selected enabled server. ep-mail names the destination and asks for native confirmation before uploading.

Add a custom HTTPS server

@@ -39,6 +40,14 @@ function openEncryptionKeys() { const status = message => { $('#pgp-status').textContent = message; }; const passphraseField = () => $('#pgp-passphrase'); let keyServers = []; + const selectedPublishServer = () => keyServers.find(server => server.id === $('#pgp-publish-server').value && server.enabled); + const updatePublishButtons = () => { + const server = selectedPublishServer(); + $$('.pgp-publish').forEach(button => { + button.disabled = !server; + button.textContent = server ? `Publish to ${server.name}…` : 'Enable a server to publish…'; + }); + }; const needPassphrase = () => { const value = passphraseField().value; if (!value) { status('Enter the key passphrase in the Passphrase field first.'); passphraseField().focus(); } @@ -89,27 +98,27 @@ function openEncryptionKeys() { row.append(button); }); const publish = document.createElement('button'); - publish.className = 'discard'; - publish.textContent = 'Publish public key…'; + publish.className = 'discard pgp-publish'; publish.onclick = async () => { - const serverId = $('#pgp-search-server').value; - if (!serverId) { status('Choose a key server first.'); return; } + const server = selectedPublishServer(); + if (!server) { status('Enable a key server and select it as the publication target first.'); return; } publish.disabled = true; try { - const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId }); + const result = await window.daybreakMail.pgp.publishKey({ fingerprint: key.fingerprint, serverId: server.id }); if (result.canceled) return; if (result.warning) status(result.warning); - else if (result.verification === 'pending' || result.verification === 'requested') status(`Uploaded to ${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 === 'pending' || result.verification === 'requested') status(`Uploaded to ${server.name}. Check ${key.email || 'your email'} for a verification message before the key becomes searchable.`); + else if (result.verification === 'published') status(`The key is already published and searchable on ${server.name}.`); else if (result.verification === 'request-failed') status('The key was uploaded, but the server could not request email verification.'); - else if (result.verification === 'check-email') status(`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()); + else if (result.verification === 'check-email') status(`${server.name} accepted the key. Check ${key.email || 'your email'} for its verification message. ${result.message || ''}`.trim()); + else status(`${server.name} accepted the key. ${result.message || ''}`.trim()); } catch (error) { status(error.message || 'Could not publish the public key.'); } - finally { publish.disabled = false; } + finally { updatePublishButtons(); } }; row.append(publish); list.append(row); }); + updatePublishButtons(); } $('#pgp-generate').onclick = async () => { @@ -201,16 +210,26 @@ function openEncryptionKeys() { }; async function renderKeyServers() { const list = $('#pgp-server-list'); - const selector = $('#pgp-search-server'); + const selector = $('#pgp-publish-server'); + const selectedId = selector.value; try { keyServers = await window.daybreakMail.pgp.keyServers(); } catch (error) { list.textContent = error.message || 'Could not load key servers.'; return; } selector.replaceChildren(); - keyServers.forEach(server => { + const enabledServers = keyServers.filter(server => server.enabled); + if (!enabledServers.length) { + const option = document.createElement('option'); + option.value = ''; + option.textContent = 'No enabled servers'; + selector.append(option); + } else enabledServers.forEach(server => { const option = document.createElement('option'); option.value = server.id; option.textContent = `${server.name} (${server.protocol.toUpperCase()})`; + option.selected = server.id === selectedId; selector.append(option); }); + if (selectedId && !enabledServers.some(server => server.id === selectedId)) selector.selectedIndex = 0; + selector.onchange = updatePublishButtons; list.replaceChildren(); keyServers.forEach(server => { const row = document.createElement('div'); @@ -222,7 +241,27 @@ function openEncryptionKeys() { const details = document.createElement('small'); details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`; info.append(title, details); - row.append(info); + const enabledLabel = document.createElement('label'); + enabledLabel.className = 'compose-line'; + const enabledText = document.createElement('span'); + enabledText.textContent = 'Use for lookup and publishing'; + const enabled = document.createElement('input'); + enabled.type = 'checkbox'; + enabled.checked = server.enabled; + enabled.setAttribute('aria-label', `${server.name} enabled`); + enabled.onchange = async () => { + enabled.disabled = true; + try { + await window.daybreakMail.pgp.setKeyServerEnabled(server.id, enabled.checked); + await renderKeyServers(); + status(`${server.name} ${enabled.checked ? 'enabled' : 'disabled'}.`); + } catch (error) { + enabled.checked = server.enabled; + status(error.message || `Could not update ${server.name}.`); + } finally { enabled.disabled = false; } + }; + enabledLabel.append(enabledText, enabled); + row.append(info, enabledLabel); if (!server.builtin) { const remove = document.createElement('button'); remove.className = 'discard'; @@ -246,12 +285,10 @@ function openEncryptionKeys() { 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 => { + found.keys.forEach(key => { const row = document.createElement('div'); row.className = 'attachment-row'; const info = document.createElement('div'); @@ -259,7 +296,7 @@ function openEncryptionKeys() { 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`; + meta.textContent = `Found on ${key.sources.join(', ')} · not verified`; const fingerprint = document.createElement('small'); fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; info.append(title, meta, fingerprint); @@ -280,7 +317,15 @@ function openEncryptionKeys() { row.append(info, add); results.append(row); }); - status(`Found ${found.length} public key(s). They remain unverified until you check their fingerprints independently.`); + found.errors.forEach(error => { + const warning = document.createElement('small'); + warning.textContent = `${error.name}: ${error.message}`; + results.append(warning); + }); + if (!found.keys.length && !found.errors.length) results.textContent = 'No matching public key was found on the enabled servers.'; + if (found.keys.length) status(`Found ${found.keys.length} public key(s) on ${found.searchedServers.map(server => server.name).join(', ')}. They remain unverified until you check their fingerprints independently.${found.errors.length ? ` ${found.errors.length} server(s) could not be searched; see details above.` : ''}`); + else if (found.errors.length) status(`No key results; ${found.errors.length} enabled server(s) could not be searched. See details above.`); + else status(`No matching key found across ${found.searchedServers.length} enabled server(s).`); } catch (error) { results.textContent = ''; status(error.message || 'Could not search the key server.'); diff --git a/tests/pgp-keyservers.test.cjs b/tests/pgp-keyservers.test.cjs index 2cc9a79..081435b 100644 --- a/tests/pgp-keyservers.test.cjs +++ b/tests/pgp-keyservers.test.cjs @@ -1,7 +1,7 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const openpgp = require('openpgp'); -const { createKeyServerService, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs'); +const { createKeyServerService, listServers, normalizeCustomServer } = require('../desktop/pgp-keyservers.cjs'); const { createKeyStore } = require('../desktop/pgp-keystore.cjs'); const email = 'ada@example.org'; @@ -45,6 +45,20 @@ test('validates custom HTTPS key server configuration', () => { assert.throws(() => normalizeCustomServer({ name: 'Unknown protocol', url: 'https://keys.example.org', protocol: 'unknown' }), /protocol/); }); +test('all built-in and custom key servers start disabled', () => { + const servers = listServers([{ + id: 'custom', + name: 'Internal server', + url: 'https://keys.example.org', + protocol: 'hkp' + }]); + assert.equal(servers.length, 3); + assert.ok(servers.every(server => server.enabled === false)); + const enabled = listServers([], ['openpgp-vks']); + assert.equal(enabled.find(server => server.id === 'openpgp-vks').enabled, true); + assert.equal(enabled.find(server => server.id === 'mailvelope-hkp').enabled, false); +}); + test('VKS lookup returns only valid keys matching the requested address', async () => { const key = await makeKey(); let requestedUrl; @@ -85,6 +99,33 @@ test('HKP lookup filters unrelated keys and reports an empty result', async () = assert.deepEqual(await service.lookup(server, 'other@example.org'), []); }); +test('enabled-server lookup checks every enabled server, merges duplicate keys and reports failures', async () => { + const key = await makeKey(); + const requested = []; + const service = createKeyServerService({ + async fetchImpl(url) { + const target = new URL(url); + requested.push(target.hostname); + if (target.hostname === 'broken.example.org') throw new Error('server unavailable'); + return new Response(key.armoredKey, { status: 200 }); + } + }); + const results = await service.lookupEnabled([ + { id: 'one', name: 'First', url: 'https://first.example.org', protocol: 'hkp', enabled: true }, + { id: 'two', name: 'Second', url: 'https://second.example.org', protocol: 'vks', enabled: true }, + { id: 'bad', name: 'Offline', url: 'https://broken.example.org', protocol: 'hkp', enabled: true }, + { id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false } + ], email); + assert.deepEqual(requested.sort(), ['broken.example.org', 'first.example.org', 'second.example.org']); + assert.equal(results.keys.length, 1); + assert.deepEqual(results.keys[0].sources, ['First', 'Second']); + assert.deepEqual(results.errors.map(error => error.name), ['Offline']); + assert.deepEqual(results.searchedServers.map(server => server.name), ['First', 'Second', 'Offline']); + await assert.rejects(() => service.lookupEnabled([ + { id: 'off', name: 'Disabled', url: 'https://disabled.example.org', protocol: 'hkp', enabled: false } + ], email), /Enable at least one key server/); +}); + test('VKS publication uploads only the public key and requests email verification', async () => { const key = await makeKey(); const calls = []; diff --git a/tests/pgp-mail.test.cjs b/tests/pgp-mail.test.cjs index b981070..75e34bc 100644 --- a/tests/pgp-mail.test.cjs +++ b/tests/pgp-mail.test.cjs @@ -166,12 +166,15 @@ test('keyring: contacts, trust levels, expired passphrase cache and settings', a await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPublic(bob.key.fingerprint) }), /already/); await assert.rejects(async () => alice.keyStore.addContact({ armoredKey: await bob.keyStore.exportPrivate(bob.key.fingerprint, bob.passphrase) }), /private key/); await assert.rejects(() => alice.keyStore.addContact({ armoredKey: 'junk' }), /valid OpenPGP/); - assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [] }); + assert.deepEqual(await alice.keyStore.getSettings(), { cacheMinutes: 10, customKeyServers: [], enabledKeyServers: [] }); const customServer = { id: 'custom', name: 'Example', url: 'https://keys.example.org/', protocol: 'hkp' }; - await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer] }); + await alice.keyStore.setSettings({ cacheMinutes: 0, customKeyServers: [customServer], enabledKeyServers: ['custom', 'openpgp-vks'] }); assert.equal((await alice.keyStore.getSettings()).cacheMinutes, 0); await alice.keyStore.setSettings({ cacheMinutes: 5 }); assert.deepEqual((await alice.keyStore.getSettings()).customKeyServers, [customServer]); + assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, ['custom', 'openpgp-vks']); + await alice.keyStore.setSettings({ cacheMinutes: 5, enabledKeyServers: [] }); + assert.deepEqual((await alice.keyStore.getSettings()).enabledKeyServers, []); await alice.keyStore.removeContact(contact.fingerprint); assert.equal((await alice.keyStore.listContacts()).length, 0);