956 lines
36 KiB
JavaScript
956 lines
36 KiB
JavaScript
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 { 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 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);
|
|
validateIpcArguments(channel, args);
|
|
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);
|
|
});
|
|
|
|
registerPgpIpcHandlers({
|
|
registerIpcHandler,
|
|
BrowserWindow,
|
|
dialog,
|
|
fs,
|
|
openpgp,
|
|
pgpKeys,
|
|
pgpCache,
|
|
pgpMail,
|
|
PgpError,
|
|
pgpKeyServers,
|
|
listServers,
|
|
MAX_CUSTOM_SERVERS,
|
|
normalizeCustomServer,
|
|
randomUUID,
|
|
readAccount,
|
|
imapClient,
|
|
folderPath,
|
|
simpleParser,
|
|
extractMailContent
|
|
});
|
|
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 = {
|
|
to: message.to,
|
|
cc: message.cc,
|
|
subject: message.subject,
|
|
text: message.text,
|
|
displayName: message.displayName,
|
|
messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`,
|
|
attachments: message.attachments
|
|
};
|
|
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 };
|
|
});
|
|
|
|
registerDavIpcHandlers({
|
|
registerIpcHandler,
|
|
readDavStore,
|
|
saveDavStore,
|
|
davPublicConfig,
|
|
openDavClient,
|
|
activeDavConfig,
|
|
ICAL,
|
|
makeCalendarData,
|
|
makeVcard,
|
|
randomUUID,
|
|
assertDavObjectReference
|
|
});
|
|
|
|
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();
|
|
});
|