Compare commits

...
2 Commits
Author SHA1 Message Date
thuttuandCopilot acba5d641e Add OpenPGP key passphrase changes
Allow desktop users to re-encrypt an existing key after verifying its current passphrase. Preserve key identity and revocation data, clear its cached passphrase, and document the feature.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 20:44:44 +03:00
thuttuandCopilot f3e68b10bd Add configurable public key server usage
Persist per-server enablement, search enabled servers, and require an explicit publication target. Update documentation and tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-10 20:28:24 +03:00
12 changed files with 312 additions and 44 deletions
+1 -1
View File
@@ -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
+3 -3
View File
@@ -25,7 +25,7 @@ Decision: OpenPGP only for v1; S/MIME may follow later.
- Android: wrap with a hardware-backed Android Keystore key; optional biometric unlock (Phase 4).
- The passphrase is cached only in memory for a configurable time, then wiped (Phase 4). It is never written to disk.
- Export as ASCII-armored files; a revocation certificate is generated when a key is created and can be exported after unlocking.
- Deleting or exporting a private key requires the passphrase.
- Deleting or exporting a private key requires the passphrase. Desktop users can change a key's passphrase by verifying the current one and entering the new one twice; the public key and revocation certificate are preserved.
**Public keys**
- Per-account contact keyring: address, fingerprint, trust level, source.
@@ -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.
+1 -1
View File
@@ -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`.
+2 -2
View File
@@ -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.
- [x] Add the ability to change the passphrase of an encryption key on desktop.
+32 -6
View File
@@ -1319,6 +1319,12 @@ ipcMain.handle('pgp:export-private', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-private-${id.slice(-16)}.asc`, await pgpKeys.exportPrivate(id, passphrase));
});
ipcMain.handle('pgp:change-passphrase', async (_event, input) => {
const id = pgpFingerprint(input?.fingerprint);
const result = await pgpKeys.changePassphrase(id, input?.currentPassphrase, input?.newPassphrase);
pgpCache.clear(id);
return result;
});
ipcMain.handle('pgp:export-revocation', async (event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
return saveKeyFile(event, `ep-mail-revocation-${id.slice(-16)}.asc`, await pgpKeys.exportRevocation(id, passphrase));
@@ -1461,7 +1467,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 +1517,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.');
+38 -4
View File
@@ -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 = {
+31 -3
View File
@@ -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] : []
};
},
@@ -295,6 +305,24 @@ function createKeyStore(storage) {
return entry.privateKey;
},
async changePassphrase(fingerprint, currentPassphrase, newPassphrase) {
requirePassphrase(newPassphrase);
const data = await read();
const keyIndex = data.keys.findIndex(key => key.fingerprint === fingerprint);
if (keyIndex < 0) throw new Error('That key was not found.');
const entry = data.keys[keyIndex];
const privateKey = await unlock(entry.privateKey, currentPassphrase);
const protectedKey = await openpgp.encryptKey({ privateKey, passphrase: newPassphrase });
const updated = {
...data,
keys: data.keys.map((key, index) => index === keyIndex
? { ...key, privateKey: protectedKey.armor() }
: key)
};
await storage.save(updated);
return { changed: true };
},
async exportRevocation(fingerprint, passphrase) {
const entry = (await read()).keys.find(key => key.fingerprint === fingerprint);
if (!entry) throw new Error('That key was not found.');
+2
View File
@@ -29,6 +29,7 @@ contextBridge.exposeInMainWorld('daybreakMail', {
importKey: details => ipcRenderer.invoke('pgp:import', details),
exportPublic: fingerprint => ipcRenderer.invoke('pgp:export-public', fingerprint),
exportPrivate: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-private', fingerprint, passphrase),
changePassphrase: details => ipcRenderer.invoke('pgp:change-passphrase', details),
exportRevocation: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:export-revocation', fingerprint, passphrase),
remove: (fingerprint, passphrase) => ipcRenderer.invoke('pgp:delete', fingerprint, passphrase),
decryptMessage: details => ipcRenderer.invoke('pgp:decrypt-message', details),
@@ -42,6 +43,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),
+109 -21
View File
@@ -7,16 +7,22 @@ function openEncryptionKeys() {
root.innerHTML = `<div class="modal-overlay"><div class="compose-modal attachments-modal"><div class="modal-head"><span>Encryption keys</span><button class="modal-close" aria-label="Close">×</button></div><div class="compose-fields">
<p class="account-note">OpenPGP keys are protected by a passphrase and stored encrypted by your operating system. Back up your private key and revocation certificate: without them, encrypted mail cannot be recovered. Contact keys below are used to encrypt mail to your correspondents and to check signatures.</p>
<div id="pgp-key-list" class="attachment-list">Loading keys…</div>
<h3 class="pgp-heading">Change a key passphrase</h3>
<label class="compose-line"><span>Current passphrase</span><input id="pgp-change-current-passphrase" type="password" autocomplete="current-password"></label>
<label class="compose-line"><span>New passphrase</span><input id="pgp-new-passphrase" type="password" autocomplete="new-password" placeholder="At least 8 characters"></label>
<label class="compose-line"><span>Confirm new passphrase</span><input id="pgp-confirm-passphrase" type="password" autocomplete="new-password" placeholder="Enter the new passphrase again"></label>
<p class="account-note">Select Change passphrase on a key below. Its public key and revocation certificate will not change.</p>
<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>
<p class="account-note">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.</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 class="pgp-actions"><button class="discard" id="pgp-find-key">Search all enabled servers</button></div>
<div id="pgp-found-keys" class="attachment-list"></div>
<label class="compose-line"><span>Publish to one server</span><select id="pgp-publish-server"></select></label>
<p class="account-note">Publishing targets only the selected enabled server. ep-mail names the destination and asks for native confirmation before uploading.</p>
<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>
@@ -39,6 +45,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(); }
@@ -68,6 +82,44 @@ function openEncryptionKeys() {
['Export public', () => window.daybreakMail.pgp.exportPublic(key.fingerprint), false],
['Export private', () => window.daybreakMail.pgp.exportPrivate(key.fingerprint, needPassphrase()), true]
];
const changePassphrase = document.createElement('button');
changePassphrase.className = 'discard';
changePassphrase.textContent = 'Change passphrase…';
changePassphrase.onclick = async () => {
const currentPassphrase = $('#pgp-change-current-passphrase').value;
if (!currentPassphrase) {
status('Enter the current passphrase for this key.');
$('#pgp-change-current-passphrase').focus();
return;
}
const newPassphrase = $('#pgp-new-passphrase').value;
if (newPassphrase.length < 8) {
status('Use a new passphrase of at least 8 characters.');
$('#pgp-new-passphrase').focus();
return;
}
if (newPassphrase !== $('#pgp-confirm-passphrase').value) {
status('The new passphrases do not match.');
$('#pgp-confirm-passphrase').focus();
return;
}
changePassphrase.disabled = true;
try {
await window.daybreakMail.pgp.changePassphrase({
fingerprint: key.fingerprint,
currentPassphrase,
newPassphrase
});
$('#pgp-change-current-passphrase').value = '';
status(`Passphrase changed for ${key.email || key.fingerprint}.`);
} catch (error) { status(error.message || 'Could not change the key passphrase.'); }
finally {
$('#pgp-new-passphrase').value = '';
$('#pgp-confirm-passphrase').value = '';
changePassphrase.disabled = false;
}
};
row.append(changePassphrase);
if (key.hasRevocationCertificate) actions.push(['Revocation cert.', () => window.daybreakMail.pgp.exportRevocation(key.fingerprint, needPassphrase()), true]);
actions.push(['Delete', async () => {
if (!confirm('Delete this key? Encrypted mail that needs it can no longer be read unless you have a backup.')) return { canceled: true };
@@ -89,27 +141,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 +253,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 +284,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 +328,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 +339,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 +360,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.');
+42 -1
View File
@@ -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 = [];
+46
View File
@@ -43,6 +43,52 @@ test('export requires the right passphrase and round-trips through import', asyn
assert.ok((await second.exportPublic(key.fingerprint)).includes('BEGIN PGP PUBLIC KEY BLOCK'));
});
test('changes a key passphrase without changing its public identity or revocation certificate', async () => {
const storage = memoryStore();
const keys = createKeyStore(storage);
const { key, revocationCertificate } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
const original = JSON.parse(JSON.stringify((await storage.load()).keys[0]));
const newPassphrase = 'new passphrase securely';
await assert.rejects(keys.changePassphrase(key.fingerprint, 'wrong passphrase', newPassphrase), /incorrect/);
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'short'), /at least 8/);
assert.deepEqual((await storage.load()).keys[0], original);
assert.deepEqual(await keys.changePassphrase(key.fingerprint, passphrase, newPassphrase), { changed: true });
const changed = (await storage.load()).keys[0];
assert.equal(changed.fingerprint, original.fingerprint);
assert.equal(changed.publicKey, original.publicKey);
assert.equal(changed.name, original.name);
assert.equal(changed.email, original.email);
assert.equal(changed.accountId, original.accountId);
assert.equal(changed.createdAt, original.createdAt);
assert.equal(changed.algorithm, original.algorithm);
assert.equal(changed.revocationCertificate, original.revocationCertificate);
assert.notEqual(changed.privateKey, original.privateKey);
await assert.rejects(keys.exportPrivate(key.fingerprint, passphrase), /incorrect/);
assert.equal(await keys.exportPrivate(key.fingerprint, newPassphrase), changed.privateKey);
assert.equal(await keys.exportRevocation(key.fingerprint, newPassphrase), revocationCertificate);
});
test('does not mutate the loaded key if saving a changed passphrase fails', async () => {
let data = null;
let failSave = false;
const storage = {
load: async () => data,
save: async value => {
if (failSave) throw new Error('Storage unavailable.');
data = JSON.parse(JSON.stringify(value));
}
};
const keys = createKeyStore(storage);
const { key } = await keys.generate({ name: 'Ada', email: 'ada@example.com', passphrase });
const original = JSON.parse(JSON.stringify(data.keys[0]));
failSave = true;
await assert.rejects(keys.changePassphrase(key.fingerprint, passphrase, 'new passphrase securely'), /Storage unavailable/);
assert.deepEqual(data.keys[0], original);
});
test('imports an unprotected key by encrypting it with the given passphrase', async () => {
const { privateKey } = await openpgp.generateKey({ type: 'curve25519', userIDs: [{ email: 'bob@example.com' }], format: 'armored' });
const keys = createKeyStore(memoryStore());
+5 -2
View File
@@ -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);