Refractoring Stage 3 Completed the mail-service refactoring stage and started IPC hardening

This commit is contained in:
2026-10-16 16:57:07 +03:00
parent e398bc4e1a
commit da543d5059
18 changed files with 1344 additions and 520 deletions
+130 -506
View File
@@ -27,6 +27,13 @@ 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');
@@ -56,18 +63,23 @@ 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();
let backgroundSyncInProgress = false;
let backgroundSyncRequested = false;
let snoozeReminderCheckInProgress = false;
const backgroundSyncGenerations = new Map();
const backgroundSyncFailures = new Map();
const flagSnapshots = new Map();
const idleWatchers = 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 };
@@ -88,153 +100,19 @@ function sendMailSyncUpdate(update) {
}
}
async function checkSnoozeReminders() {
if (snoozeReminderCheckInProgress) return;
snoozeReminderCheckInProgress = true;
try {
const current = await readAccountStore();
if (!current?.accounts.some(account =>
(account.snoozedMessages || []).some(item => Number(item.dueAt) <= Date.now())
)) return;
const due = await updateAccountStore(store => {
const reminders = [];
for (const account of store.accounts) {
const snoozes = account.snoozedMessages || [];
const remaining = [];
for (const item of snoozes) {
if (Number(item.dueAt) <= Date.now()) reminders.push({
accountId: account.id,
email: account.email,
notificationsEnabled: account.notificationsEnabled !== false,
...item
});
else remaining.push(item);
}
account.snoozedMessages = remaining;
}
return reminders;
});
for (const reminder of due) {
if (reminder.notificationsEnabled !== false && Notification.isSupported()) {
new Notification({
title: 'Mail reminder',
body: `${reminder.subject || 'A message'}${reminder.email ? ` · ${reminder.email}` : ''}`
}).show();
}
sendMailSyncUpdate({
accountId: reminder.accountId,
snoozeReminder: true,
snoozedFolder: reminder.folder,
foldersChanged: ['Snoozed', reminder.folder]
});
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();
}
} catch (error) {
console.error('Could not process snooze reminders:', error);
} finally {
snoozeReminderCheckInProgress = false;
}
}
function requestBackgroundSync(accountId = null, force = false) {
if (accountId) {
backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1);
backgroundSyncFailures.delete(accountId);
flagSnapshots.delete(accountId);
}
if (force) {
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
}
void reconcileIdleWatchers().catch(error => console.error('Could not reconcile IMAP IDLE watchers:', error));
if (backgroundSyncInProgress) {
if (accountId || force) backgroundSyncRequested = true;
return;
}
backgroundSyncRequested = true;
void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
}
function stopIdleWatcher(accountId) {
const watcher = idleWatchers.get(accountId);
if (!watcher) return;
watcher.stopped = true;
watcher.client?.close();
idleWatchers.delete(accountId);
}
function startIdleWatcher(account) {
if (idleWatchers.has(account.id)) return;
const watcher = {
generation: backgroundSyncGenerations.get(account.id) || 0,
stopped: false,
client: null
};
idleWatchers.set(account.id, watcher);
void runIdleWatcher(account.id, watcher).catch(error => {
console.error(`IMAP IDLE watcher failed for ${account.email}:`, error);
});
}
async function runIdleWatcher(accountId, watcher) {
let failures = 0;
while (!watcher.stopped && backgroundSyncGenerations.get(accountId) === watcher.generation) {
let client;
try {
const account = await readAccount(accountId);
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
client = imapClient(account, {
autoIdleDelay: 10_000,
maxIdleTime: 25 * 60 * 1000,
socketTimeout: 30 * 60 * 1000
});
watcher.client = client;
let signalDisconnected;
const disconnected = new Promise(resolve => { signalDisconnected = resolve; });
client.on('exists', event => {
if (event.path.toLowerCase() === 'inbox' && event.count > event.prevCount) requestBackgroundSync();
});
client.on('flags', event => {
if (event.path.toLowerCase() === 'inbox') requestBackgroundSync();
});
client.on('error', error => {
if (!watcher.stopped) console.error(`IMAP IDLE connection failed for ${account.email}:`, error);
signalDisconnected();
});
client.once('close', signalDisconnected);
await client.connect();
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
await client.mailboxOpen('INBOX', { readOnly: true });
const connectedAt = Date.now();
await disconnected;
if (Date.now() - connectedAt > 60_000) failures = 0;
} catch (error) {
if (!watcher.stopped) console.error(`IMAP IDLE watcher disconnected for ${accountId}:`, error);
} finally {
if (watcher.client === client) watcher.client = null;
if (client?.usable) await client.logout().catch(() => client.close());
else client?.close();
}
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
const retryDelay = Math.min(5 * 60 * 1000, 15_000 * (2 ** Math.min(failures, 5)));
failures += 1;
await new Promise(resolve => {
const timer = setTimeout(resolve, retryDelay);
timer.unref();
});
}
}
async function reconcileIdleWatchers() {
const store = (await readAccountStore()) || { accounts: [] };
const desiredAccounts = store.accounts.slice(0, backgroundIdleConcurrency);
const desiredIds = new Set(desiredAccounts.map(account => account.id));
for (const [accountId, watcher] of idleWatchers) {
if (!desiredIds.has(accountId) || watcher.generation !== (backgroundSyncGenerations.get(accountId) || 0)) {
stopIdleWatcher(accountId);
}
}
for (const account of desiredAccounts) startIdleWatcher(account);
}
},
sendMailSyncUpdate
});
const { createKeyStore } = require('./pgp-keystore.cjs');
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
@@ -489,143 +367,6 @@ async function saveAccountSyncState(accountId, generation, folders) {
});
}
function backgroundFolderLabel(mailbox) {
const specialUse = String(mailbox.specialUse || '').toLowerCase();
if (specialUse === '\\sent') return 'Sent';
if (specialUse === '\\archive') return 'Archive';
if (specialUse === '\\trash') return 'Trash';
if (mailbox.path.toLowerCase() === 'inbox') return 'Inbox';
const finalPart = mailbox.path.toLowerCase().split(/[./]/).pop();
if (['sent', 'sent items', 'sent mail', 'sent messages'].includes(finalPart)) return 'Sent';
if (['archive', 'archives', 'all mail'].includes(finalPart)) return 'Archive';
if (['trash', 'deleted items', 'deleted messages'].includes(finalPart)) return 'Trash';
return mailbox.path;
}
async function syncAccountMailboxes(account) {
await flushMailOutbox(account);
const generation = backgroundSyncGenerations.get(account.id) || 0;
const client = imapClient(account);
try {
await client.connect();
const mailboxes = await client.list();
const states = { ...(account.syncState?.folders || {}) };
const accountSnapshots = new Map(flagSnapshots.get(account.id) || []);
let inboxNewCount = 0;
const changedFolders = [];
const ruleActions = [];
for (const listedMailbox of mailboxes) {
const mailbox = await client.mailboxOpen(listedMailbox.path, { readOnly: true });
const folder = listedMailbox.path;
const label = backgroundFolderLabel(listedMailbox);
const uidValidity = String(mailbox.uidValidity);
const uidCeiling = Math.max(0, Number(mailbox.uidNext) - 1);
const oldState = states[folder];
const cursorIsValid = oldState?.uidValidity === uidValidity && Number.isInteger(oldState.lastUid);
if (!cursorIsValid) {
states[folder] = {
uidValidity,
lastUid: uidCeiling,
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : null
};
if (!mailbox.highestModseq) {
const initialFlags = await client.fetchAll('1:*', { uid: true, flags: true });
accountSnapshots.set(folder, {
uidValidity,
flags: new Map(initialFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]))
});
}
continue;
}
const previousUid = Number(oldState.lastUid);
const added = uidCeiling > previousUid
? await client.fetchAll(`${previousUid + 1}:${uidCeiling}`, { uid: true, envelope: true, flags: true }, { uid: true })
: [];
if (label === 'Inbox' && account.rules?.length) {
for (const item of added) {
const rule = account.rules.find(candidate => {
const sender = (item.envelope?.from || []).map(address => `${address.name || ''} ${address.address || ''}`).join(' ').toLowerCase();
const subject = String(item.envelope?.subject || '').toLowerCase();
return (!candidate.senderContains || sender.includes(candidate.senderContains.toLowerCase())) &&
(!candidate.subjectContains || subject.includes(candidate.subjectContains.toLowerCase()));
});
if (rule) ruleActions.push({ uid: Number(item.uid), folder, rule });
}
}
let flagsChanged = false;
if (mailbox.highestModseq && oldState.highestModseq) {
const changed = await client.fetchAll('1:*', { uid: true, flags: true, modseq: true }, {
uid: true,
changedSince: BigInt(oldState.highestModseq)
});
flagsChanged = changed.some(item => Number(item.uid) <= previousUid);
} else if (!mailbox.highestModseq) {
const currentFlags = await client.fetchAll('1:*', { uid: true, flags: true });
const nextSnapshot = new Map(currentFlags.map(item => [Number(item.uid), [...(item.flags || [])].sort().join(',')]));
const previousSnapshot = accountSnapshots.get(folder);
if (previousSnapshot?.uidValidity === uidValidity) {
flagsChanged = [...previousSnapshot.flags].some(([uid, flags]) => uid <= previousUid && nextSnapshot.get(uid) !== flags);
}
accountSnapshots.set(folder, { uidValidity, flags: nextSnapshot });
}
states[folder] = {
uidValidity,
lastUid: Math.max(previousUid, uidCeiling),
highestModseq: mailbox.highestModseq ? String(mailbox.highestModseq) : oldState.highestModseq || null
};
if (added.length && label === 'Inbox') inboxNewCount += added.length;
if (added.length || flagsChanged) changedFolders.push(label);
}
const ruleLabels = [];
for (const { uid, folder, rule } of ruleActions) {
const lock = await client.getMailboxLock(folder);
try {
if (rule.action === 'flag') {
await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
} else if (rule.action === 'archive' || rule.action === 'move') {
const target = rule.action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: await folderPath(client, rule.value);
if (!target) throw new Error(`Rule destination mailbox "${rule.value}" was not found.`);
if (target !== folder) await client.messageMove(uid, target, { uid: true });
changedFolders.push(rule.action === 'archive' ? 'Archive' : backgroundFolderLabel({ path: target }));
} else if (rule.action === 'label') {
ruleLabels.push({ key: `${folder}:${uid}`, label: rule.value });
}
} catch (error) {
console.error(`Could not apply mail rule "${rule.id}" to message ${uid}:`, error);
} finally {
lock.release();
}
}
if (ruleLabels.length) {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (!saved) return;
saved.ruleLabels = saved.ruleLabels || {};
for (const { key, label } of ruleLabels) {
saved.ruleLabels[key] = [...new Set([...(saved.ruleLabels[key] || []), label])];
}
});
}
const saved = await saveAccountSyncState(account.id, generation, states);
if (!saved || backgroundSyncGenerations.get(account.id) !== generation) {
return { newCount: 0, changedFolders: [] };
}
flagSnapshots.set(account.id, accountSnapshots);
return { newCount: inboxNewCount, changedFolders: [...new Set(changedFolders)] };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
function showNewMailNotification(account, count) {
if (!count || account.notificationsEnabled === false || !Notification.isSupported()) return;
const focused = BrowserWindow.getAllWindows().some(window => window.isFocused());
@@ -637,69 +378,19 @@ function showNewMailNotification(account, count) {
notification.show();
}
async function syncAccountWithBackoff(account, periodicOnly = false) {
if (periodicOnly) {
const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000;
if (Date.now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return;
}
const failure = backgroundSyncFailures.get(account.id);
if (failure && Date.now() < failure.retryAt) return;
lastBackgroundSyncAt.set(account.id, Date.now());
const generation = backgroundSyncGenerations.get(account.id) || 0;
try {
const result = await syncAccountMailboxes(account);
if (backgroundSyncGenerations.get(account.id) !== generation) return;
backgroundSyncFailures.delete(account.id);
if (result.newCount || result.changedFolders.length) {
const update = { accountId: account.id, newCount: result.newCount, foldersChanged: result.changedFolders };
sendMailSyncUpdate(update);
showNewMailNotification(account, result.newCount);
}
} catch (error) {
const attempts = (failure?.attempts || 0) + 1;
const retryDelay = Math.min(30 * 60 * 1000, backgroundRetryIntervalMs * (2 ** Math.min(attempts - 1, 4)));
backgroundSyncFailures.set(account.id, { attempts, retryAt: Date.now() + retryDelay });
console.error(`Background mail sync failed for ${account.email}:`, error);
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
}
}
registerIpcHandler('app:get-version', () => app.getVersion());
async function runBackgroundSync(periodicOnly = false) {
if (backgroundSyncInProgress) {
if (!periodicOnly) backgroundSyncRequested = true;
return;
}
backgroundSyncInProgress = true;
let onlyDueAccounts = periodicOnly;
try {
do {
backgroundSyncRequested = false;
const store = (await readAccountStore()) || { accounts: [] };
for (let index = 0; index < store.accounts.length; index += backgroundSyncConcurrency) {
await Promise.all(store.accounts.slice(index, index + backgroundSyncConcurrency)
.map(account => syncAccountWithBackoff(account, onlyDueAccounts)));
}
if (backgroundSyncRequested) onlyDueAccounts = false;
} while (backgroundSyncRequested);
} finally {
backgroundSyncInProgress = false;
if (backgroundSyncRequested) void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
}
}
ipcMain.handle('app:get-version', () => app.getVersion());
ipcMain.handle('mail:get-account', async () => {
registerIpcHandler('mail:get-account', async () => {
const account = await readAccount();
return account ? publicAccount(account) : null;
});
ipcMain.handle('mail:list-accounts', async () => {
registerIpcHandler('mail:list-accounts', async () => {
const store = (await readAccountStore()) || { accounts: [], activeId: null };
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
});
ipcMain.handle('mail:select-account', async (_event, accountId) => {
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.');
@@ -710,7 +401,7 @@ ipcMain.handle('mail:select-account', async (_event, accountId) => {
return publicAccount(account);
});
ipcMain.handle('mail:remove-account', async (_event, accountId) => {
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;
@@ -721,7 +412,7 @@ ipcMain.handle('mail:remove-account', async (_event, accountId) => {
return result;
});
ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
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 });
@@ -749,7 +440,7 @@ ipcMain.handle('mail:update-account', async (_event, accountId, input) => {
}
});
ipcMain.handle('mail:connect', async (_event, input) => {
registerIpcHandler('mail:connect', async (_event, input) => {
const account = normalizeAccount(input);
try {
const status = await connectMail(account);
@@ -761,7 +452,7 @@ ipcMain.handle('mail:connect', async (_event, input) => {
}
});
ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => {
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']);
@@ -780,7 +471,7 @@ ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0, f
}
});
ipcMain.handle('mail:list-folders', async () => {
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);
@@ -795,7 +486,7 @@ ipcMain.handle('mail:list-folders', async () => {
}
});
ipcMain.handle('mail:create-folder', async (_event, input) => {
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);
@@ -817,13 +508,13 @@ ipcMain.handle('mail:create-folder', async (_event, input) => {
}
});
ipcMain.handle('mail:list-drafts', async () => {
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 };
});
ipcMain.handle('mail:save-draft', async (_event, input) => {
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 = {
@@ -844,7 +535,7 @@ ipcMain.handle('mail:save-draft', async (_event, input) => {
return draft;
});
ipcMain.handle('mail:delete-draft', async (_event, id) => {
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 => {
@@ -854,7 +545,7 @@ ipcMain.handle('mail:delete-draft', async (_event, id) => {
return { ok: true };
});
ipcMain.handle('mail:set-snooze', async (_event, input) => {
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);
@@ -896,66 +587,14 @@ function isConnectivityFailure(error) {
return false;
}
function applyQueuedActionToCache(account, input) {
const folder = String(input.folder || 'Inbox');
const cache = account.mailCache?.[folder];
if (!cache) return;
const index = cache.findIndex(message => Number(message.uid || message.id) === Number(input.uid));
if (index < 0) return;
const [message] = cache.splice(index, 1);
if (input.action === 'star' || input.action === 'unread') {
message[input.action] = Boolean(input.enabled);
cache.splice(index, 0, message);
return;
}
const target = input.action === 'archive' ? 'Archive' : input.action === 'delete' ? 'Trash' : input.action === 'inbox' ? 'Inbox' : null;
if (!target) {
cache.splice(index, 0, message);
return;
}
message.sourceFolder = target;
message.archived = target === 'Archive';
message.deleted = target === 'Trash';
account.mailCache[target] = account.mailCache[target] || [];
account.mailCache[target] = [...account.mailCache[target].filter(item => Number(item.uid || item.id) !== Number(input.uid)), message].slice(-50);
}
async function flushMailOutbox(account) {
const operations = [...(account.mailOutbox || [])];
for (const operation of operations) {
try {
if (operation.type === 'send') await sendMailNow(account, operation.data);
else if (operation.type === 'action') await applyMessageAction(account, operation.data);
else throw new Error('Unsupported queued mail operation.');
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) saved.mailOutbox = (saved.mailOutbox || []).filter(item => item.id !== operation.id);
});
} catch (error) {
if (isConnectivityFailure(error)) break;
console.error(`Could not complete queued mail operation ${operation.id}:`, error);
break;
}
}
}
ipcMain.handle('mail:update-message', async (_event, input) => {
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;
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 = saved.mailOutbox.filter(item => !(item.type === 'action' &&
Number(item.data?.uid) === Number(input.uid) && item.data?.folder === input.folder && item.data?.action === input.action));
saved.mailOutbox.push({ id: randomUUID(), type: 'action', data: input, createdAt: Date.now() });
applyQueuedActionToCache(saved, input);
});
return { ok: true, queued: true };
return mailOutbox.queueMessageAction(account, input);
}
});
@@ -971,80 +610,26 @@ async function parseForAttachments(source) {
throw error;
}
}
ipcMain.handle('mail:save-attachment', async (event, input) => {
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 uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox');
const filename = String(input?.filename || 'attachment');
const safeFilename = filename.replace(/[\\/:*?"<>|]/g, '_');
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.');
const parsed = await parseForAttachments(item.source);
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename) || parsed.attachments?.[0];
if (!attachment) throw new Error('No attachment was found in this message.');
const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_') });
if (result.canceled || !result.filePath) return { canceled: true };
await fs.writeFile(result.filePath, attachment.content);
return { saved: true };
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
const parent = BrowserWindow.fromWebContents(event.sender);
return attachmentService.saveAttachment(account, input, options => dialog.showSaveDialog(parent, options));
});
ipcMain.handle('mail:preview-attachment', async (_event, input) => {
registerIpcHandler('mail:preview-attachment', async (_event, input) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before previewing attachments.');
const uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox');
const filename = String(input?.filename || 'attachment');
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.');
const parsed = await parseForAttachments(item.source);
const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename);
if (!attachment) throw new Error('No attachment was found in this message.');
const mimeType = String(attachment.contentType || '').toLowerCase().split(';')[0];
const size = attachment.content.length;
if (/^image\/(png|jpe?g|gif|webp|bmp|svg\+xml)$/.test(mimeType)) {
if (size > 5 * 1048576) return { kind: 'none', reason: 'This image is too large to preview. Download it instead.' };
return { kind: 'image', dataUrl: `data:${mimeType};base64,${attachment.content.toString('base64')}` };
}
if (mimeType.startsWith('text/') || ['application/json', 'application/xml'].includes(mimeType)) {
return { kind: 'text', text: attachment.content.subarray(0, 100000).toString('utf8'), truncated: size > 100000 };
}
return { kind: 'none', reason: 'No preview is available for this file type. Download it to open it.' };
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
return attachmentService.previewAttachment(account, input);
});
ipcMain.handle('pgp:list', () => pgpKeys.list());
ipcMain.handle('pgp:generate', (_event, input) => pgpKeys.generate({
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
}));
ipcMain.handle('pgp:import', async (event, input) => {
registerIpcHandler('pgp:import', async (event, input) => {
let armoredKey = input?.armoredKey;
if (!armoredKey) {
const result = await dialog.showOpenDialog(BrowserWindow.fromWebContents(event.sender), {
@@ -1069,25 +654,25 @@ const pgpFingerprint = value => {
if (!/^[0-9A-F]{40,64}$/.test(fingerprint)) throw new Error('That key could not be identified.');
return fingerprint;
};
ipcMain.handle('pgp:export-public', async (event, 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));
});
ipcMain.handle('pgp:export-private', async (event, fingerprint, passphrase) => {
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));
});
ipcMain.handle('pgp:change-passphrase', async (_event, input) => {
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;
});
ipcMain.handle('pgp:export-revocation', async (event, fingerprint, passphrase) => {
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));
});
ipcMain.handle('pgp:delete', async (_event, fingerprint, passphrase) => {
registerIpcHandler('pgp:delete', async (_event, fingerprint, passphrase) => {
const id = pgpFingerprint(fingerprint);
const result = await pgpKeys.remove(id, passphrase);
pgpCache.clear(id);
@@ -1123,7 +708,7 @@ const pgpFailure = error => ({
missing: error.details?.missing || []
});
ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
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));
@@ -1148,13 +733,13 @@ ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
}
});
ipcMain.handle('pgp:check-send', async (_event, input) => {
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 || '' });
});
ipcMain.handle('pgp:contacts', () => pgpKeys.listContacts());
ipcMain.handle('pgp:add-contact', async (event, input) => {
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), {
@@ -1193,7 +778,7 @@ ipcMain.handle('pgp:add-contact', async (event, input) => {
const source = ['message', 'keyserver', 'paste'].includes(input?.source) ? input.source : 'import';
return pgpKeys.addContact({ armoredKey, source });
});
ipcMain.handle('pgp:set-trust', async (event, fingerprint, trust) => {
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.
@@ -1213,22 +798,22 @@ ipcMain.handle('pgp:set-trust', async (event, fingerprint, trust) => {
}
return pgpKeys.setTrust(id, level);
});
ipcMain.handle('pgp:remove-contact', (_event, fingerprint) => pgpKeys.removeContact(pgpFingerprint(fingerprint)));
ipcMain.handle('pgp:export-contact', async (event, fingerprint) => {
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));
});
ipcMain.handle('pgp:get-settings', () => pgpKeys.getSettings());
ipcMain.handle('pgp:set-settings', async (_event, input) => {
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;
});
ipcMain.handle('pgp:key-servers', async () => {
registerIpcHandler('pgp:key-servers', async () => {
const settings = await pgpKeys.getSettings();
return listServers(settings.customKeyServers, settings.enabledKeyServers);
});
ipcMain.handle('pgp:set-key-server-enabled', async (_event, input) => {
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);
@@ -1244,7 +829,7 @@ ipcMain.handle('pgp:set-key-server-enabled', async (_event, input) => {
});
return { serverId, enabled: input.enabled };
});
ipcMain.handle('pgp:add-key-server', async (event, input) => {
registerIpcHandler('pgp:add-key-server', async (event, input) => {
const candidate = normalizeCustomServer(input);
const settings = await pgpKeys.getSettings();
const customServers = settings.customKeyServers.map(normalizeCustomServer);
@@ -1271,7 +856,7 @@ ipcMain.handle('pgp:add-key-server', async (event, input) => {
});
return { server: updated.customKeyServers[updated.customKeyServers.length - 1] };
});
ipcMain.handle('pgp:remove-key-server', async (_event, serverId) => {
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);
@@ -1283,12 +868,12 @@ ipcMain.handle('pgp:remove-key-server', async (_event, serverId) => {
});
return { removed: true };
});
ipcMain.handle('pgp:find-key', async (_event, input) => {
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);
});
ipcMain.handle('pgp:publish-key', async (event, input) => {
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 || ''));
@@ -1316,9 +901,9 @@ ipcMain.handle('pgp:publish-key', async (event, input) => {
if (response !== 1) return { canceled: true };
return pgpKeyServers.publish(server, entry.email, armoredKey, fingerprint);
});
ipcMain.handle('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
registerIpcHandler('pgp:forget-passphrases', () => { pgpCache.clear(); return { cleared: true }; });
ipcMain.handle('mail:open-external', async (event, rawUrl) => {
registerIpcHandler('mail:open-external', async (event, rawUrl) => {
let target;
try {
target = new URL(String(rawUrl || ''));
@@ -1344,15 +929,54 @@ ipcMain.handle('mail:open-external', async (event, rawUrl) => {
return { opened: true };
});
ipcMain.handle('mail:sync-inbox', async () => {
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);
ipcMain.handle('mail:send', async (event, message) => {
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;
@@ -1418,7 +1042,7 @@ ipcMain.handle('mail:send', async (event, message) => {
}
});
ipcMain.handle('mail:disconnect', async (_event, accountId) => {
registerIpcHandler('mail:disconnect', async (_event, accountId) => {
const store = await readAccountStore();
if (!store) return { accounts: [], activeId: null };
if (accountId) {
@@ -1434,12 +1058,12 @@ ipcMain.handle('mail:disconnect', async (_event, accountId) => {
return { accounts: store.accounts.map(publicAccount), activeId: store.activeId };
});
ipcMain.handle('dav:list', async () => {
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 };
});
ipcMain.handle('dav:connect', async (_event, input) => {
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();
@@ -1464,7 +1088,7 @@ ipcMain.handle('dav:connect', async (_event, input) => {
return { config: davPublicConfig(config), collections: config.collections, accounts: { caldav: store.caldav.map(davPublicConfig), carddav: store.carddav.map(davPublicConfig), activeCaldavId: store.activeCaldavId, activeCarddavId: store.activeCarddavId } };
});
ipcMain.handle('dav:activate', async (_event, input) => {
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);
@@ -1474,7 +1098,7 @@ ipcMain.handle('dav:activate', async (_event, input) => {
return { id: config.id };
});
ipcMain.handle('dav:remove', async (_event, input) => {
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);
@@ -1484,7 +1108,7 @@ ipcMain.handle('dav:remove', async (_event, input) => {
return { accounts: store[type].map(davPublicConfig), activeId: store[activeKey] };
});
ipcMain.handle('dav:sync', async (_event, requestedType) => {
registerIpcHandler('dav:sync', async (_event, requestedType) => {
const type = requestedType === 'carddav' ? 'carddav' : 'caldav';
const store = await readDavStore();
const config = activeDavConfig(store, type);
@@ -1529,7 +1153,7 @@ ipcMain.handle('dav:sync', async (_event, requestedType) => {
return { items: result, account: davPublicConfig(config) };
});
ipcMain.handle('dav:save-event', async (_event, input) => {
registerIpcHandler('dav:save-event', async (_event, input) => {
const store = await readDavStore();
const remote = input?._dav;
const config = activeDavConfig(store, 'caldav', remote?.accountId);
@@ -1549,7 +1173,7 @@ ipcMain.handle('dav:save-event', async (_event, input) => {
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 };
});
ipcMain.handle('dav:delete-event', async (_event, remote) => {
registerIpcHandler('dav:delete-event', async (_event, remote) => {
const store = await readDavStore();
const config = activeDavConfig(store, 'caldav', remote?.accountId);
if (!config || !remote?.objectUrl) return;
@@ -1557,7 +1181,7 @@ ipcMain.handle('dav:delete-event', async (_event, remote) => {
await client.deleteCalendarObject({ calendarObject: { url: remote.objectUrl, etag: remote.etag } });
});
ipcMain.handle('dav:save-contact', async (_event, input) => {
registerIpcHandler('dav:save-contact', async (_event, input) => {
const store = await readDavStore();
const remote = input?._dav;
const config = activeDavConfig(store, 'carddav', remote?.accountId);
@@ -1577,7 +1201,7 @@ ipcMain.handle('dav:save-contact', async (_event, input) => {
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 };
});
ipcMain.handle('dav:delete-contact', async (_event, remote) => {
registerIpcHandler('dav:delete-contact', async (_event, remote) => {
const store = await readDavStore();
const config = activeDavConfig(store, 'carddav', remote?.accountId);
if (!config || !remote?.objectUrl) return;
@@ -1611,7 +1235,7 @@ function createWindow() {
return { action: 'deny' };
});
window.webContents.on('will-navigate', (event, url) => {
if (!url.startsWith('file:')) event.preventDefault();
if (!isTrustedApplicationUrl(url, applicationHtmlPath)) event.preventDefault();
});
return window;
}
@@ -1695,7 +1319,7 @@ app.whenReady().then(() => {
void checkSnoozeReminders();
requestBackgroundSync();
powerMonitor.on('suspend', () => {
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
idleWatcherManager.stopAll();
});
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
app.on('activate', () => {
@@ -1708,5 +1332,5 @@ app.on('window-all-closed', () => {
});
app.on('before-quit', () => {
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
idleWatcherManager.stopAll();
});