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

This commit is contained in:
2026-10-16 16:57:07 +03:00
parent e398bc4e1a
commit da543d5059
18 changed files with 1344 additions and 520 deletions
+44
View File
@@ -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);
});
+93
View File
@@ -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/);
});
+75
View File
@@ -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();
});
+102
View File
@@ -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);
});
+111
View File
@@ -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);
});
+113
View File
@@ -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);
});