const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog, Notification, powerMonitor, Menu, Tray, nativeImage } = require('electron'); const fsSync = require('node:fs'); const path = require('node:path'); const fs = require('node:fs/promises'); const { ImapFlow } = require('imapflow'); const nodemailer = require('nodemailer'); const { simpleParser } = require('mailparser'); const { randomUUID } = require('node:crypto'); const { createDAVClient } = require('tsdav'); const ICAL = require('ical.js'); const openpgp = require('openpgp'); const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs'); const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs'); const { CUSTOM_FOLDER_PREFIX, filterMailboxMessages, isReservedFolderName, normalizeAccount, publicAccount, validFolderName } = require('./mail-model.cjs'); const { makeCalendarData, makeVcard } = require('./dav-codecs.cjs'); const { extractMailContent } = require('./mail-content.cjs'); const { createSecureJsonStore } = require('./secure-json-store.cjs'); const { createAccountStore } = require('./account-store.cjs'); const { createMailSender } = require('./mail/send-service.cjs'); const { createFolderService } = require('./mail/folders.cjs'); const { createMailReader } = require('./mail/read-service.cjs'); const { createMessageActionService } = require('./mail/action-service.cjs'); const { createMailOutboxService } = require('./mail/outbox-service.cjs'); const { createAttachmentService } = require('./mail/attachment-service.cjs'); const { createMailboxSyncService } = require('./mail/sync-service.cjs'); const { createBackgroundSyncCoordinator } = require('./mail/sync-coordinator.cjs'); const { createIdleWatcherManager } = require('./mail/idle-watcher-manager.cjs'); const { createSnoozeReminderService } = require('./mail/snooze-reminder-service.cjs'); const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('./security/ipc-sender.cjs'); const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc'); const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc'); const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc'); const accountJsonStore = createSecureJsonStore({ getFilePath: credentialsPath, safeStorage, assertSecureStorage, unavailableMessage: 'Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.' }); const accountRepository = createAccountStore(accountJsonStore); const davJsonStore = createSecureJsonStore({ getFilePath: davCredentialsPath, safeStorage, assertSecureStorage, unavailableMessage: 'Secure credential storage is unavailable.' }); const pgpJsonStore = createSecureJsonStore({ getFilePath: pgpKeysPath, safeStorage, assertSecureStorage, unavailableMessage: 'Secure key storage is unavailable.' }); const backgroundSyncIntervalMs = 30 * 1000; const backgroundRetryIntervalMs = 2 * 60 * 1000; const backgroundSyncConcurrency = 2; const backgroundIdleConcurrency = 2; const snoozeCheckIntervalMs = 30 * 1000; const windowsAppUserModelId = 'studio.daybreak.mail'; const applicationHtmlPath = path.join(__dirname, '..', 'index.html'); const ipcMainHandle = ipcMain.handle.bind(ipcMain); let accountStoreQueue = Promise.resolve(); const backgroundSyncGenerations = new Map(); const backgroundSyncFailures = new Map(); const flagSnapshots = new Map(); const lastBackgroundSyncAt = new Map(); let windowsAppIcon = null; let tray = null; function registerIpcHandler(channel, handler) { return ipcMainHandle(channel, (event, ...args) => { assertTrustedIpcSender(event, applicationHtmlPath); return handler(event, ...args); }); } function updateAccountStore(update) { const operation = accountStoreQueue.then(async () => { const store = (await readAccountStore()) || { accounts: [], activeId: null }; const result = await update(store); if (store.accounts.length) await saveAccountStore(store); else await fs.rm(credentialsPath(), { force: true }); return result; }); accountStoreQueue = operation.catch(() => {}); return operation; } function sendMailSyncUpdate(update) { for (const window of BrowserWindow.getAllWindows()) { if (!window.isDestroyed() && !window.webContents.isDestroyed()) { window.webContents.send('mail:sync-update', update); } } } const { checkSnoozeReminders } = createSnoozeReminderService({ readAccountStore, updateAccountStore, showNotification(reminder) { if (reminder.notificationsEnabled !== false && Notification.isSupported()) { new Notification({ title: 'Mail reminder', body: `${reminder.subject || 'A message'}${reminder.email ? ` ยท ${reminder.email}` : ''}` }).show(); } }, sendMailSyncUpdate }); const { createKeyStore } = require('./pgp-keystore.cjs'); const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs'); const pgpKeys = createKeyStore({ async load() { try { return await pgpJsonStore.load(); } catch (error) { if (error.code === 'ENOENT') return { keys: [] }; throw error; } }, save(data) { return pgpJsonStore.save(data); } }); const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes); const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache }); const pgpKeyServers = createKeyServerService(); const { findSpecialMailbox, findSentMailbox, listCustomFolders, folderPath } = createFolderService({ customFolderPrefix: CUSTOM_FOLDER_PREFIX, isReservedFolderName }); async function readDavStore() { try { return await davJsonStore.load(); } catch (error) { if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null }; throw error; } } async function saveDavStore(store) { return davJsonStore.save(store); } function davPublicConfig(config) { return { id: config.id, serverUrl: config.serverUrl, username: config.username, collections: config.collections || [] }; } async function openDavClient(config, type) { return createDAVClient({ serverUrl: config.serverUrl, credentials: { username: config.username, password: config.password }, authMethod: 'Basic', defaultAccountType: type }); } function activeDavConfig(store, type, id = null) { const key = type === 'caldav' ? 'caldav' : 'carddav'; const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId'; return store[key].find(item => item.id === (id || store[activeKey])) || null; } function imapClient(account, options = {}) { return new ImapFlow({ host: account.imapHost, port: account.imapPort, secure: false, doSTARTTLS: true, auth: { user: account.email, pass: account.password }, tls: { rejectUnauthorized: true }, logger: false, connectionTimeout: 15000, greetingTimeout: 10000, socketTimeout: 20000, ...options }); } function smtpTransport(account) { return nodemailer.createTransport({ host: account.smtpHost, port: account.smtpPort, secure: false, requireTLS: true, auth: { user: account.email, pass: account.password }, tls: { rejectUnauthorized: true, servername: account.smtpHost }, connectionTimeout: 15000, greetingTimeout: 10000, socketTimeout: 20000 }); } function assertSecureStorage() { if (process.platform === 'linux' && typeof safeStorage.getSelectedStorageBackend === 'function') { const backend = safeStorage.getSelectedStorageBackend(); if (backend === 'basic_text') { throw new Error('This Linux session is using the insecure basic_text password backend. Configure a secure secret store such as gnome-libsecret or kwallet before saving mail credentials or OpenPGP keys.'); } } if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.'); } async function readAccountStore() { return accountRepository.load(); } async function saveAccountStore(store) { return accountRepository.save(store); } async function readAccount(accountId = null) { const store = await readAccountStore(); if (!store?.accounts.length) return null; return store.accounts.find(account => account.id === (accountId || store.activeId)) || null; } async function saveAccount(account) { return updateAccountStore(store => { const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase()); const saved = { ...existing, ...account, id: existing?.id || randomUUID() }; store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved]; store.activeId = saved.id; return saved; }); } async function connectMail(account) { const client = imapClient(account); let transport; try { await client.connect(); const mailbox = await client.mailboxOpen('INBOX', { readOnly: true }); transport = smtpTransport(account); await transport.verify(); return { mailbox: mailbox.name, messages: mailbox.exists }; } finally { if (transport) transport.close(); if (client.usable) await client.logout().catch(() => {}); } } async function cacheMailboxMessages(accountId, folder, messages) { if (!messages.length) return; await updateAccountStore(store => { const account = store.accounts.find(item => item.id === accountId); if (!account) return; account.mailCache = account.mailCache || {}; const previous = account.mailCache[folder] || []; const merged = new Map(previous.map(message => [String(message.uid || message.id), message])); for (const message of messages) merged.set(String(message.uid || message.id), message); account.mailCache[folder] = [...merged.values()].slice(-50); }); } function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) { const all = filterMailboxMessages(account.mailCache?.[folder] || [], filters) .sort((a, b) => Number(b.timestamp || 0) - Number(a.timestamp || 0)); const start = Math.max(0, Number(offset) || 0); const messages = all.slice(start, start + limit); return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true }; } async function toUiMessage(item, folder) { const parsed = await simpleParser(item.source); const sender = parsed.from?.value?.[0]; const pgpKind = pgpMail.detect(parsed); const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline'; const content = encrypted ? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' } : extractMailContent(parsed); const { bodyText, body, links } = content; const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null; const date = parsed.date || item.internalDate || new Date(); return { id: Number(item.uid), initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(), color: '#dce6df', sender: sender?.name || sender?.address || 'Unknown sender', email: sender?.address || '', subject: parsed.subject || '(no subject)', snippet: encrypted ? 'Encrypted message' : (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180), encrypted, pgpSignatures, time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date), date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date), timestamp: date.getTime(), unread: !item.flags?.has('\\Seen'), star: item.flags?.has('\\Flagged') || false, tags: [folder], sent: folder === 'Sent', archived: folder === 'Archive', deleted: folder === 'Trash', sourceFolder: folder, body, html: content.html, links, uid: Number(item.uid), attachments: content.attachments, attachment: content.attachment, size: content.size }; } async function fetchSnoozedMailbox(account, offset, limit) { const now = Date.now(); const pending = (account.snoozedMessages || []) .filter(item => Number(item.dueAt) > now) .sort((first, second) => Number(first.dueAt) - Number(second.dueAt)); const selected = pending.slice(Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + Math.max(1, Math.min(50, Number(limit) || 20))); const client = imapClient(account); const messages = []; try { await client.connect(); for (const snooze of selected) { const sourceFolder = String(snooze.folder || 'Inbox'); const mailboxPath = await folderPath(client, sourceFolder); if (!mailboxPath) continue; const lock = await client.getMailboxLock(mailboxPath); try { const item = await client.fetchOne(Number(snooze.uid), { uid: true, envelope: true, flags: true, internalDate: true, source: true }, { uid: true }); if (!item?.source) continue; const message = await toUiMessage(item, 'Snoozed'); message.tags.push(...(account.ruleLabels?.[`${sourceFolder}:${item.uid}`] || [])); messages.push({ ...message, sourceFolder, snoozedUntil: Number(snooze.dueAt) }); } finally { lock.release(); } } } finally { if (client.usable) await client.logout().catch(() => {}); } return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' }; } const { fetchMailbox } = createMailReader({ imapClient, folderPath, toUiMessage, cacheMailboxMessages, fetchSnoozedMailbox, filterMailboxMessages }); const { applyMessageAction } = createMessageActionService({ imapClient, folderPath, findSpecialMailbox, updateAccountStore }); async function saveAccountSyncState(accountId, generation, folders) { return updateAccountStore(store => { const account = store.accounts.find(item => item.id === accountId); if (!account || backgroundSyncGenerations.get(accountId) !== generation) return false; account.syncState = account.syncState || { folders: {} }; account.syncState.folders = folders; return true; }); } function showNewMailNotification(account, count) { if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return; const focused = BrowserWindow.getAllWindows().some(window => window.isFocused()); if (focused) return; const notification = new Notification({ title: count === 1 ? 'New mail' : `${count} new messages`, body: account.email }); notification.show(); } registerIpcHandler('app:get-version', () => app.getVersion()); registerIpcHandler('mail:get-account', async () => { const account = await readAccount(); return account ? publicAccount(account) : null; }); registerIpcHandler('mail:list-accounts', async () => { const store = (await readAccountStore()) || { accounts: [], activeId: null }; return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; }); registerIpcHandler('mail:select-account', async (_event, accountId) => { const account = await updateAccountStore(store => { const selected = store.accounts.find(item => item.id === accountId); if (!selected) throw new Error('That mail account is no longer available.'); store.activeId = selected.id; return selected; }); requestBackgroundSync(); return publicAccount(account); }); registerIpcHandler('mail:remove-account', async (_event, accountId) => { const result = await updateAccountStore(store => { store.accounts = store.accounts.filter(account => account.id !== accountId); if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null; return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; }); requestBackgroundSync(accountId); requestBackgroundSync(); return result; }); registerIpcHandler('mail:update-account', async (_event, accountId, input) => { const existing = await readAccount(accountId); if (!existing) throw new Error('That mail account is no longer available.'); const account = normalizeAccount({ ...existing, ...input, password: String(input?.password || '') || existing.password }); account.id = existing.id; try { const status = await connectMail(account); const savedAccount = await updateAccountStore(store => { const current = store.accounts.find(item => item.id === existing.id); if (!current) throw new Error('That mail account is no longer available.'); const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost; store.accounts = store.accounts.map(item => item.id === existing.id ? { ...account, syncState: endpointChanged ? undefined : current.syncState, snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []), ruleLabels: endpointChanged ? {} : (current.ruleLabels || {}) } : item); return store.accounts.find(item => item.id === existing.id); }); requestBackgroundSync(existing.id); return { ...publicAccount(savedAccount), ...status }; } catch (error) { throw new Error(`Could not update the mailbox: ${error.message}`); } }); registerIpcHandler('mail:connect', async (_event, input) => { const account = normalizeAccount(input); try { const status = await connectMail(account); const saved = await saveAccount(account); requestBackgroundSync(saved.id); return { ok: true, ...publicAccount(saved), ...status }; } catch (error) { throw new Error(`Could not connect to the mailbox: ${error.message}`); } }); registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before syncing.'); const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']); const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder; const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX) ? selectedFolder : 'Inbox'; const { folder: _filterFolder, ...criteria } = filters; try { await flushMailOutbox(account); return await fetchMailbox(account, folder, offset, 20, criteria); } catch (error) { if (!isConnectivityFailure(error)) throw error; const cached = cachedMailbox(account, folder, offset, 20, criteria); if (!cached.total) throw error; return cached; } }); registerIpcHandler('mail:list-folders', async () => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before listing folders.'); const client = imapClient(account); try { await client.connect(); return { folders: await listCustomFolders(client) }; } catch (error) { if (isConnectivityFailure(error)) return { folders: [], offline: true }; throw error; } finally { if (client.usable) await client.logout().catch(() => {}); } }); registerIpcHandler('mail:create-folder', async (_event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before creating folders.'); const name = validFolderName(input?.name); const client = imapClient(account); try { await client.connect(); const existing = await client.list(); if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) { throw new Error('A folder with that name already exists.'); } const created = await client.mailboxCreate(name); await client.mailboxSubscribe(created.path).catch(() => {}); return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) }; } catch (error) { if (error.message === 'A folder with that name already exists.') throw error; throw new Error(`Could not create the folder: ${error.message}`); } finally { if (client.usable) await client.logout().catch(() => {}); } }); registerIpcHandler('mail:list-drafts', async () => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before opening drafts.'); return { drafts: account.drafts || [], offline: true }; }); registerIpcHandler('mail:save-draft', async (_event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before saving drafts.'); const draft = { id: String(input?.id || randomUUID()), to: String(input?.to || '').slice(0, 4000), cc: String(input?.cc || '').slice(0, 4000), subject: String(input?.subject || '').slice(0, 998), text: String(input?.text || '').slice(0, 500000), attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)), updatedAt: Date.now() }; await updateAccountStore(store => { const saved = store.accounts.find(item => item.id === account.id); if (!saved) throw new Error('That mail account is no longer available.'); const drafts = saved.drafts || []; saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500); }); return draft; }); registerIpcHandler('mail:delete-draft', async (_event, id) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before deleting drafts.'); await updateAccountStore(store => { const saved = store.accounts.find(item => item.id === account.id); if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id); }); return { ok: true }; }); registerIpcHandler('mail:set-snooze', async (_event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before setting a reminder.'); const uid = Number(input?.uid); const folder = String(input?.sourceFolder || input?.folder || 'Inbox'); if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.'); const dueAt = input?.dueAt == null ? null : Number(input.dueAt); if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) { throw new Error('Choose a reminder time in the future.'); } await updateAccountStore(store => { const saved = store.accounts.find(item => item.id === account.id); if (!saved) throw new Error('That mail account is no longer available.'); const snoozes = saved.snoozedMessages || []; const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder)); if (dueAt != null) { remaining.push({ uid, folder, dueAt, subject: String(input.subject || '').slice(0, 200) }); } saved.snoozedMessages = remaining; }); sendMailSyncUpdate({ accountId: account.id, foldersChanged: ['Snoozed', folder] }); return { ok: true, snoozed: dueAt != null }; }); function isConnectivityFailure(error) { const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']); for (let current = error; current; current = current.cause) { if (networkCodes.has(current.code)) return true; if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true; } return false; } registerIpcHandler('mail:update-message', async (_event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before changing messages.'); try { return await applyMessageAction(account, input); } catch (error) { if (!isConnectivityFailure(error)) throw error; return mailOutbox.queueMessageAction(account, input); } }); // Encrypted messages keep their attachments inside the encrypted payload. async function parseForAttachments(source) { const parsed = await simpleParser(source); const kind = pgpMail.detect(parsed); if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed; try { return (await pgpMail.decrypt(parsed)).parsed; } catch (error) { if (error instanceof PgpError) throw new Error(error.code === 'PASSPHRASE_REQUIRED' ? 'Open the message and unlock it before using its attachments.' : error.message); throw error; } } const attachmentService = createAttachmentService({ imapClient, folderPath, parseForAttachments }); registerIpcHandler('mail:save-attachment', async (event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before downloading attachments.'); const parent = BrowserWindow.fromWebContents(event.sender); return attachmentService.saveAttachment(account, input, options => dialog.showSaveDialog(parent, options)); }); registerIpcHandler('mail:preview-attachment', async (_event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before previewing attachments.'); return attachmentService.previewAttachment(account, input); }); 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 }) }; }); 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: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; }); async function fetchMessageSource(account, folder, uid) { if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); const client = 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(() => {}); } } const pgpFailure = error => ({ failed: true, code: error.code, message: error.message, fingerprint: error.details?.fingerprint || null, email: error.details?.email || null, missing: error.details?.missing || [] }); 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 }; }); registerIpcHandler('mail:open-external', async (event, rawUrl) => { let target; try { target = new URL(String(rawUrl || '')); } catch { throw new Error('This link is not a valid web address.'); } if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) { throw new Error('Only standard web links can be opened from mail.'); } const parent = BrowserWindow.fromWebContents(event.sender); const confirmation = await dialog.showMessageBox(parent, { type: 'warning', title: 'Open external link?', message: 'Email links can lead to fake sign-in pages or harmful content.', detail: `Check the full address before continuing:\n${target.href}`, buttons: ['Cancel', 'Open link'], defaultId: 0, cancelId: 0, noLink: true }); if (confirmation.response !== 1) return { opened: false }; await shell.openExternal(target.href); return { opened: true }; }); registerIpcHandler('mail:sync-inbox', async () => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before syncing.'); return fetchMailbox(account, 'Inbox'); }); const { sendMailNow } = createMailSender({ smtpTransport, imapClient, findSentMailbox }); const mailOutbox = createMailOutboxService({ sendMailNow, applyMessageAction, updateAccountStore, isConnectivityFailure }); const flushMailOutbox = account => mailOutbox.flushMailOutbox(account); const { syncAccountMailboxes } = createMailboxSyncService({ imapClient, flushMailOutbox, updateAccountStore, saveAccountSyncState, backgroundSyncGenerations, flagSnapshots, findSpecialMailbox, folderPath }); const idleWatcherManager = createIdleWatcherManager({ readAccountStore, readAccount, imapClient, backgroundSyncGenerations, concurrency: backgroundIdleConcurrency }); const { reconcileIdleWatchers } = idleWatcherManager; const { requestBackgroundSync, runBackgroundSync } = createBackgroundSyncCoordinator({ readAccountStore, syncAccountMailboxes, backgroundSyncGenerations, backgroundSyncFailures, lastBackgroundSyncAt, flagSnapshots, reconcileIdleWatchers, sendMailSyncUpdate, showNewMailNotification, concurrency: backgroundSyncConcurrency, retryIntervalMs: backgroundRetryIntervalMs }); idleWatcherManager.setRequestBackgroundSync(requestBackgroundSync); registerIpcHandler('mail:send', async (event, message) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before sending.'); const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null; const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` }; const attachments = normalizeOutgoingAttachments(message?.attachments); queuedMessage.attachments = serializeOutgoingAttachments(attachments); delete queuedMessage.pgp; if (!pgpOptions?.encrypt) { const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean); const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email }); if (status.recipients.length && !status.missing.length) { const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), { type: 'warning', buttons: ['Cancel', 'Send anyway'], defaultId: 0, cancelId: 0, title: 'Send without encryption?', message: 'Public keys are available for all recipients.', detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.', noLink: true }); if (response !== 1) throw new Error('Plaintext send cancelled.'); } } if (pgpOptions) { // Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox. const signature = String(account.signature || '').slice(0, 5000); const body = String(queuedMessage.text || '').slice(0, 500000); const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email; try { const built = await pgpMail.build({ from: { name: fromName, address: account.email }, to: queuedMessage.to, cc: queuedMessage.cc, subject: String(queuedMessage.subject || '(no subject)').slice(0, 998), text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, messageId: queuedMessage.messageId, encrypt: Boolean(pgpOptions.encrypt), sign: Boolean(pgpOptions.sign), passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null, attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content })) }); queuedMessage.rawBase64 = built.raw.toString('base64'); queuedMessage.envelope = built.envelope; queuedMessage.text = ''; queuedMessage.attachments = []; } catch (error) { if (error instanceof PgpError) return pgpFailure(error); throw error; } } try { return await sendMailNow(account, queuedMessage); } catch (error) { if (!isConnectivityFailure(error)) throw error; await updateAccountStore(store => { const saved = store.accounts.find(item => item.id === account.id); if (!saved) throw new Error('That mail account is no longer available.'); saved.mailOutbox = saved.mailOutbox || []; saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() }); }); return { ok: true, queued: true }; } }); registerIpcHandler('mail:disconnect', async (_event, accountId) => { const store = await readAccountStore(); if (!store) return { accounts: [], activeId: null }; if (accountId) { store.accounts = store.accounts.filter(account => account.id !== accountId); } else { store.accounts = []; } if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true }); else { if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id; await saveAccountStore(store); } return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; }); registerIpcHandler('dav:list', async () => { const store = await readDavStore(); return { caldav: store.caldav.map(davPublicConfig), carddav: store.carddav.map(davPublicConfig), activeCaldavId: store.activeCaldavId, activeCarddavId: store.activeCarddavId }; }); registerIpcHandler('dav:connect', async (_event, input) => { const type = input?.type === 'carddav' ? 'carddav' : 'caldav'; const serverUrl = String(input?.serverUrl || '').trim(); const username = String(input?.username || '').trim(); const password = String(input?.password || ''); let parsedUrl; try { parsedUrl = new URL(serverUrl); } catch { throw new Error('Enter a valid CalDAV or CardDAV server URL.'); } if (!['https:', 'http:'].includes(parsedUrl.protocol) || (parsedUrl.protocol === 'http:' && !['localhost','127.0.0.1','::1'].includes(parsedUrl.hostname))) throw new Error('DAV server URLs must use HTTPS.'); if (!username || !password) throw new Error('Enter the DAV username and password.'); const config = { id: randomUUID(), type, serverUrl: parsedUrl.href, username, password }; const client = await openDavClient(config, type); const collections = type === 'caldav' ? await client.fetchCalendars() : await client.fetchAddressBooks(); if (!collections.length) throw new Error(`No ${type === 'caldav' ? 'calendars' : 'address books'} were found on this server.`); config.collections = collections.map(collection => ({ url: collection.url, name: typeof collection.displayName === 'string' ? collection.displayName : collection.url })); const store = await readDavStore(); const key = type; const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId'; const duplicate = store[key].find(account => account.serverUrl === config.serverUrl && account.username.toLowerCase() === username.toLowerCase()); if (duplicate) config.id = duplicate.id; store[key] = [...store[key].filter(account => account.id !== config.id), config]; store[activeKey] = config.id; await saveDavStore(store); return { config: davPublicConfig(config), collections: config.collections, accounts: { caldav: store.caldav.map(davPublicConfig), carddav: store.carddav.map(davPublicConfig), activeCaldavId: store.activeCaldavId, activeCarddavId: store.activeCarddavId } }; }); registerIpcHandler('dav:activate', async (_event, input) => { const type = input?.type === 'carddav' ? 'carddav' : 'caldav'; const store = await readDavStore(); const config = store[type].find(item => item.id === input?.id); if (!config) throw new Error('That DAV account could not be found.'); store[type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId'] = config.id; await saveDavStore(store); return { id: config.id }; }); registerIpcHandler('dav:remove', async (_event, input) => { const type = input?.type === 'carddav' ? 'carddav' : 'caldav'; const store = await readDavStore(); store[type] = store[type].filter(item => item.id !== input?.id); const activeKey = type === 'caldav' ? 'activeCaldavId' : 'activeCarddavId'; if (store[activeKey] === input?.id) store[activeKey] = store[type][0]?.id || null; await saveDavStore(store); return { accounts: store[type].map(davPublicConfig), activeId: store[activeKey] }; }); registerIpcHandler('dav:sync', async (_event, requestedType) => { const type = requestedType === 'carddav' ? 'carddav' : 'caldav'; const store = await readDavStore(); const config = activeDavConfig(store, type); if (!config) throw new Error(`Connect a ${type === 'caldav' ? 'CalDAV' : 'CardDAV'} server first.`); const client = await openDavClient(config, type); if (type === 'caldav') { const calendars = await client.fetchCalendars(); const result = []; for (const calendar of calendars) { const objects = await client.fetchCalendarObjects({ calendar }); for (const object of objects) { if (!object.data) continue; try { const component = new ICAL.Component(ICAL.parse(object.data)); for (const part of component.getAllSubcomponents('vevent')) { const parsed = new ICAL.Event(part); if (!parsed.startDate) continue; const start = parsed.startDate.toJSDate(); result.push({ id: `dav:${config.id}:${encodeURIComponent(object.url)}:${encodeURIComponent(parsed.uid)}`, title: parsed.summary || '(no title)', date: `${start.getFullYear()}-${String(start.getMonth()+1).padStart(2,'0')}-${String(start.getDate()).padStart(2,'0')}`, time: parsed.startDate.isDate ? '' : `${String(start.getHours()).padStart(2,'0')}:${String(start.getMinutes()).padStart(2,'0')}`, with: part.getAllProperties('attendee').map(property => String(property.getFirstValue() || '').replace(/^mailto:/i, '')).join(', '), place: parsed.location || '', notes: parsed.description || '', _dav: { accountId: config.id, collectionUrl: calendar.url, objectUrl: object.url, etag: object.etag, uid: parsed.uid } }); } } catch {} } } return { items: result, account: davPublicConfig(config) }; } const books = await client.fetchAddressBooks(); const result = []; for (const book of books) { const cards = await client.fetchVCards({ addressBook: book }); for (const card of cards) { if (!card.data) continue; try { const parsed = new ICAL.Component(ICAL.parse(card.data)); const name = String(parsed.getFirstPropertyValue('fn') || '').trim(); if (!name) continue; const emails = parsed.getAllProperties('email').map(property => String(property.getFirstValue() || '')); const uid = String(parsed.getFirstPropertyValue('uid') || ''); result.push({ id: `dav:${config.id}:${encodeURIComponent(card.url)}:${encodeURIComponent(uid)}`, name, email: emails[0] || '', note: String(parsed.getFirstPropertyValue('note') || ''), initials: name.split(/\s+/).map(part => part[0]).join('').slice(0,2).toUpperCase(), color: '#dce9dd', _dav: { accountId: config.id, collectionUrl: book.url, objectUrl: card.url, etag: card.etag, uid } }); } catch {} } } return { items: result, account: davPublicConfig(config) }; }); registerIpcHandler('dav:save-event', async (_event, input) => { const store = await readDavStore(); const remote = input?._dav; const config = activeDavConfig(store, 'caldav', remote?.accountId); if (!config) return null; const client = await openDavClient(config, 'caldav'); const calendars = await client.fetchCalendars(); const calendar = calendars.find(item => item.url === remote?.collectionUrl) || calendars[0]; if (!calendar) throw new Error('No writable calendar was found.'); const uid = remote?.uid || randomUUID(); const data = makeCalendarData({ ...input, _dav: { ...remote, uid } }); if (remote?.objectUrl) { const response = await client.updateCalendarObject({ calendarObject: { url: remote.objectUrl, data, etag: remote.etag } }); return { accountId: config.id, collectionUrl: calendar.url, objectUrl: remote.objectUrl, etag: response.headers.get('etag') || remote.etag, uid }; } const filename = `${uid}.ics`; const response = await client.createCalendarObject({ calendar, iCalString: data.replace(`UID:${uid}`, `UID:${uid}`), filename }); return { accountId: config.id, collectionUrl: calendar.url, objectUrl: new URL(filename, calendar.url.endsWith('/')?calendar.url:`${calendar.url}/`).href, etag: response.headers.get('etag'), uid }; }); registerIpcHandler('dav:delete-event', async (_event, remote) => { const store = await readDavStore(); const config = activeDavConfig(store, 'caldav', remote?.accountId); if (!config || !remote?.objectUrl) return; const client = await openDavClient(config, 'caldav'); await client.deleteCalendarObject({ calendarObject: { url: remote.objectUrl, etag: remote.etag } }); }); registerIpcHandler('dav:save-contact', async (_event, input) => { const store = await readDavStore(); const remote = input?._dav; const config = activeDavConfig(store, 'carddav', remote?.accountId); if (!config) return null; const client = await openDavClient(config, 'carddav'); const books = await client.fetchAddressBooks(); const book = books.find(item => item.url === remote?.collectionUrl) || books[0]; if (!book) throw new Error('No writable address book was found.'); const uid = remote?.uid || randomUUID(); const data = makeVcard({ ...input, _dav: { ...remote, uid } }); if (remote?.objectUrl) { const response = await client.updateVCard({ vCard: { url: remote.objectUrl, data, etag: remote.etag } }); return { accountId: config.id, collectionUrl: book.url, objectUrl: remote.objectUrl, etag: response.headers.get('etag') || remote.etag, uid }; } const filename = `${uid}.vcf`; const response = await client.createVCard({ addressBook: book, vCardString: data, filename }); return { accountId: config.id, collectionUrl: book.url, objectUrl: new URL(filename, book.url.endsWith('/')?book.url:`${book.url}/`).href, etag: response.headers.get('etag'), uid }; }); registerIpcHandler('dav:delete-contact', async (_event, remote) => { const store = await readDavStore(); const config = activeDavConfig(store, 'carddav', remote?.accountId); if (!config || !remote?.objectUrl) return; const client = await openDavClient(config, 'carddav'); await client.deleteVCard({ vCard: { url: remote.objectUrl, etag: remote.etag } }); }); function createWindow() { const window = new BrowserWindow({ width: 1440, height: 920, minWidth: 920, minHeight: 680, title: `ep-mail v${app.getVersion()}`, backgroundColor: '#f4f5f1', show: false, autoHideMenuBar: true, icon: windowsAppIcon || path.join(__dirname, '..', 'icon.svg'), webPreferences: { preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true } }); window.once('ready-to-show', () => window.show()); window.loadFile(path.join(__dirname, '..', 'index.html')); window.webContents.setWindowOpenHandler(() => { return { action: 'deny' }; }); window.webContents.on('will-navigate', (event, url) => { if (!isTrustedApplicationUrl(url, applicationHtmlPath)) event.preventDefault(); }); return window; } function showMainWindow() { let window = BrowserWindow.getAllWindows().find(item => !item.isDestroyed()); if (!window) { window = createWindow(); } else { if (window.isMinimized()) window.restore(); window.show(); window.focus(); } } function createWindowsTray() { tray = new Tray(windowsAppIcon.resize({ width: 16, height: 16 })); tray.setToolTip('ep-mail'); tray.setContextMenu(Menu.buildFromTemplate([ { label: 'Open ep-mail', click: showMainWindow }, { type: 'separator' }, { label: 'Quit ep-mail', click: () => app.quit() } ])); tray.on('click', showMainWindow); tray.on('double-click', showMainWindow); } function repairWindowsStartMenuShortcut() { if (!app.isPackaged) return; const shortcutPath = path.join( app.getPath('appData'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'ep-mail.lnk' ); if (!fsSync.existsSync(shortcutPath)) return; try { const shortcut = shell.readShortcutLink(shortcutPath); const isEpMailShortcut = path.basename(shortcut.target).toLowerCase() === 'ep-mail.exe' || shortcut.appUserModelId === windowsAppUserModelId; if (!isEpMailShortcut) return; if (shortcut.appUserModelId && shortcut.appUserModelId !== windowsAppUserModelId) return; const portableExecutable = process.env.PORTABLE_EXECUTABLE_FILE; const executable = portableExecutable && fsSync.existsSync(portableExecutable) ? portableExecutable : process.execPath; const updated = shell.writeShortcutLink(shortcutPath, 'update', { ...shortcut, target: executable, cwd: path.dirname(executable), icon: executable, iconIndex: 0, appUserModelId: windowsAppUserModelId }); if (!updated) throw new Error('Windows did not update the shortcut.'); } catch (error) { console.error('Could not repair the ep-mail Start Menu shortcut:', error); } } app.whenReady().then(() => { app.setAppUserModelId(windowsAppUserModelId); if (process.platform === 'win32') { windowsAppIcon = nativeImage.createFromPath(path.join(__dirname, '..', 'icon.ico')); if (windowsAppIcon.isEmpty()) throw new Error('Could not load the Windows application icon.'); repairWindowsStartMenuShortcut(); createWindowsTray(); } createWindow(); const syncTimer = setInterval(() => { void runBackgroundSync(true).catch(error => console.error('Periodic mail sync failed:', error)); }, backgroundSyncIntervalMs); syncTimer.unref(); const snoozeTimer = setInterval(() => void checkSnoozeReminders(), snoozeCheckIntervalMs); snoozeTimer.unref(); void checkSnoozeReminders(); requestBackgroundSync(); powerMonitor.on('suspend', () => { idleWatcherManager.stopAll(); }); powerMonitor.on('resume', () => requestBackgroundSync(null, true)); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); }); app.on('before-quit', () => { idleWatcherManager.stopAll(); });