function pgpFailure(error) { return { failed: true, code: error.code, message: error.message, fingerprint: error.details?.fingerprint || null, email: error.details?.email || null, missing: error.details?.missing || [] }; } function registerPgpIpcHandlers({ registerIpcHandler, BrowserWindow, dialog, fs, openpgp, pgpKeys, pgpCache, pgpMail, PgpError, pgpKeyServers, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer, randomUUID, readAccount, imapClient, folderPath, simpleParser, extractMailContent }) { async function fetchMessageSource(account, folder, uid) { if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); const client = await imapClient(account); try { await client.connect(); const mailboxPath = await folderPath(client, folder); if (!mailboxPath) throw new Error('That mail folder could not be found.'); const lock = await client.getMailboxLock(mailboxPath); try { const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true }); if (!item?.source) throw new Error('The message is no longer available.'); return item.source; } finally { lock.release(); } } finally { if (client.usable) await client.logout().catch(() => {}); } } async function saveKeyFile(event, defaultName, content) { const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: defaultName }); if (result.canceled || !result.filePath) return { canceled: true }; await fs.writeFile(result.filePath, content, { mode: 0o600 }); return { saved: true }; } const pgpFingerprint = value => { const fingerprint = String(value || '').toUpperCase(); if (!/^[0-9A-F]{40,64}$/.test(fingerprint)) throw new Error('That key could not be identified.'); return fingerprint; }; registerIpcHandler('pgp:list', () => pgpKeys.list()); registerIpcHandler('pgp:generate', (_event, input) => pgpKeys.generate({ name: input?.name, email: input?.email, passphrase: input?.passphrase, accountId: input?.accountId || null })); registerIpcHandler('pgp:import', async (event, input) => { let armoredKey = input?.armoredKey; if (!armoredKey) { const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), { properties: ['openFile'], filters: [{ name: 'OpenPGP keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }] }); if (result.canceled || !result.filePaths[0]) return { canceled: true }; const stat = await fs.stat(result.filePaths[0]); if (stat.size > 200000) throw new Error('That key file is too large.'); armoredKey = await fs.readFile(result.filePaths[0], 'utf8'); } return { key: await pgpKeys.import({ armoredKey, passphrase: input?.passphrase, accountId: input?.accountId || null }) }; }); registerIpcHandler('pgp:export-public', async (event, fingerprint) => { const id = pgpFingerprint(fingerprint); return saveKeyFile(event, `ep-mail-public-${id.slice(-16)}.asc`, await pgpKeys.exportPublic(id)); }); registerIpcHandler('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)); }); registerIpcHandler('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; }); registerIpcHandler('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)); }); registerIpcHandler('pgp:delete', async (_event, fingerprint, passphrase) => { const id = pgpFingerprint(fingerprint); const result = await pgpKeys.remove(id, passphrase); pgpCache.clear(id); return result; }); registerIpcHandler('pgp:decrypt-message', async (_event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before opening messages.'); const source = await fetchMessageSource(account, String(input?.folder || 'Inbox'), Number(input?.uid)); const outer = await simpleParser(source); try { const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null }); const content = extractMailContent(result.parsed); return { ok: true, body: content.body, html: content.html, links: content.links, attachments: content.attachments, attachment: content.attachment, size: content.size, signatures: result.signatures, attachedKeys: result.attachedKeys.map(key => ({ fingerprint: key.fingerprint, emails: key.emails, armoredKey: key.armoredKey })) }; } catch (error) { if (error instanceof PgpError) return pgpFailure(error); throw error; } }); registerIpcHandler('pgp:check-send', async (_event, input) => { const account = await readAccount(); return pgpMail.recipientStatus([input?.to, input?.cc], { sign: Boolean(input?.sign), from: account?.email || '' }); }); registerIpcHandler('pgp:contacts', () => pgpKeys.listContacts()); registerIpcHandler('pgp:add-contact', async (event, input) => { let armoredKey = typeof input?.armoredKey === 'string' ? input.armoredKey : ''; if (!armoredKey) { const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), { properties: ['openFile'], filters: [{ name: 'OpenPGP public keys', extensions: ['asc', 'gpg', 'pgp', 'key', 'txt'] }] }); if (result.canceled || !result.filePaths[0]) return { canceled: true }; if ((await fs.stat(result.filePaths[0])).size > 200000) throw new Error('That key file is too large.'); armoredKey = await fs.readFile(result.filePaths[0], 'utf8'); } const key = await openpgp.readKey({ armoredKey }).catch(() => { throw new Error('That is not a valid OpenPGP public key.'); }); const fingerprint = key.getFingerprint().toUpperCase(); const emails = [...new Set(key.getUserIDs().map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase()).filter(Boolean))]; const existing = await pgpKeys.listContacts(); const overlaps = existing.filter(item => (item.emails || []).some(email => emails.includes(String(email).toLowerCase()))); if (overlaps.length) { const detail = overlaps.map(item => { const name = item.name || 'Unknown contact'; const addresses = (item.emails || []).join(', ') || 'no address'; const fp = String(item.fingerprint || '').replace(/(.{4})/g, '$1 ').trim(); return `${name} (${addresses})\nFingerprint: ${fp}`; }).join('\n\n'); const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), { type: 'warning', buttons: ['Cancel', 'Replace key'], defaultId: 0, cancelId: 0, title: 'Confirm key replacement', message: 'A different public key already exists for this email address.', detail: `New key:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nExisting key(s):\n${detail}\n\nOnly continue if you verified the new fingerprint with the owner.`, noLink: true }); if (response !== 1) throw new Error('Key replacement cancelled.'); } const source = ['message', 'keyserver', 'paste'].includes(input?.source) ? input.source : 'import'; return pgpKeys.addContact({ armoredKey, source }); }); registerIpcHandler('pgp:set-trust', async (event, fingerprint, trust) => { const id = pgpFingerprint(fingerprint); const level = String(trust); // Raising trust changes which key outgoing mail is encrypted to, so confirm it here, outside the renderer. if (level !== 'unknown') { const contact = (await pgpKeys.listContacts()).find(item => item.fingerprint === id); if (!contact) throw new Error('That contact key was not found.'); const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), { type: 'question', buttons: ['Cancel', `Mark as ${level}`], defaultId: 0, cancelId: 0, title: 'Confirm key trust', message: `Mark this key as ${level}?`, detail: `${contact.name || ''} ${(contact.emails || []).join(', ')}\nFingerprint:\n${id.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly continue if you checked this fingerprint with the owner.` }); if (response !== 1) throw new Error('Trust change cancelled.'); } return pgpKeys.setTrust(id, level); }); registerIpcHandler('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint))); registerIpcHandler('pgp:export-contact', async (event, fingerprint) => { const id = pgpFingerprint(fingerprint); return saveKeyFile(event, `ep-mail-contact-${id.slice(-16)}.asc`, await pgpKeys.exportContact(id)); }); registerIpcHandler('pgp:get-settings', () => pgpKeys.getSettings()); registerIpcHandler('pgp:set-settings', async (_event, input) => { const settings = await pgpKeys.setSettings({ cacheMinutes: input?.cacheMinutes }); pgpCache.clear(); return settings; }); registerIpcHandler('pgp:key-servers', async () => { const settings = await pgpKeys.getSettings(); return listServers(settings.customKeyServers, settings.enabledKeyServers); }); registerIpcHandler('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 }; }); registerIpcHandler('pgp:add-key-server', async (event, input) => { const candidate = normalizeCustomServer(input); const settings = await pgpKeys.getSettings(); const customServers = settings.customKeyServers.map(normalizeCustomServer); if (customServers.length >= MAX_CUSTOM_SERVERS) throw new Error(`You can configure up to ${MAX_CUSTOM_SERVERS} custom key servers.`); if (customServers.some(server => server.url === candidate.url && server.protocol === candidate.protocol)) { throw new Error('That key server is already configured.'); } const url = new URL(candidate.url); const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), { type: 'warning', buttons: ['Cancel', 'Add server'], defaultId: 0, cancelId: 0, title: 'Add custom key server?', message: `Allow ep-mail to contact ${url.host} for OpenPGP keys?`, detail: `Protocol: ${candidate.protocol.toUpperCase()}\nEndpoint: ${candidate.url}\nThe server may learn which email addresses you search for. Only add a server you trust.`, noLink: true }); if (response !== 1) return { canceled: true }; candidate.id = randomUUID(); const updated = await pgpKeys.setSettings({ cacheMinutes: settings.cacheMinutes, customKeyServers: [...customServers, candidate] }); return { server: updated.customKeyServers[updated.customKeyServers.length - 1] }; }); registerIpcHandler('pgp:remove-key-server', async (_event, serverId) => { const id = String(serverId || ''); const settings = await pgpKeys.getSettings(); const customServers = settings.customKeyServers.filter(server => server.id !== id); if (customServers.length === settings.customKeyServers.length) throw new Error('That custom key server was not found.'); await pgpKeys.setSettings({ cacheMinutes: settings.cacheMinutes, customKeyServers, enabledKeyServers: settings.enabledKeyServers.filter(enabledId => enabledId !== id) }); return { removed: true }; }); registerIpcHandler('pgp:find-key', async (_event, input) => { const settings = await pgpKeys.getSettings(); const servers = listServers(settings.customKeyServers, settings.enabledKeyServers); return pgpKeyServers.lookupEnabled(servers, input?.email); }); registerIpcHandler('pgp:publish-key', async (event, input) => { const fingerprint = pgpFingerprint(input?.fingerprint); const settings = await pgpKeys.getSettings(); 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.'); const armoredKey = await pgpKeys.exportPublic(fingerprint); const publicKey = await openpgp.readKey({ armoredKey }); const emails = [...new Set(publicKey.getUserIDs() .map(userId => (/<([^>]+)>/.exec(userId)?.[1] || (userId.includes('@') ? userId : '')).trim().toLowerCase()) .filter(Boolean))]; if (!emails.includes(entry.email.toLowerCase())) throw new Error('The selected key no longer matches its stored email address.'); const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), { type: 'warning', buttons: ['Cancel', 'Publish public key'], defaultId: 0, cancelId: 0, title: 'Publish public key?', message: `Publish the public key for ${emails.join(', ')} to ${server.name}?`, detail: `Fingerprint:\n${fingerprint.replace(/(.{4})/g, '$1 ').trim()}\n\nOnly the public key will be sent. This exposes the email address(es) in the key to the server, which may retain them. The server may send a verification email before the key becomes searchable.`, noLink: true }); if (response !== 1) return { canceled: true }; return pgpKeyServers.publish(server, entry.email, armoredKey, fingerprint); }); registerIpcHandler('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; }); } module.exports = { pgpFailure, registerPgpIpcHandlers };