(() => { // Encryption key management (desktop). Hidden where the platform has no key store yet. const pgpKeyMailUi = window.epMailFeatures.mail; const selectPgpKeyUi = pgpKeyMailUi.select; const selectAllPgpKeyUi = pgpKeyMailUi.selectAll; const escapePgpKeyUi = pgpKeyMailUi.escapeHtml; const toastPgpKeyUi = pgpKeyMailUi.toast; function pgpAvailable() { return Boolean(window.daybreakMail?.pgp); } async function saveAndroidPgpExport(label, value) { if (window.daybreakMail?.pgp?.platform !== 'android' || typeof value !== 'string') return value; const warning = /private|revocation/i.test(label) ? ' This contains secret key material; keep it private.' : ''; if (!confirm(`Copy this ${label.toLowerCase()} to the clipboard?${warning}`)) return { canceled: true }; if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(value); else if (prompt(`Copy this ${label.toLowerCase()}:`, value) === null) return { canceled: true }; return { saved: true }; } function openEncryptionKeys() { const root = selectPgpKeyUi('#modal-root'); const account = window.epMailFeatures.mail.connectedAccount || {}; const androidPgp = window.daybreakMail?.pgp?.platform === 'android'; const serverSettings = `

Public key servers

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

`; root.innerHTML = ``; const close = () => { root.innerHTML = ''; }; root.querySelector('.modal-close').onclick = close; root.querySelector('.modal-overlay').onclick = event => { if (event.target.classList.contains('modal-overlay')) close(); }; const status = message => { selectPgpKeyUi('#pgp-status').textContent = message; }; const passphraseField = () => selectPgpKeyUi('#pgp-passphrase'); let keyServers = []; const selectedPublishServer = () => keyServers.find(server => server.id === selectPgpKeyUi('#pgp-publish-server').value && server.enabled); const updatePublishButtons = () => { const server = selectedPublishServer(); selectAllPgpKeyUi('.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(); } return value; }; async function render() { const list = selectPgpKeyUi('#pgp-key-list'); let keys = []; try { keys = await window.daybreakMail.pgp.list(); } catch (error) { list.textContent = error.message || 'Could not load keys.'; return; } list.replaceChildren(); if (!keys.length) { list.textContent = 'No keys yet.'; return; } keys.forEach(key => { const row = document.createElement('div'); row.className = 'attachment-row'; const info = document.createElement('div'); info.className = 'attachment-row-info'; const title = document.createElement('strong'); title.textContent = key.email || 'OpenPGP key'; const meta = document.createElement('small'); meta.textContent = `${key.name ? key.name + ' · ' : ''}${key.algorithm} · ${new Date(key.createdAt).toLocaleDateString()}`; const fingerprint = document.createElement('small'); fingerprint.textContent = `Fingerprint: ${key.fingerprint.match(/.{1,4}/g).join(' ')}`; info.append(title, meta, fingerprint); row.append(info); const actions = [ ['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 = selectPgpKeyUi('#pgp-change-current-passphrase').value; if (!currentPassphrase) { status('Enter the current passphrase for this key.'); selectPgpKeyUi('#pgp-change-current-passphrase').focus(); return; } const newPassphrase = selectPgpKeyUi('#pgp-new-passphrase').value; if (newPassphrase.length < 8) { status('Use a new passphrase of at least 8 characters.'); selectPgpKeyUi('#pgp-new-passphrase').focus(); return; } if (newPassphrase !== selectPgpKeyUi('#pgp-confirm-passphrase').value) { status('The new passphrases do not match.'); selectPgpKeyUi('#pgp-confirm-passphrase').focus(); return; } changePassphrase.disabled = true; try { await window.daybreakMail.pgp.changePassphrase({ fingerprint: key.fingerprint, currentPassphrase, newPassphrase }); selectPgpKeyUi('#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 { selectPgpKeyUi('#pgp-new-passphrase').value = ''; selectPgpKeyUi('#pgp-confirm-passphrase').value = ''; changePassphrase.disabled = false; } }; row.append(changePassphrase); if (androidPgp) { const biometric = document.createElement('button'); biometric.className = 'discard'; biometric.textContent = 'Checking biometric unlock…'; biometric.disabled = true; row.append(biometric); window.daybreakMail.pgp.biometricUnlockEnabled(key.fingerprint).then(enabled => { if (!biometric.isConnected) return; biometric.dataset.enabled = String(enabled); biometric.textContent = enabled ? 'Disable biometric unlock' : 'Set up biometric unlock…'; biometric.disabled = false; }).catch(error => { if (biometric.isConnected) status(error.message || 'Could not load biometric unlock settings.'); }); biometric.onclick = async () => { biometric.disabled = true; try { if (biometric.dataset.enabled === 'true') { if (!confirm('Disable biometric unlock for this key? Its PGP passphrase will still be required.')) return; await window.daybreakMail.pgp.disableBiometricUnlock(key.fingerprint); status('Biometric unlock disabled.'); } else { const passphrase = needPassphrase(); if (!passphrase) return; await window.daybreakMail.pgp.enableBiometricUnlock({ fingerprint: key.fingerprint, passphrase }); passphraseField().value = ''; status('Biometric unlock enabled. Your OpenPGP key remains passphrase-protected.'); } await render(); } catch (error) { status(error.message || 'Could not update biometric key unlock.'); } finally { biometric.disabled = false; } }; } 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 }; await window.daybreakMail.pgp.remove(key.fingerprint, needPassphrase()); await render(); return { deleted: true }; }, true]); actions.forEach(([label, run, secret]) => { const button = document.createElement('button'); button.className = 'discard'; button.textContent = label; button.onclick = async () => { if (secret && !passphraseField().value) { needPassphrase(); return; } try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'File saved.' : result?.deleted ? 'Key deleted.' : ''); } catch (error) { status(error.message || 'That action failed.'); } }; row.append(button); }); const publish = document.createElement('button'); publish.className = 'discard pgp-publish'; publish.onclick = async () => { 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: server.id }); if (result.canceled) return; if (result.warning) status(result.warning); 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(`${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 { updatePublishButtons(); } }; row.append(publish); list.append(row); }); updatePublishButtons(); } selectPgpKeyUi('#pgp-generate').onclick = async () => { const button = selectPgpKeyUi('#pgp-generate'); button.disabled = true; status('Creating key…'); try { await window.daybreakMail.pgp.generate({ name: selectPgpKeyUi('#pgp-name').value, email: selectPgpKeyUi('#pgp-email').value, passphrase: passphraseField().value, accountId: account.id || null }); status('Key created. Export your private key and revocation certificate now and keep them safe.'); await render(); } catch (error) { status(error.message || 'Could not create the key.'); } button.disabled = false; }; const importPrivateKey = async source => { const passphrase = needPassphrase(); if (!passphrase) return; try { const result = await window.daybreakMail.pgp.importKey({ passphrase, accountId: account.id || null, ...(androidPgp ? { source } : {}) }); status(result.canceled ? '' : result.keyChangedFrom?.length ? 'Key imported. You already have a different key for this address; compare fingerprints before trusting either key.' : 'Key imported.'); if (!result.canceled) await render(); } catch (error) { status(error.message || 'Could not import the key.'); } }; selectPgpKeyUi('#pgp-import').onclick = () => importPrivateKey(androidPgp ? 'file' : undefined); if (androidPgp) selectPgpKeyUi('#pgp-import-paste').onclick = () => importPrivateKey('paste'); async function renderContacts() { const list = selectPgpKeyUi('#pgp-contact-list'); let contacts = []; try { contacts = await window.daybreakMail.pgp.contacts(); } catch (error) { list.textContent = error.message || 'Could not load contacts.'; return; } list.replaceChildren(); if (!contacts.length) { list.textContent = 'No contact keys yet. Import a public key, or add one from a received message.'; return; } contacts.forEach(contact => { const row = document.createElement('div'); row.className = 'attachment-row'; const info = document.createElement('div'); info.className = 'attachment-row-info'; const title = document.createElement('strong'); title.textContent = contact.emails.join(', ') || contact.name || 'Public key'; const meta = document.createElement('small'); meta.textContent = `${contact.name ? contact.name + ' · ' : ''}added ${new Date(contact.addedAt).toLocaleDateString()} · from ${contact.source}`; const fingerprint = document.createElement('small'); fingerprint.textContent = `Fingerprint: ${contact.fingerprint.match(/.{1,4}/g).join(' ')}`; info.append(title, meta, fingerprint); const trust = document.createElement('select'); trust.className = 'pgp-trust'; trust.setAttribute('aria-label', 'Key trust'); [['unknown', 'Not verified'], ['trusted', 'Trusted'], ['verified', 'Verified (fingerprint checked)']].forEach(([value, label]) => { const option = document.createElement('option'); option.value = value; option.textContent = label; option.selected = contact.trust === value; trust.append(option); }); trust.onchange = async () => { if (trust.value === 'verified' && !confirm(`Mark this key as verified only if you compared this fingerprint with its owner through another channel:\n\n${contact.fingerprint.match(/.{1,4}/g).join(' ')}`)) { trust.value = contact.trust; return; } try { await window.daybreakMail.pgp.setTrust(contact.fingerprint, trust.value); contact.trust = trust.value; status('Trust updated.'); } catch (error) { trust.value = contact.trust; status(error.message || 'Could not update trust.'); } }; const actions = [ ['Export', () => window.daybreakMail.pgp.exportContact(contact.fingerprint)], ['Remove', async () => { if (!confirm('Remove this contact key? You will no longer be able to encrypt to it.')) return { canceled: true }; await window.daybreakMail.pgp.removeContact(contact.fingerprint); await renderContacts(); return { deleted: true }; }] ]; row.append(info, trust); actions.forEach(([label, run]) => { const button = document.createElement('button'); button.className = 'discard'; button.textContent = label; button.onclick = async () => { try { const result = await saveAndroidPgpExport(label, await run()); status(result?.saved ? 'Copied to clipboard.' : result?.deleted ? 'Contact key removed.' : ''); } catch (error) { status(error.message || 'That action failed.'); } }; row.append(button); }); list.append(row); }); } selectPgpKeyUi('#pgp-add-contact').onclick = async () => { try { const result = await window.daybreakMail.pgp.addContact({}); if (!result.canceled) status(result.keyChangedFrom?.length ? 'Key added. Warning: you already had a different key for this address. Verify the new fingerprint.' : 'Public key added. Verify its fingerprint with the owner, then mark it as verified.'); await renderContacts(); } catch (error) { status(error.message || 'Could not import the key.'); } }; async function renderKeyServers() { const list = selectPgpKeyUi('#pgp-server-list'); const selector = selectPgpKeyUi('#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(); 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'); row.className = 'attachment-row'; const info = document.createElement('div'); info.className = 'attachment-row-info'; const title = document.createElement('strong'); title.textContent = server.name; const details = document.createElement('small'); details.textContent = `${server.protocol.toUpperCase()} · ${server.url}${server.builtin ? ' · built in' : ' · custom'}`; info.append(title, details); 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); const remove = document.createElement('button'); remove.className = 'discard'; remove.textContent = 'Remove'; remove.onclick = async () => { try { await window.daybreakMail.pgp.removeKeyServer(server.id); await renderKeyServers(); status(`${server.name} removed.`); } catch (error) { status(error.message || 'Could not remove the key server.'); } }; row.append(remove); list.append(row); }); } selectPgpKeyUi('#pgp-find-key').onclick = async () => { const button = selectPgpKeyUi('#pgp-find-key'); const results = selectPgpKeyUi('#pgp-found-keys'); button.disabled = true; results.textContent = 'Searching…'; try { const found = await window.daybreakMail.pgp.findKey({ email: selectPgpKeyUi('#pgp-search-email').value }); results.replaceChildren(); found.keys.forEach(key => { const row = document.createElement('div'); row.className = 'attachment-row'; const info = document.createElement('div'); info.className = 'attachment-row-info'; const title = document.createElement('strong'); title.textContent = key.emails.join(', ') || key.name || 'Public key'; const meta = document.createElement('small'); meta.textContent = `Found on ${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); const add = document.createElement('button'); add.className = 'discard'; add.textContent = 'Add to contacts…'; add.onclick = async () => { add.disabled = true; try { const result = await window.daybreakMail.pgp.addContact({ armoredKey: key.armoredKey, source: 'keyserver' }); if (result.canceled) return; status(result.keyChangedFrom?.length ? 'Key added. You already had another key for this address; compare fingerprints before trusting either key.' : 'Key added as unverified. Compare its fingerprint with the owner before trusting it.'); await renderContacts(); row.remove(); } catch (error) { status(error.message || 'Could not add the public key.'); } finally { add.disabled = false; } }; row.append(info, add); results.append(row); }); 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.'); } finally { button.disabled = false; } }; selectPgpKeyUi('#pgp-add-server').onclick = async () => { const button = selectPgpKeyUi('#pgp-add-server'); button.disabled = true; try { const result = await window.daybreakMail.pgp.addKeyServer({ name: selectPgpKeyUi('#pgp-server-name').value, url: selectPgpKeyUi('#pgp-server-url').value, protocol: selectPgpKeyUi('#pgp-server-protocol').value }); if (result.canceled) return; selectPgpKeyUi('#pgp-server-name').value = ''; selectPgpKeyUi('#pgp-server-url').value = ''; await renderKeyServers(); status('Custom key server added.'); } catch (error) { status(error.message || 'Could not add the key server.'); } finally { button.disabled = false; } }; window.daybreakMail.pgp.getSettings().then(settings => { selectPgpKeyUi('#pgp-cache-minutes').value = settings.cacheMinutes; }).catch(() => {}); selectPgpKeyUi('#pgp-save-cache').onclick = async () => { try { const settings = await window.daybreakMail.pgp.setSettings({ cacheMinutes: Number(selectPgpKeyUi('#pgp-cache-minutes').value) }); status(`Passphrases are remembered for ${settings.cacheMinutes} minute(s).`); } catch (error) { status(error.message || 'Could not save the setting.'); } }; selectPgpKeyUi('#pgp-forget').onclick = async () => { await window.daybreakMail.pgp.forgetPassphrases(); status('Remembered passphrases were cleared.'); }; void renderKeyServers(); void renderContacts(); void render(); } window.epMailFeatures.productivity.wrapOpenPreferences(baseOpenPreferences => async function () { await baseOpenPreferences(); const fields = selectPgpKeyUi('#modal-root .compose-fields'); if (!fields || !pgpAvailable()) return; const button = document.createElement('button'); button.type = 'button'; button.className = 'discard'; button.id = 'open-encryption-keys'; button.textContent = 'Encryption keys…'; button.onclick = openEncryptionKeys; fields.append(button); }); })();