Refractoring Stage 3 Completed the mail-service refactoring stage and started IPC hardening
This commit is contained in:
+17
-11
@@ -65,27 +65,30 @@ This is a gradual destination, not a requirement to move everything at once. IPC
|
||||
|
||||
**Result:** persistence adapters and legacy migration are covered independently; `npm test` passes 54 tests.
|
||||
|
||||
### 4. Split mail services — in progress
|
||||
### 4. Split mail services — complete
|
||||
|
||||
- [x] Extract SMTP submission and Sent-copy handling (`desktop/mail/send-service.cjs`).
|
||||
- [x] Extract IMAP special-folder discovery and folder-path resolution (`desktop/mail/folders.cjs`).
|
||||
- [x] Extract mailbox page/search reads (`desktop/mail/read-service.cjs`).
|
||||
- [x] Extract message actions (`desktop/mail/action-service.cjs`).
|
||||
- [ ] Extract background sync, IDLE watchers, retries, and snooze processing.
|
||||
- [ ] Extract offline outbox processing.
|
||||
- [ ] Extract attachment parsing, saving, and preview workflows.
|
||||
- [x] Extract mailbox reconciliation and rule application (`desktop/mail/sync-service.cjs`).
|
||||
- [x] Extract background scheduling, per-account backoff, and request coalescing (`desktop/mail/sync-coordinator.cjs`).
|
||||
- [x] Extract IMAP IDLE watcher lifecycle (`desktop/mail/idle-watcher-manager.cjs`).
|
||||
- [x] Extract snooze reminder processing (`desktop/mail/snooze-reminder-service.cjs`).
|
||||
- [x] Extract offline outbox processing and optimistic cache updates (`desktop/mail/outbox-service.cjs`).
|
||||
- [x] Extract attachment saving and preview workflows (`desktop/mail/attachment-service.cjs`).
|
||||
|
||||
**Acceptance:** mail services can be tested with fake clients/stores; generation invalidation, connection cleanup, and no-plaintext PGP queueing remain covered.
|
||||
|
||||
**Progress:** SMTP submission/Sent-copy behavior, IMAP folder discovery, mailbox reads, and message actions now have fake-client tests, including transport cleanup, duplicate-send prevention, special-use lookup, custom-folder validation, paging/search, snooze exclusions, flag/move/delete behavior, and connection cleanup. Background sync, outbox, and attachment workflows remain to be extracted.
|
||||
**Result:** mail protocol, outbox, attachment, scheduling, IDLE, and snooze workflows are isolated behind injected dependencies; `npm test` passes 92 tests.
|
||||
|
||||
### 5. Harden and modularize IPC
|
||||
|
||||
- Register handlers by feature and keep `preload.cjs` as the narrow renderer API.
|
||||
- Validate argument shape, type, size, and authority-sensitive values at the IPC boundary.
|
||||
- Verify the sender is the expected application document before privileged actions.
|
||||
- Review navigation handling so only the intended app document can load; do not allow arbitrary `file:` navigation.
|
||||
- Return deliberate DTOs rather than internal store objects.
|
||||
- [x] Verify the IPC sender is the expected top-level application document (`desktop/security/ipc-sender.cjs`).
|
||||
- [x] Restrict navigation to the exact app document URL; reject arbitrary `file:` navigation.
|
||||
- [ ] Validate argument shape, type, size, and authority-sensitive values at the IPC boundary.
|
||||
- [ ] Register handlers by feature and keep `preload.cjs` as the narrow renderer API.
|
||||
- [ ] Return deliberate DTOs rather than internal store objects.
|
||||
|
||||
**Acceptance:** IPC tests cover malformed inputs and rejected senders; privileged behavior remains in trusted code.
|
||||
|
||||
@@ -119,5 +122,8 @@ This is a gradual destination, not a requirement to move everything at once. IPC
|
||||
- Step 1 added a generated-web-asset parity test; the full suite passed 38 tests.
|
||||
- Step 2 extracted pure account, folder, mail-content, filtering, and DAV codec helpers; the full suite passed 47 tests.
|
||||
- Step 3 extracted encrypted JSON persistence and account migration; the full suite passed 54 tests.
|
||||
- Step 4 extracted injected SMTP, IMAP folder/read, and message-action services; the full suite passed 69 tests.
|
||||
- Step 4 extracted injected SMTP, IMAP folder/read/action, outbox, attachment, mailbox-sync, and scheduling services; the full suite passed 86 tests.
|
||||
- Step 4 completed with extracted IDLE and snooze services; the full suite passed 92 tests.
|
||||
- Step 5 added a trusted top-level sender check to all 54 registered IPC handlers; sender boundary tests pass.
|
||||
- Step 5 also aligned `will-navigate` with the same exact-document policy; `npm test` passes 96 tests.
|
||||
- While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
const fs = require('node:fs/promises');
|
||||
|
||||
function createAttachmentService({ imapClient, folderPath, parseForAttachments, writeFile = fs.writeFile }) {
|
||||
async function loadAttachment(account, input, selectAttachment) {
|
||||
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 = selectAttachment(parsed.attachments || [], filename);
|
||||
if (!attachment) throw new Error('No attachment was found in this message.');
|
||||
return { attachment, filename };
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
} finally {
|
||||
if (client.usable) await client.logout().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
async function saveAttachment(account, input, showSaveDialog) {
|
||||
const { attachment, filename } = await loadAttachment(account, input, (attachments, selectedName) =>
|
||||
attachments.find(file => (file.filename || 'attachment') === selectedName) || attachments[0]);
|
||||
const safeFilename = filename.replace(/[\\/:*?"<>|]/g, '_');
|
||||
const result = await showSaveDialog({
|
||||
defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_')
|
||||
});
|
||||
if (result.canceled || !result.filePath) return { canceled: true };
|
||||
await writeFile(result.filePath, attachment.content);
|
||||
return { saved: true };
|
||||
}
|
||||
|
||||
async function previewAttachment(account, input) {
|
||||
const { attachment } = await loadAttachment(account, input, (attachments, filename) =>
|
||||
attachments.find(file => (file.filename || 'attachment') === filename));
|
||||
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.' };
|
||||
}
|
||||
|
||||
return { previewAttachment, saveAttachment };
|
||||
}
|
||||
|
||||
module.exports = { createAttachmentService };
|
||||
@@ -0,0 +1,107 @@
|
||||
function createIdleWatcherManager({
|
||||
readAccountStore,
|
||||
readAccount,
|
||||
imapClient,
|
||||
backgroundSyncGenerations,
|
||||
concurrency = 2,
|
||||
logError = (...args) => console.error(...args),
|
||||
wait = delay => new Promise(resolve => {
|
||||
const timer = setTimeout(resolve, delay);
|
||||
timer.unref();
|
||||
})
|
||||
}) {
|
||||
const idleWatchers = new Map();
|
||||
let requestSync = () => {};
|
||||
|
||||
function setRequestBackgroundSync(callback) {
|
||||
requestSync = callback;
|
||||
}
|
||||
|
||||
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 => {
|
||||
logError(`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) requestSync();
|
||||
});
|
||||
client.on('flags', event => {
|
||||
if (event.path.toLowerCase() === 'inbox') requestSync();
|
||||
});
|
||||
client.on('error', error => {
|
||||
if (!watcher.stopped) logError(`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) logError(`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 wait(retryDelay);
|
||||
}
|
||||
}
|
||||
|
||||
async function reconcileIdleWatchers() {
|
||||
const store = (await readAccountStore()) || { accounts: [] };
|
||||
const desiredAccounts = store.accounts.slice(0, concurrency);
|
||||
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);
|
||||
}
|
||||
|
||||
function stopAll() {
|
||||
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||
}
|
||||
|
||||
return { reconcileIdleWatchers, setRequestBackgroundSync, stopAll, stopIdleWatcher };
|
||||
}
|
||||
|
||||
module.exports = { createIdleWatcherManager };
|
||||
@@ -0,0 +1,71 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
function createMailOutboxService({
|
||||
sendMailNow,
|
||||
applyMessageAction,
|
||||
updateAccountStore,
|
||||
isConnectivityFailure,
|
||||
createId = randomUUID,
|
||||
now = Date.now,
|
||||
logError = (...args) => console.error(...args)
|
||||
}) {
|
||||
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;
|
||||
logError(`Could not complete queued mail operation ${operation.id}:`, error);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function queueMessageAction(account, input) {
|
||||
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: createId(), type: 'action', data: input, createdAt: now() });
|
||||
applyQueuedActionToCache(saved, input);
|
||||
});
|
||||
return { ok: true, queued: true };
|
||||
}
|
||||
|
||||
return { flushMailOutbox, queueMessageAction };
|
||||
}
|
||||
|
||||
module.exports = { applyQueuedActionToCache, createMailOutboxService };
|
||||
@@ -0,0 +1,56 @@
|
||||
function createSnoozeReminderService({
|
||||
readAccountStore,
|
||||
updateAccountStore,
|
||||
showNotification,
|
||||
sendMailSyncUpdate,
|
||||
now = Date.now,
|
||||
logError = (...args) => console.error(...args)
|
||||
}) {
|
||||
let checkInProgress = false;
|
||||
|
||||
async function checkSnoozeReminders() {
|
||||
if (checkInProgress) return;
|
||||
checkInProgress = true;
|
||||
try {
|
||||
const current = await readAccountStore();
|
||||
if (!current?.accounts.some(account =>
|
||||
(account.snoozedMessages || []).some(item => Number(item.dueAt) <= 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) <= 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) showNotification(reminder);
|
||||
sendMailSyncUpdate({
|
||||
accountId: reminder.accountId,
|
||||
snoozeReminder: true,
|
||||
snoozedFolder: reminder.folder,
|
||||
foldersChanged: ['Snoozed', reminder.folder]
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logError('Could not process snooze reminders:', error);
|
||||
} finally {
|
||||
checkInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
return { checkSnoozeReminders };
|
||||
}
|
||||
|
||||
module.exports = { createSnoozeReminderService };
|
||||
@@ -0,0 +1,90 @@
|
||||
function createBackgroundSyncCoordinator({
|
||||
readAccountStore,
|
||||
syncAccountMailboxes,
|
||||
backgroundSyncGenerations,
|
||||
backgroundSyncFailures,
|
||||
lastBackgroundSyncAt,
|
||||
flagSnapshots,
|
||||
reconcileIdleWatchers,
|
||||
sendMailSyncUpdate,
|
||||
showNewMailNotification,
|
||||
concurrency = 2,
|
||||
retryIntervalMs = 2 * 60 * 1000,
|
||||
now = Date.now,
|
||||
logError = (...args) => console.error(...args)
|
||||
}) {
|
||||
let backgroundSyncInProgress = false;
|
||||
let backgroundSyncRequested = false;
|
||||
|
||||
async function syncAccountWithBackoff(account, periodicOnly = false) {
|
||||
if (periodicOnly) {
|
||||
const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000;
|
||||
if (now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return;
|
||||
}
|
||||
const failure = backgroundSyncFailures.get(account.id);
|
||||
if (failure && now() < failure.retryAt) return;
|
||||
lastBackgroundSyncAt.set(account.id, 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, retryIntervalMs * (2 ** Math.min(attempts - 1, 4)));
|
||||
backgroundSyncFailures.set(account.id, { attempts, retryAt: now() + retryDelay });
|
||||
logError(`Background mail sync failed for ${account.email}:`, error);
|
||||
if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' });
|
||||
}
|
||||
}
|
||||
|
||||
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 += concurrency) {
|
||||
await Promise.all(store.accounts.slice(index, index + concurrency)
|
||||
.map(account => syncAccountWithBackoff(account, onlyDueAccounts)));
|
||||
}
|
||||
if (backgroundSyncRequested) onlyDueAccounts = false;
|
||||
} while (backgroundSyncRequested);
|
||||
} finally {
|
||||
backgroundSyncInProgress = false;
|
||||
if (backgroundSyncRequested) void runBackgroundSync().catch(error => logError('Background mail sync failed:', error));
|
||||
}
|
||||
}
|
||||
|
||||
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 => logError('Could not reconcile IMAP IDLE watchers:', error));
|
||||
if (backgroundSyncInProgress) {
|
||||
if (accountId || force) backgroundSyncRequested = true;
|
||||
return;
|
||||
}
|
||||
backgroundSyncRequested = true;
|
||||
void runBackgroundSync().catch(error => logError('Background mail sync failed:', error));
|
||||
}
|
||||
|
||||
return { requestBackgroundSync, runBackgroundSync, syncAccountWithBackoff };
|
||||
}
|
||||
|
||||
module.exports = { createBackgroundSyncCoordinator };
|
||||
@@ -0,0 +1,152 @@
|
||||
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;
|
||||
}
|
||||
|
||||
function createMailboxSyncService({
|
||||
imapClient,
|
||||
flushMailOutbox,
|
||||
updateAccountStore,
|
||||
saveAccountSyncState,
|
||||
backgroundSyncGenerations,
|
||||
flagSnapshots,
|
||||
findSpecialMailbox,
|
||||
folderPath,
|
||||
logError = (...args) => console.error(...args)
|
||||
}) {
|
||||
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) {
|
||||
logError(`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(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
return { syncAccountMailboxes };
|
||||
}
|
||||
|
||||
module.exports = { backgroundFolderLabel, createMailboxSyncService };
|
||||
+124
-500
@@ -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) {
|
||||
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({
|
||||
accountId: reminder.accountId,
|
||||
snoozeReminder: true,
|
||||
snoozedFolder: reminder.folder,
|
||||
foldersChanged: ['Snoozed', reminder.folder]
|
||||
},
|
||||
sendMailSyncUpdate
|
||||
});
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
const path = require('node:path');
|
||||
const { fileURLToPath } = require('node:url');
|
||||
|
||||
function isTrustedApplicationUrl(rawUrl, expectedFile) {
|
||||
let actualFile;
|
||||
try {
|
||||
const url = new URL(rawUrl);
|
||||
if (url.protocol !== 'file:' || url.search || url.hash) {
|
||||
return false;
|
||||
}
|
||||
actualFile = fileURLToPath(url);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
const expected = path.resolve(expectedFile);
|
||||
const actual = path.resolve(actualFile);
|
||||
return process.platform === 'win32'
|
||||
? actual.toLowerCase() === expected.toLowerCase()
|
||||
: actual === expected;
|
||||
}
|
||||
|
||||
function assertTrustedIpcSender(event, expectedFile) {
|
||||
const frame = event?.senderFrame;
|
||||
if (!frame || !event?.sender || frame !== event.sender.mainFrame ||
|
||||
!isTrustedApplicationUrl(frame.url, expectedFile)) {
|
||||
throw new Error('This request must come from the application window.');
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { assertTrustedIpcSender, isTrustedApplicationUrl };
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.7",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ep-mail",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.7",
|
||||
"dependencies": {
|
||||
"@capacitor/android": "^8.5.2",
|
||||
"@capacitor/core": "^8.5.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ep-mail",
|
||||
"version": "0.4.6",
|
||||
"version": "0.4.7",
|
||||
"private": true,
|
||||
"description": "Eternity Project mail client",
|
||||
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('node:path');
|
||||
const { pathToFileURL } = require('node:url');
|
||||
const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('../desktop/security/ipc-sender.cjs');
|
||||
|
||||
function eventFor(url, { subframe = false } = {}) {
|
||||
const mainFrame = { url: subframe ? pathToFileURL(path.resolve('index.html')).href : url };
|
||||
const senderFrame = subframe ? { url } : mainFrame;
|
||||
return { sender: { mainFrame }, senderFrame };
|
||||
}
|
||||
|
||||
test('accepts the trusted top-level application document', () => {
|
||||
const expected = path.resolve('index.html');
|
||||
assert.doesNotThrow(() => assertTrustedIpcSender(
|
||||
eventFor(pathToFileURL(expected).href), expected
|
||||
));
|
||||
});
|
||||
|
||||
test('rejects remote, different-file, query, and hash documents', () => {
|
||||
const expected = path.resolve('index.html');
|
||||
for (const url of [
|
||||
'https://example.com/index.html',
|
||||
pathToFileURL(path.resolve('other.html')).href,
|
||||
`${pathToFileURL(expected).href}?debug=1`,
|
||||
`${pathToFileURL(expected).href}#fragment`
|
||||
]) {
|
||||
assert.throws(() => assertTrustedIpcSender(eventFor(url), expected), /application window/);
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects subframes and missing sender-frame information', () => {
|
||||
const expected = path.resolve('index.html');
|
||||
const topUrl = pathToFileURL(expected).href;
|
||||
assert.throws(() => assertTrustedIpcSender(eventFor(topUrl, { subframe: true }), expected), /application window/);
|
||||
assert.throws(() => assertTrustedIpcSender({ sender: { mainFrame: {} } }, expected), /application window/);
|
||||
});
|
||||
|
||||
test('trusted-navigation policy allows only the app document URL', () => {
|
||||
const expected = path.resolve('index.html');
|
||||
assert.equal(isTrustedApplicationUrl(pathToFileURL(expected).href, expected), true);
|
||||
assert.equal(isTrustedApplicationUrl('https://example.com/', expected), false);
|
||||
assert.equal(isTrustedApplicationUrl(`${pathToFileURL(expected).href}#route`, expected), false);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createAttachmentService } = require('../desktop/mail/attachment-service.cjs');
|
||||
|
||||
function setup({ mailboxPath = 'INBOX', item = { source: Buffer.from('message') }, attachments = [] } = {}) {
|
||||
const calls = { loggedOut: 0, locksReleased: 0, saved: [], dialogOptions: [], parsedSources: [] };
|
||||
const client = {
|
||||
usable: true,
|
||||
async connect() {},
|
||||
async getMailboxLock(path) {
|
||||
assert.equal(path, mailboxPath);
|
||||
return { release() { calls.locksReleased += 1; } };
|
||||
},
|
||||
async fetchOne(uid, query, options) {
|
||||
assert.equal(uid, 4);
|
||||
assert.deepEqual(query, { uid: true, source: true });
|
||||
assert.deepEqual(options, { uid: true });
|
||||
return item;
|
||||
},
|
||||
async logout() { calls.loggedOut += 1; }
|
||||
};
|
||||
const service = createAttachmentService({
|
||||
imapClient() { return client; },
|
||||
async folderPath(_client, folder) { return folder === 'Missing' ? null : mailboxPath; },
|
||||
async parseForAttachments(source) {
|
||||
calls.parsedSources.push(source);
|
||||
return { attachments };
|
||||
},
|
||||
async writeFile(filePath, content) { calls.saved.push({ filePath, content }); }
|
||||
});
|
||||
return { service, calls };
|
||||
}
|
||||
|
||||
test('saves the requested attachment using a sanitized dialog default path', async () => {
|
||||
const bytes = Buffer.from('contents');
|
||||
const { service, calls } = setup({ attachments: [{ filename: 'reports/annual:2026.txt', content: bytes }] });
|
||||
const result = await service.saveAttachment({ id: 'account-1' }, {
|
||||
uid: 4, folder: 'Inbox', filename: 'reports/annual:2026.txt'
|
||||
}, async options => {
|
||||
calls.dialogOptions.push(options);
|
||||
return { canceled: false, filePath: 'C:/exports/report.txt' };
|
||||
});
|
||||
|
||||
assert.deepEqual(result, { saved: true });
|
||||
assert.deepEqual(calls.dialogOptions, [{ defaultPath: 'reports_annual_2026.txt' }]);
|
||||
assert.equal(calls.saved[0].filePath, 'C:/exports/report.txt');
|
||||
assert.deepEqual(calls.saved[0].content, bytes);
|
||||
assert.equal(calls.locksReleased, 1);
|
||||
assert.equal(calls.loggedOut, 1);
|
||||
});
|
||||
|
||||
test('cancellation does not write attachment bytes and save falls back to the first attachment', async () => {
|
||||
const { service, calls } = setup({ attachments: [{ filename: 'first.txt', content: Buffer.from('first') }] });
|
||||
const result = await service.saveAttachment({ id: 'account-1' }, { uid: 4 }, async options => {
|
||||
calls.dialogOptions.push(options);
|
||||
return { canceled: true };
|
||||
});
|
||||
|
||||
assert.deepEqual(result, { canceled: true });
|
||||
assert.deepEqual(calls.dialogOptions, [{ defaultPath: 'first.txt' }]);
|
||||
assert.equal(calls.saved.length, 0);
|
||||
});
|
||||
|
||||
test('previews supported image and text attachments with explicit size bounds', async () => {
|
||||
const imageBytes = Buffer.from([1, 2, 3]);
|
||||
const imageService = setup({ attachments: [{ filename: 'image.png', contentType: 'image/png', content: imageBytes }] }).service;
|
||||
assert.deepEqual(await imageService.previewAttachment({}, { uid: 4, filename: 'image.png' }), {
|
||||
kind: 'image', dataUrl: `data:image/png;base64,${imageBytes.toString('base64')}`
|
||||
});
|
||||
|
||||
const largeImage = setup({ attachments: [{ filename: 'large.png', contentType: 'image/png', content: Buffer.alloc(5 * 1048576 + 1) }] }).service;
|
||||
assert.deepEqual(await largeImage.previewAttachment({}, { uid: 4, filename: 'large.png' }), {
|
||||
kind: 'none', reason: 'This image is too large to preview. Download it instead.'
|
||||
});
|
||||
|
||||
const textBytes = Buffer.from('hello');
|
||||
const textService = setup({ attachments: [{ filename: 'note.txt', contentType: 'text/plain; charset=utf-8', content: textBytes }] }).service;
|
||||
assert.deepEqual(await textService.previewAttachment({}, { uid: 4, filename: 'note.txt' }), {
|
||||
kind: 'text', text: 'hello', truncated: false
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects invalid identifiers, missing messages, folders, and attachment names', async () => {
|
||||
const { service, calls } = setup({ item: null });
|
||||
await assert.rejects(() => service.previewAttachment({}, { uid: 0 }), /could not be identified/);
|
||||
await assert.rejects(() => service.previewAttachment({}, { uid: 4 }), /no longer available/);
|
||||
assert.equal(calls.loggedOut, 1);
|
||||
|
||||
const missingFolder = setup().service;
|
||||
await assert.rejects(() => missingFolder.previewAttachment({}, { uid: 4, folder: 'Missing' }), /folder could not be found/);
|
||||
const noAttachment = setup().service;
|
||||
await assert.rejects(() => noAttachment.previewAttachment({}, { uid: 4, filename: 'unknown.txt' }), /No attachment/);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const { createIdleWatcherManager } = require('../desktop/mail/idle-watcher-manager.cjs');
|
||||
|
||||
function setup(accounts, { concurrency = 2, generations = new Map(accounts.map(account => [account.id, 0])) } = {}) {
|
||||
const calls = { clients: [], requests: 0, loggedOut: 0, closed: 0, mailboxOpens: [], errors: [] };
|
||||
const manager = createIdleWatcherManager({
|
||||
async readAccountStore() { return { accounts }; },
|
||||
async readAccount(accountId) { return accounts.find(account => account.id === accountId) || null; },
|
||||
imapClient(account, options) {
|
||||
const client = new EventEmitter();
|
||||
client.usable = true;
|
||||
client.connect = async () => {};
|
||||
client.mailboxOpen = async (...args) => { calls.mailboxOpens.push(args); };
|
||||
client.logout = async () => { calls.loggedOut += 1; client.usable = false; };
|
||||
client.close = () => { calls.closed += 1; client.emit('close'); };
|
||||
calls.clients.push({ account, options, client });
|
||||
return client;
|
||||
},
|
||||
backgroundSyncGenerations: generations,
|
||||
concurrency,
|
||||
wait: () => new Promise(() => {}),
|
||||
logError(...args) { calls.errors.push(args); }
|
||||
});
|
||||
manager.setRequestBackgroundSync(() => { calls.requests += 1; });
|
||||
return { manager, calls, generations };
|
||||
}
|
||||
|
||||
test('starts only the configured number of IDLE watchers and reconciles updates', async () => {
|
||||
const accounts = [
|
||||
{ id: 'one', email: 'one@example.com' },
|
||||
{ id: 'two', email: 'two@example.com' },
|
||||
{ id: 'three', email: 'three@example.com' }
|
||||
];
|
||||
const { manager, calls } = setup(accounts, { concurrency: 2 });
|
||||
await manager.reconcileIdleWatchers();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
assert.deepEqual(calls.clients.map(item => item.account.id), ['one', 'two']);
|
||||
assert.deepEqual(calls.clients[0].options, {
|
||||
autoIdleDelay: 10_000,
|
||||
maxIdleTime: 25 * 60 * 1000,
|
||||
socketTimeout: 30 * 60 * 1000
|
||||
});
|
||||
assert.deepEqual(calls.mailboxOpens, [['INBOX', { readOnly: true }], ['INBOX', { readOnly: true }]]);
|
||||
|
||||
const firstClient = calls.clients[0].client;
|
||||
firstClient.emit('exists', { path: 'INBOX', count: 2, prevCount: 1 });
|
||||
firstClient.emit('exists', { path: 'INBOX', count: 2, prevCount: 2 });
|
||||
firstClient.emit('exists', { path: 'Sent', count: 3, prevCount: 2 });
|
||||
firstClient.emit('flags', { path: 'INBOX' });
|
||||
firstClient.emit('flags', { path: 'Sent' });
|
||||
assert.equal(calls.requests, 2);
|
||||
|
||||
manager.stopAll();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(calls.closed, 2);
|
||||
assert.equal(calls.loggedOut, 2);
|
||||
});
|
||||
|
||||
test('stops watchers when accounts are removed or their generation changes', async () => {
|
||||
const accounts = [{ id: 'one', email: 'one@example.com' }, { id: 'two', email: 'two@example.com' }];
|
||||
const generations = new Map([['one', 0], ['two', 0]]);
|
||||
const { manager, calls } = setup(accounts, { generations });
|
||||
await manager.reconcileIdleWatchers();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
generations.set('one', 1);
|
||||
accounts.splice(1, 1);
|
||||
await manager.reconcileIdleWatchers();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
assert.equal(calls.closed, 2);
|
||||
assert.equal(calls.loggedOut, 2);
|
||||
manager.stopAll();
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { applyQueuedActionToCache, createMailOutboxService } = require('../desktop/mail/outbox-service.cjs');
|
||||
|
||||
function setup({ failSend = null, failAction = null, connectivity = () => false } = {}) {
|
||||
const calls = { sends: [], actions: [], errors: [], updates: 0 };
|
||||
const store = { accounts: [{
|
||||
id: 'account-1',
|
||||
mailOutbox: [],
|
||||
mailCache: { Inbox: [{ uid: 7, subject: 'One', star: false }] }
|
||||
}] };
|
||||
const service = createMailOutboxService({
|
||||
async sendMailNow(account, data) {
|
||||
calls.sends.push([account.id, data]);
|
||||
if (failSend) throw failSend;
|
||||
},
|
||||
async applyMessageAction(account, data) {
|
||||
calls.actions.push([account.id, data]);
|
||||
if (failAction) throw failAction;
|
||||
},
|
||||
async updateAccountStore(update) { calls.updates += 1; return update(store); },
|
||||
isConnectivityFailure: connectivity,
|
||||
createId: () => 'queued-action',
|
||||
now: () => 12345,
|
||||
logError(...args) { calls.errors.push(args); }
|
||||
});
|
||||
return { service, calls, store };
|
||||
}
|
||||
|
||||
test('flushes queued sends and actions in order and removes completed operations', async () => {
|
||||
const { service, calls, store } = setup();
|
||||
const account = {
|
||||
id: 'account-1',
|
||||
mailOutbox: [
|
||||
{ id: 'send-1', type: 'send', data: { to: 'a@example.com' } },
|
||||
{ id: 'action-1', type: 'action', data: { uid: 7, action: 'star' } }
|
||||
]
|
||||
};
|
||||
store.accounts[0].mailOutbox = structuredClone(account.mailOutbox);
|
||||
|
||||
await service.flushMailOutbox(account);
|
||||
assert.deepEqual(calls.sends, [['account-1', { to: 'a@example.com' }]]);
|
||||
assert.deepEqual(calls.actions, [['account-1', { uid: 7, action: 'star' }]]);
|
||||
assert.deepEqual(store.accounts[0].mailOutbox, []);
|
||||
assert.equal(calls.updates, 2);
|
||||
});
|
||||
|
||||
test('stops at a connectivity failure and leaves the failed and later operations queued', async () => {
|
||||
const networkError = Object.assign(new Error('network down'), { code: 'ECONNRESET' });
|
||||
const { service, calls, store } = setup({ failSend: networkError, connectivity: error => error.code === 'ECONNRESET' });
|
||||
const operations = [
|
||||
{ id: 'send-1', type: 'send', data: {} },
|
||||
{ id: 'action-1', type: 'action', data: { uid: 7, action: 'star' } }
|
||||
];
|
||||
store.accounts[0].mailOutbox = structuredClone(operations);
|
||||
await service.flushMailOutbox({ id: 'account-1', mailOutbox: operations });
|
||||
|
||||
assert.deepEqual(store.accounts[0].mailOutbox, operations);
|
||||
assert.equal(calls.actions.length, 0);
|
||||
assert.equal(calls.errors.length, 0);
|
||||
});
|
||||
|
||||
test('logs non-connectivity failures and stops without deleting the failed item', async () => {
|
||||
const failure = new Error('invalid queued operation');
|
||||
const { service, calls, store } = setup({ failAction: failure });
|
||||
const operations = [{ id: 'action-1', type: 'action', data: { uid: 7, action: 'star' } }];
|
||||
store.accounts[0].mailOutbox = structuredClone(operations);
|
||||
await service.flushMailOutbox({ id: 'account-1', mailOutbox: operations });
|
||||
|
||||
assert.deepEqual(store.accounts[0].mailOutbox, operations);
|
||||
assert.equal(calls.errors.length, 1);
|
||||
assert.match(calls.errors[0][0], /action-1/);
|
||||
});
|
||||
|
||||
test('queues an action once, updates cached message state, and moves it to its optimistic folder', async () => {
|
||||
const { service, store } = setup();
|
||||
const result = await service.queueMessageAction({ id: 'account-1' }, {
|
||||
uid: 7, folder: 'Inbox', action: 'archive'
|
||||
});
|
||||
|
||||
assert.deepEqual(result, { ok: true, queued: true });
|
||||
assert.equal(store.accounts[0].mailOutbox.length, 1);
|
||||
assert.deepEqual(store.accounts[0].mailOutbox[0], {
|
||||
id: 'queued-action',
|
||||
type: 'action',
|
||||
data: { uid: 7, folder: 'Inbox', action: 'archive' },
|
||||
createdAt: 12345
|
||||
});
|
||||
assert.equal(store.accounts[0].mailCache.Inbox.length, 0);
|
||||
assert.deepEqual(store.accounts[0].mailCache.Archive[0], {
|
||||
uid: 7, subject: 'One', star: false, sourceFolder: 'Archive', archived: true, deleted: false
|
||||
});
|
||||
|
||||
await service.queueMessageAction({ id: 'account-1' }, { uid: 7, folder: 'Inbox', action: 'archive' });
|
||||
assert.equal(store.accounts[0].mailOutbox.length, 1);
|
||||
});
|
||||
|
||||
test('optimistic flag changes update the cached record without moving it', () => {
|
||||
const account = { mailCache: { Inbox: [{ uid: 2, star: false }] } };
|
||||
applyQueuedActionToCache(account, { uid: 2, folder: 'Inbox', action: 'star', enabled: true });
|
||||
assert.deepEqual(account.mailCache.Inbox, [{ uid: 2, star: true }]);
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createSnoozeReminderService } = require('../desktop/mail/snooze-reminder-service.cjs');
|
||||
|
||||
function setup({ accounts, now = 1000, update } = {}) {
|
||||
const calls = { notifications: [], updates: [], errors: [], storesRead: 0 };
|
||||
const store = { accounts };
|
||||
const service = createSnoozeReminderService({
|
||||
async readAccountStore() { calls.storesRead += 1; return store; },
|
||||
async updateAccountStore(callback) { return update ? update(callback, store) : callback(store); },
|
||||
showNotification(reminder) { calls.notifications.push(reminder); },
|
||||
sendMailSyncUpdate(message) { calls.updates.push(message); },
|
||||
now: () => now,
|
||||
logError(...args) { calls.errors.push(args); }
|
||||
});
|
||||
return { service, calls, store };
|
||||
}
|
||||
|
||||
test('removes due reminders, notifies when enabled, and sends UI updates', async () => {
|
||||
const { service, calls, store } = setup({ accounts: [
|
||||
{
|
||||
id: 'account-1', email: 'one@example.com',
|
||||
snoozedMessages: [
|
||||
{ uid: 4, folder: 'Inbox', dueAt: 900, subject: 'Due' },
|
||||
{ uid: 5, folder: 'Sent', dueAt: 1200, subject: 'Later' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id: 'account-2', email: 'two@example.com', notificationsEnabled: false,
|
||||
snoozedMessages: [{ uid: 6, folder: 'Archive', dueAt: 1000, subject: 'Quiet' }]
|
||||
}
|
||||
] });
|
||||
|
||||
await service.checkSnoozeReminders();
|
||||
assert.deepEqual(store.accounts.map(account => account.snoozedMessages), [
|
||||
[{ uid: 5, folder: 'Sent', dueAt: 1200, subject: 'Later' }],
|
||||
[]
|
||||
]);
|
||||
assert.deepEqual(calls.notifications.map(item => item.subject), ['Due']);
|
||||
assert.deepEqual(calls.updates, [
|
||||
{ accountId: 'account-1', snoozeReminder: true, snoozedFolder: 'Inbox', foldersChanged: ['Snoozed', 'Inbox'] },
|
||||
{ accountId: 'account-2', snoozeReminder: true, snoozedFolder: 'Archive', foldersChanged: ['Snoozed', 'Archive'] }
|
||||
]);
|
||||
});
|
||||
|
||||
test('does not write stores when no reminders are due', async () => {
|
||||
let writes = 0;
|
||||
const { service, calls } = setup({
|
||||
accounts: [{ id: 'account-1', snoozedMessages: [{ dueAt: 2000 }] }],
|
||||
update: async callback => { writes += 1; return callback({ accounts: [] }); }
|
||||
});
|
||||
await service.checkSnoozeReminders();
|
||||
assert.equal(writes, 0);
|
||||
assert.equal(calls.notifications.length, 0);
|
||||
assert.equal(calls.updates.length, 0);
|
||||
});
|
||||
|
||||
test('prevents overlapping reminder sweeps', async () => {
|
||||
let release;
|
||||
const update = () => new Promise(resolve => { release = resolve; });
|
||||
const { service, calls } = setup({
|
||||
accounts: [{ id: 'account-1', snoozedMessages: [{ dueAt: 1, folder: 'Inbox' }] }],
|
||||
update
|
||||
});
|
||||
const first = service.checkSnoozeReminders();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await service.checkSnoozeReminders();
|
||||
assert.equal(calls.storesRead, 1);
|
||||
release([{ accountId: 'account-1', email: 'one@example.com', folder: 'Inbox', subject: 'Due', notificationsEnabled: true }]);
|
||||
await first;
|
||||
assert.equal(calls.updates.length, 1);
|
||||
});
|
||||
|
||||
test('reports reminder processing failures and permits a later retry', async () => {
|
||||
let fail = true;
|
||||
const { service, calls } = setup({
|
||||
accounts: [{ id: 'account-1', snoozedMessages: [{ dueAt: 1, folder: 'Inbox' }] }],
|
||||
update: async callback => {
|
||||
if (fail) throw new Error('store write failed');
|
||||
return callback({ accounts: [{ id: 'account-1', snoozedMessages: [] }] });
|
||||
}
|
||||
});
|
||||
await service.checkSnoozeReminders();
|
||||
assert.equal(calls.errors.length, 1);
|
||||
fail = false;
|
||||
await service.checkSnoozeReminders();
|
||||
assert.equal(calls.errors.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createBackgroundSyncCoordinator } = require('../desktop/mail/sync-coordinator.cjs');
|
||||
|
||||
function setup({ accounts = [], sync, clock = 100000, concurrency = 2 } = {}) {
|
||||
let now = clock;
|
||||
const calls = { sync: [], updates: [], notifications: [], errors: [], reconciles: 0, active: 0, maxActive: 0 };
|
||||
const generations = new Map(accounts.map(account => [account.id, 0]));
|
||||
const failures = new Map();
|
||||
const lastSync = new Map();
|
||||
const snapshots = new Map();
|
||||
const coordinator = createBackgroundSyncCoordinator({
|
||||
async readAccountStore() { return { accounts }; },
|
||||
async syncAccountMailboxes(account) {
|
||||
calls.sync.push(account.id);
|
||||
calls.active += 1;
|
||||
calls.maxActive = Math.max(calls.maxActive, calls.active);
|
||||
try {
|
||||
return sync ? await sync(account, calls) : { newCount: 0, changedFolders: [] };
|
||||
} finally {
|
||||
calls.active -= 1;
|
||||
}
|
||||
},
|
||||
backgroundSyncGenerations: generations,
|
||||
backgroundSyncFailures: failures,
|
||||
lastBackgroundSyncAt: lastSync,
|
||||
flagSnapshots: snapshots,
|
||||
async reconcileIdleWatchers() { calls.reconciles += 1; },
|
||||
sendMailSyncUpdate(update) { calls.updates.push(update); },
|
||||
showNewMailNotification(account, count) { calls.notifications.push([account.id, count]); },
|
||||
concurrency,
|
||||
retryIntervalMs: 1000,
|
||||
now: () => now,
|
||||
logError(...args) { calls.errors.push(args); }
|
||||
});
|
||||
return { coordinator, calls, generations, failures, lastSync, snapshots, setNow(value) { now = value; } };
|
||||
}
|
||||
|
||||
test('sends sync updates and notifications only for the current account generation', async () => {
|
||||
const accounts = [{ id: 'account-1', email: 'one@example.com' }];
|
||||
const { coordinator, calls, generations } = setup({
|
||||
accounts,
|
||||
sync: async () => ({ newCount: 2, changedFolders: ['Inbox'] })
|
||||
});
|
||||
await coordinator.syncAccountWithBackoff(accounts[0]);
|
||||
assert.deepEqual(calls.updates, [{ accountId: 'account-1', newCount: 2, foldersChanged: ['Inbox'] }]);
|
||||
assert.deepEqual(calls.notifications, [['account-1', 2]]);
|
||||
|
||||
calls.updates.length = 0;
|
||||
calls.notifications.length = 0;
|
||||
const pending = coordinator.syncAccountWithBackoff(accounts[0]);
|
||||
generations.set('account-1', 1);
|
||||
await pending;
|
||||
assert.deepEqual(calls.updates, []);
|
||||
assert.deepEqual(calls.notifications, []);
|
||||
});
|
||||
|
||||
test('applies periodic account intervals and exponential retry backoff', async () => {
|
||||
let attempts = 0;
|
||||
const account = { id: 'account-1', email: 'one@example.com', syncIntervalMinutes: 2 };
|
||||
const { coordinator, calls, failures, lastSync, setNow } = setup({
|
||||
accounts: [account],
|
||||
sync: async () => {
|
||||
attempts += 1;
|
||||
throw new Error('offline');
|
||||
}
|
||||
});
|
||||
lastSync.set(account.id, 99000);
|
||||
await coordinator.syncAccountWithBackoff(account, true);
|
||||
assert.equal(attempts, 0);
|
||||
|
||||
await coordinator.syncAccountWithBackoff(account);
|
||||
assert.deepEqual(failures.get(account.id), { attempts: 1, retryAt: 101000 });
|
||||
await coordinator.syncAccountWithBackoff(account);
|
||||
assert.equal(attempts, 1);
|
||||
assert.equal(calls.updates.length, 1);
|
||||
assert.equal(calls.errors.length, 1);
|
||||
|
||||
setNow(101000);
|
||||
await coordinator.syncAccountWithBackoff(account);
|
||||
assert.deepEqual(failures.get(account.id), { attempts: 2, retryAt: 103000 });
|
||||
});
|
||||
|
||||
test('runs account syncs in bounded concurrent batches', async () => {
|
||||
const accounts = Array.from({ length: 5 }, (_, index) => ({ id: `account-${index}` }));
|
||||
const { coordinator, calls } = setup({
|
||||
accounts,
|
||||
concurrency: 2,
|
||||
sync: async (_account, state) => {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
state.sync.push('completed');
|
||||
return { newCount: 0, changedFolders: [] };
|
||||
}
|
||||
});
|
||||
await coordinator.runBackgroundSync();
|
||||
assert.ok(calls.maxActive <= 2);
|
||||
assert.equal(calls.sync.filter(id => id.startsWith('account-')).length, 5);
|
||||
});
|
||||
|
||||
test('account-specific requests invalidate stale state and force requests clear retry delays', () => {
|
||||
const { coordinator, generations, failures, snapshots } = setup({ accounts: [] });
|
||||
generations.set('account-1', 3);
|
||||
failures.set('account-1', { attempts: 3, retryAt: 999999 });
|
||||
failures.set('account-2', { attempts: 1, retryAt: 999999 });
|
||||
snapshots.set('account-1', new Map());
|
||||
coordinator.requestBackgroundSync('account-1', true);
|
||||
assert.equal(generations.get('account-1'), 4);
|
||||
assert.equal(failures.has('account-1'), false);
|
||||
assert.equal(failures.get('account-2').retryAt, 0);
|
||||
assert.equal(snapshots.has('account-1'), false);
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { backgroundFolderLabel, createMailboxSyncService } = require('../desktop/mail/sync-service.cjs');
|
||||
|
||||
function setup({ mailboxes, mailboxByPath, fetchResults = {} }) {
|
||||
const calls = { fetches: [], flags: [], moves: [], locksReleased: 0, logout: 0, outbox: 0, labels: 0, saved: null, errors: [] };
|
||||
const generations = new Map([['account-1', 1]]);
|
||||
const snapshots = new Map();
|
||||
const savedStore = { accounts: [{ id: 'account-1', ruleLabels: {} }] };
|
||||
const client = {
|
||||
usable: true,
|
||||
async connect() {},
|
||||
async list() { return mailboxes; },
|
||||
async mailboxOpen(path, options) {
|
||||
assert.deepEqual(options, { readOnly: true });
|
||||
return mailboxByPath[path];
|
||||
},
|
||||
async fetchAll(range, query, options) {
|
||||
calls.fetches.push({ range, query, options });
|
||||
const result = fetchResults[range] || [];
|
||||
return result.map(item => ({ ...item, flags: item.flags || new Set() }));
|
||||
},
|
||||
async getMailboxLock(path) {
|
||||
calls.flags.push(['lock', path]);
|
||||
return { release() { calls.locksReleased += 1; } };
|
||||
},
|
||||
async messageFlagsAdd(...args) { calls.flags.push(['add', ...args]); },
|
||||
async messageMove(...args) { calls.moves.push(args); },
|
||||
async logout() { calls.logout += 1; }
|
||||
};
|
||||
const service = createMailboxSyncService({
|
||||
imapClient() { return client; },
|
||||
async flushMailOutbox() { calls.outbox += 1; },
|
||||
async updateAccountStore(update) { calls.labels += 1; return update(savedStore); },
|
||||
async saveAccountSyncState(_id, generation, folders) {
|
||||
calls.saved = folders;
|
||||
return generations.get('account-1') === generation;
|
||||
},
|
||||
backgroundSyncGenerations: generations,
|
||||
flagSnapshots: snapshots,
|
||||
async findSpecialMailbox() { return 'Archive'; },
|
||||
async folderPath(_client, folder) { return folder; },
|
||||
logError(...args) { calls.errors.push(args); }
|
||||
});
|
||||
return { service, calls, generations, snapshots, savedStore };
|
||||
}
|
||||
|
||||
test('maps server special-use and fallback names to user-facing folders', () => {
|
||||
assert.equal(backgroundFolderLabel({ path: 'INBOX' }), 'Inbox');
|
||||
assert.equal(backgroundFolderLabel({ path: 'Provider/Sent Items' }), 'Sent');
|
||||
assert.equal(backgroundFolderLabel({ path: 'Archive', specialUse: '\\Archive' }), 'Archive');
|
||||
assert.equal(backgroundFolderLabel({ path: 'Projects/2026' }), 'Projects/2026');
|
||||
});
|
||||
|
||||
test('initializes a new mailbox cursor without reporting historical messages as new', async () => {
|
||||
const { service, calls, snapshots } = setup({
|
||||
mailboxes: [{ path: 'INBOX' }],
|
||||
mailboxByPath: { INBOX: { uidValidity: 9, uidNext: 22, highestModseq: null } },
|
||||
fetchResults: { '1:*': [{ uid: 1, flags: new Set(['\\Seen']) }, { uid: 21, flags: new Set() }] }
|
||||
});
|
||||
const result = await service.syncAccountMailboxes({ id: 'account-1', syncState: { folders: {} } });
|
||||
|
||||
assert.deepEqual(result, { newCount: 0, changedFolders: [] });
|
||||
assert.deepEqual(calls.saved.INBOX, { uidValidity: '9', lastUid: 21, highestModseq: null });
|
||||
assert.equal(snapshots.get('account-1').get('INBOX').flags.size, 2);
|
||||
assert.equal(calls.outbox, 1);
|
||||
assert.equal(calls.logout, 1);
|
||||
});
|
||||
|
||||
test('detects new inbox messages, applies matching rules, persists labels, and closes the client', async () => {
|
||||
const oldFlags = new Map([[1, '\\Seen']]);
|
||||
const { service, calls, snapshots, savedStore } = setup({
|
||||
mailboxes: [{ path: 'INBOX' }],
|
||||
mailboxByPath: { INBOX: { uidValidity: 9, uidNext: 5, highestModseq: null } },
|
||||
fetchResults: {
|
||||
'3:4': [
|
||||
{ uid: 3, envelope: { from: [{ address: 'flag@example.com' }], subject: 'Mark' } },
|
||||
{ uid: 4, envelope: { from: [{ address: 'label@example.com' }], subject: 'Keep' } }
|
||||
],
|
||||
'1:*': [{ uid: 1, flags: new Set() }, { uid: 3, flags: new Set() }, { uid: 4, flags: new Set() }]
|
||||
}
|
||||
});
|
||||
snapshots.set('account-1', new Map([['INBOX', { uidValidity: '9', flags: oldFlags }]]));
|
||||
const account = {
|
||||
id: 'account-1',
|
||||
syncState: { folders: { INBOX: { uidValidity: '9', lastUid: 2, highestModseq: null } } },
|
||||
rules: [
|
||||
{ id: 'flag-rule', senderContains: 'flag@', subjectContains: '', action: 'flag' },
|
||||
{ id: 'label-rule', senderContains: 'label@', subjectContains: '', action: 'label', value: 'Keep' }
|
||||
]
|
||||
};
|
||||
|
||||
const result = await service.syncAccountMailboxes(account);
|
||||
assert.deepEqual(result, { newCount: 2, changedFolders: ['Inbox'] });
|
||||
assert.deepEqual(calls.flags[1], ['add', 3, ['\\Flagged'], { uid: true }]);
|
||||
assert.equal(calls.locksReleased, 2);
|
||||
assert.equal(savedStore.accounts[0].ruleLabels['INBOX:4'][0], 'Keep');
|
||||
assert.equal(calls.labels, 1);
|
||||
assert.equal(calls.saved.INBOX.lastUid, 4);
|
||||
assert.equal(calls.logout, 1);
|
||||
});
|
||||
|
||||
test('does not publish a stale sync result after its account generation changes', async () => {
|
||||
const { service, calls, generations } = setup({
|
||||
mailboxes: [{ path: 'INBOX' }],
|
||||
mailboxByPath: { INBOX: { uidValidity: 9, uidNext: 1, highestModseq: 1n } }
|
||||
});
|
||||
const pending = service.syncAccountMailboxes({ id: 'account-1', syncState: { folders: {} } });
|
||||
generations.set('account-1', 2);
|
||||
const result = await pending;
|
||||
assert.deepEqual(result, { newCount: 0, changedFolders: [] });
|
||||
assert.equal(calls.logout, 1);
|
||||
});
|
||||
Reference in New Issue
Block a user