require('v8-compile-cache'); const startupTraceEnabled = process.env.EP_MAIL_STARTUP_TRACE === '1'; const startupTraceStartedAt = process.hrtime.bigint(); function traceStartup(message) { if (!startupTraceEnabled) return; const elapsed = Number(process.hrtime.bigint() - startupTraceStartedAt) / 1e6; console.info(`[ep-mail startup +${elapsed.toFixed(1)}ms] ${message}`); } traceStartup('main process entered'); 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 { randomUUID } = require('node:crypto'); let tsdavPromise = null; function getTsdav() { if (!tsdavPromise) tsdavPromise = import('tsdav'); return tsdavPromise; } let icalPromise = null; function getICAL() { if (!icalPromise) icalPromise = import('ical.js'); return icalPromise; } let openpgpPromise = null; function getOpenPGP() { if (!openpgpPromise) openpgpPromise = import('openpgp'); return openpgpPromise; } let imapFlowPromise = null; function getImapFlow() { if (!imapFlowPromise) imapFlowPromise = import('imapflow'); return imapFlowPromise; } let nodemailerPromise = null; function getNodemailer() { if (!nodemailerPromise) nodemailerPromise = import('nodemailer'); return nodemailerPromise; } let mailparserPromise = null; function getMailparser() { if (!mailparserPromise) mailparserPromise = import('mailparser'); return mailparserPromise; } 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 { 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 { createOAuth2Service, loadOAuthProviderConfig } = require('./mail/oauth2-service.cjs'); const { createOAuthTokenManager } = require('./mail/oauth-token-manager.cjs'); const { createMailConnections } = require('./mail/connection-factory.cjs'); const { isConnectivityFailure } = require('./mail/connectivity.cjs'); const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('./security/ipc-sender.cjs'); const { validateIpcArguments } = require('./security/ipc-arguments.cjs'); const { assertDavObjectReference } = require('./dav/remote-reference.cjs'); const { pgpFailure, registerPgpIpcHandlers } = require('./ipc/pgp.cjs'); const { registerDavIpcHandlers } = require('./ipc/dav.cjs'); const { registerMailIpcHandlers } = require('./ipc/mail.cjs'); traceStartup('all requires complete'); 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, async (event, ...args) => { const startedAt = startupTraceEnabled ? process.hrtime.bigint() : null; try { assertTrustedIpcSender(event, applicationHtmlPath); validateIpcArguments(channel, args); return await handler(event, ...args); } finally { if (startedAt) { const elapsed = Number(process.hrtime.bigint() - startedAt) / 1e6; traceStartup(`${channel} IPC completed in ${elapsed.toFixed(1)}ms`); } } }); } 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; } const oauth2Service = createOAuth2Service({ providers: loadOAuthProviderConfig(), openExternal: url => shell.openExternal(url) }); const oauthTokenManager = createOAuthTokenManager({ oauth2Service, async persistTokens(accountId, tokens) { if (!accountId) return; await updateAccountStore(store => { const account = store.accounts.find(item => item.id === accountId); if (account?.authMethod === 'oauth2') Object.assign(account, tokens); }); } }); async function authorizeOAuthAccount(account) { return { ...account, ...await oauth2Service.authorize(account.oauthProvider, account.email) }; } function listOAuthProviders() { return oauth2Service.listProviders(); } 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) { const { createDAVClient } = await getTsdav(); 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; } const { imapClient, smtpTransport } = createMailConnections({ getImapFlow, getNodemailer, oauthTokenManager }); 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 = await imapClient(account); let transport; try { await client.connect(); const mailbox = await client.mailboxOpen('INBOX', { readOnly: true }); transport = await 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 { simpleParser } = await getMailparser(); 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 = await 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()); registerPgpIpcHandlers({ registerIpcHandler, BrowserWindow, dialog, fs, getOpenPGP, pgpKeys, pgpCache, pgpMail, PgpError, pgpKeyServers, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer, randomUUID, readAccount, imapClient, folderPath, getMailparser, extractMailContent }); 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); registerMailIpcHandlers({ registerIpcHandler, BrowserWindow, dialog, shell, fs, credentialsPath, readAccount, readAccountStore, saveAccountStore, updateAccountStore, saveAccount, publicAccount, normalizeAccount, connectMail, authorizeOAuthAccount, listOAuthProviders, requestBackgroundSync, CUSTOM_FOLDER_PREFIX, flushMailOutbox, fetchMailbox, cachedMailbox, listCustomFolders, imapClient, validFolderName, isConnectivityFailure, randomUUID, serializeOutgoingAttachments, normalizeOutgoingAttachments, sendMailSyncUpdate, applyMessageAction, mailOutbox, pgpMail, PgpError, getMailparser, folderPath, sendMailNow, pgpFailure }); registerDavIpcHandlers({ registerIpcHandler, readDavStore, saveDavStore, davPublicConfig, openDavClient, activeDavConfig, getICAL, makeCalendarData, makeVcard, randomUUID, assertDavObjectReference }); traceStartup('main services and IPC handlers initialized'); function createWindow() { traceStartup('creating BrowserWindow'); 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.webContents.on('dom-ready', () => traceStartup('renderer DOM ready')); window.webContents.on('did-finish-load', () => traceStartup('renderer load complete')); window.once('ready-to-show', () => { traceStartup('BrowserWindow ready-to-show'); window.show(); }); window.loadFile(path.join(__dirname, '..', 'index.html')).catch(error => { traceStartup(`loadFile failed: ${error.message}`); console.error('Could not load the application window:', error); }); 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(() => { traceStartup('Electron app.whenReady'); 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.'); } const mainWindow = createWindow(); mainWindow.once('ready-to-show', () => { if (process.platform === 'win32') { repairWindowsStartMenuShortcut(); createWindowsTray(); } void checkSnoozeReminders(); const startupSyncTimer = setTimeout(() => requestBackgroundSync(), 3000); startupSyncTimer.unref(); traceStartup('post-first-frame work started; background sync scheduled'); }); 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(); 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(); });