Refractoring Stage 2 Add Refractor plan.md
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createAccountStore } = require('../desktop/account-store.cjs');
|
||||
|
||||
test('account store migrates a legacy single-account record and persists its generated id', async () => {
|
||||
let stored = { email: 'user@example.com', password: 'secret' };
|
||||
let saves = 0;
|
||||
const repository = createAccountStore({
|
||||
async load() { return stored; },
|
||||
async save(value) { stored = value; saves += 1; }
|
||||
}, { createId: () => 'migrated-account' });
|
||||
|
||||
assert.deepEqual(await repository.load(), {
|
||||
accounts: [{ email: 'user@example.com', password: 'secret', id: 'migrated-account' }],
|
||||
activeId: 'migrated-account'
|
||||
});
|
||||
assert.equal(saves, 1);
|
||||
assert.equal(stored.activeId, 'migrated-account');
|
||||
});
|
||||
|
||||
test('account store retains current account records without rewriting them', async () => {
|
||||
const stored = { accounts: [{ id: 'account-1', email: 'user@example.com' }], activeId: 'account-1' };
|
||||
let saves = 0;
|
||||
const repository = createAccountStore({
|
||||
async load() { return stored; },
|
||||
async save() { saves += 1; }
|
||||
});
|
||||
|
||||
assert.equal(await repository.load(), stored);
|
||||
assert.equal(saves, 0);
|
||||
});
|
||||
|
||||
test('account store distinguishes missing records from invalid store failures', async () => {
|
||||
const missing = createAccountStore({ async load() { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); } });
|
||||
const broken = createAccountStore({ async load() { throw new Error('decrypt failed'); } });
|
||||
assert.equal(await missing.load(), null);
|
||||
await assert.rejects(() => broken.load(), /decrypt failed/);
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { makeCalendarData, makeVcard } = require('../desktop/dav-codecs.cjs');
|
||||
|
||||
test('serializes calendar events with escaped values and stable injected identifiers', () => {
|
||||
const data = makeCalendarData({
|
||||
date: '2026-10-16',
|
||||
title: 'Review, plan; follow-up',
|
||||
place: 'Room A, west',
|
||||
notes: 'First line\nSecond line',
|
||||
_dav: { uid: 'event-1' }
|
||||
}, { now: () => new Date('2026-10-16T12:34:56.000Z') });
|
||||
|
||||
assert.match(data, /UID:event-1\r\n/);
|
||||
assert.match(data, /DTSTAMP:20261016T123456Z\r\n/);
|
||||
assert.match(data, /DTSTART;VALUE=DATE:20261016\r\n/);
|
||||
assert.match(data, /SUMMARY:Review\\, plan\\; follow-up\r\n/);
|
||||
assert.match(data, /LOCATION:Room A\\, west\r\n/);
|
||||
assert.match(data, /DESCRIPTION:First line\\nSecond line\r\n/);
|
||||
});
|
||||
|
||||
test('serializes contacts with escaped fields and an injected identifier', () => {
|
||||
const data = makeVcard({
|
||||
name: 'Ada Example Lovelace',
|
||||
email: 'ada@example.com',
|
||||
note: 'Research, analysis; mathematics',
|
||||
_dav: { uid: 'contact-1' }
|
||||
});
|
||||
|
||||
assert.equal(data,
|
||||
'BEGIN:VCARD\r\nVERSION:3.0\r\nUID:contact-1\r\nFN:Ada Example Lovelace\r\n' +
|
||||
'N:Example Lovelace;Ada;;;\r\nEMAIL:ada@example.com\r\n' +
|
||||
'NOTE:Research\\, analysis\\; mathematics\r\nEND:VCARD\r\n');
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createMessageActionService } = require('../desktop/mail/action-service.cjs');
|
||||
|
||||
function setup({ sourcePath = 'INBOX', usable = true } = {}) {
|
||||
const calls = { actions: [], locks: [], released: 0, logout: 0, updates: 0 };
|
||||
const store = { accounts: [{ id: 'account-1', snoozedMessages: [
|
||||
{ uid: 7, folder: 'Inbox' }, { uid: 8, folder: 'Inbox' }, { uid: 7, folder: 'Sent' }
|
||||
] }] };
|
||||
const client = {
|
||||
usable,
|
||||
async connect() {},
|
||||
async getMailboxLock(path) {
|
||||
calls.locks.push(path);
|
||||
return { release() { calls.released += 1; } };
|
||||
},
|
||||
async messageFlagsAdd(...args) { calls.actions.push(['flagsAdd', ...args]); },
|
||||
async messageFlagsRemove(...args) { calls.actions.push(['flagsRemove', ...args]); },
|
||||
async messageMove(...args) { calls.actions.push(['move', ...args]); },
|
||||
async messageDelete(...args) { calls.actions.push(['delete', ...args]); },
|
||||
async logout() { calls.logout += 1; }
|
||||
};
|
||||
const service = createMessageActionService({
|
||||
imapClient() { return client; },
|
||||
async folderPath(_client, folder) { return folder === 'Inbox' ? sourcePath : folder; },
|
||||
async findSpecialMailbox(_client, specialUse, _fallbackNames, createName) {
|
||||
calls.actions.push(['find', specialUse, createName]);
|
||||
return specialUse === '\\Archive' ? 'Archive' : 'Trash';
|
||||
},
|
||||
async updateAccountStore(update) { calls.updates += 1; return update(store); }
|
||||
});
|
||||
return { service, calls, store };
|
||||
}
|
||||
|
||||
test('applies star and unread flags with UID addressing and releases the mailbox lock', async () => {
|
||||
const { service, calls } = setup();
|
||||
assert.deepEqual(await service.applyMessageAction({ id: 'account-1' }, { uid: 7, action: 'star', enabled: true }), { ok: true });
|
||||
assert.deepEqual(calls.actions[0], ['flagsAdd', 7, ['\\Flagged'], { uid: true }]);
|
||||
assert.deepEqual(calls.locks, ['INBOX']);
|
||||
assert.equal(calls.released, 1);
|
||||
assert.equal(calls.logout, 1);
|
||||
assert.equal(calls.updates, 0);
|
||||
});
|
||||
|
||||
test('moves archived messages and removes their matching snooze entry', async () => {
|
||||
const { service, calls, store } = setup();
|
||||
await service.applyMessageAction({ id: 'account-1' }, { uid: 7, folder: 'Inbox', action: 'archive' });
|
||||
assert.deepEqual(calls.actions, [
|
||||
['find', '\\Archive', 'Archive'],
|
||||
['move', 7, 'Archive', { uid: true }]
|
||||
]);
|
||||
assert.deepEqual(store.accounts[0].snoozedMessages, [{ uid: 8, folder: 'Inbox' }, { uid: 7, folder: 'Sent' }]);
|
||||
assert.equal(calls.updates, 1);
|
||||
assert.equal(calls.released, 1);
|
||||
});
|
||||
|
||||
test('deleting in Trash deletes rather than attempting to move a message to itself', async () => {
|
||||
const { service, calls } = setup({ sourcePath: 'Trash' });
|
||||
await service.applyMessageAction({ id: 'account-1' }, { uid: 9, folder: 'Inbox', action: 'delete' });
|
||||
assert.deepEqual(calls.actions, [
|
||||
['find', '\\Trash', 'Trash'],
|
||||
['delete', 9, { uid: true }]
|
||||
]);
|
||||
});
|
||||
|
||||
test('rejects invalid message identifiers and actions without opening IMAP', async () => {
|
||||
const { service, calls } = setup();
|
||||
await assert.rejects(() => service.applyMessageAction({}, { uid: 0, action: 'star' }), /could not be identified/);
|
||||
await assert.rejects(() => service.applyMessageAction({}, { uid: 1, action: 'expunge' }), /not supported/);
|
||||
assert.equal(calls.locks.length, 0);
|
||||
assert.equal(calls.logout, 0);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { extractMailContent } = require('../desktop/mail-content.cjs');
|
||||
|
||||
test('extracts bounded display content, links, and non-PGP attachment metadata', () => {
|
||||
const result = extractMailContent({
|
||||
text: 'First paragraph\r\n\r\nSecond paragraph',
|
||||
html: '<a href="https://example.com/a?x=1&y=2">one</a><a href="/next">two</a>',
|
||||
attachments: [
|
||||
{ filename: 'signature.asc', contentType: 'application/pgp-signature', size: 20 },
|
||||
{ filename: 'report.pdf', contentType: 'application/pdf', size: 1048576 }
|
||||
]
|
||||
});
|
||||
|
||||
assert.equal(result.bodyText, 'First paragraph\n\nSecond paragraph');
|
||||
assert.deepEqual(result.body, ['First paragraph', 'Second paragraph']);
|
||||
assert.deepEqual(result.links, ['https://example.com/a?x=1&y=2', '/next']);
|
||||
assert.deepEqual(result.attachments, [{ filename: 'report.pdf', size: 1048576 }]);
|
||||
assert.equal(result.attachment, 'report.pdf');
|
||||
assert.equal(result.size, '1.0 MB');
|
||||
});
|
||||
|
||||
test('bounds text, HTML, and links and supplies an empty-body fallback', () => {
|
||||
const result = extractMailContent({
|
||||
text: `${'x'.repeat(20001)}\n\n${Array.from({ length: 45 }, (_, index) => `p${index}`).join('\n\n')}`,
|
||||
html: `${'<a href="https://example.com">link</a>'.repeat(31)}${'h'.repeat(100001)}`
|
||||
});
|
||||
|
||||
assert.equal(result.bodyText.length, 20000);
|
||||
assert.equal(result.body.length, 1);
|
||||
assert.equal(result.html.length, 100000);
|
||||
assert.equal(result.links.length, 30);
|
||||
|
||||
const empty = extractMailContent({});
|
||||
assert.deepEqual(empty.body, ['This message has no plain-text body.']);
|
||||
assert.deepEqual(empty.attachments, []);
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createFolderService } = require('../desktop/mail/folders.cjs');
|
||||
const { isReservedFolderName } = require('../desktop/mail-model.cjs');
|
||||
|
||||
function clientWith(mailboxes = []) {
|
||||
const created = [];
|
||||
return {
|
||||
created,
|
||||
async list() { return mailboxes; },
|
||||
async mailboxCreate(name) {
|
||||
created.push(name);
|
||||
const mailbox = { path: name, name };
|
||||
mailboxes.push(mailbox);
|
||||
return mailbox;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const folders = createFolderService({ isReservedFolderName });
|
||||
|
||||
test('resolves special-use folders before provider-specific fallback names', async () => {
|
||||
const client = clientWith([
|
||||
{ path: 'Sent Items', specialUse: null },
|
||||
{ path: 'Provider/Sent', specialUse: '\\Sent' }
|
||||
]);
|
||||
assert.equal(await folders.findSpecialMailbox(client, '\\Sent', ['sent', 'sent items']), 'Provider/Sent');
|
||||
assert.equal(await folders.findSpecialMailbox(client, '\\Archive', ['archive']), null);
|
||||
});
|
||||
|
||||
test('creates a missing special mailbox only when requested', async () => {
|
||||
const client = clientWith([]);
|
||||
assert.equal(await folders.findSentMailbox(client), null);
|
||||
assert.equal(client.created.length, 0);
|
||||
assert.equal(await folders.findSentMailbox(client, true), 'Sent');
|
||||
assert.deepEqual(client.created, ['Sent']);
|
||||
});
|
||||
|
||||
test('maps built-in folder labels and validates custom folder paths', async () => {
|
||||
const client = clientWith([
|
||||
{ path: 'INBOX', name: 'INBOX' },
|
||||
{ path: 'Sent Items', name: 'Sent Items' },
|
||||
{ path: 'ArchiveBox', name: 'ArchiveBox' },
|
||||
{ path: 'Projects/2026', name: '2026' },
|
||||
{ path: 'Private', name: 'Private', flags: new Set(['\\Noselect']) }
|
||||
]);
|
||||
assert.equal(await folders.folderPath(client, 'Inbox'), 'INBOX');
|
||||
assert.equal(await folders.folderPath(client, 'Starred'), 'INBOX');
|
||||
assert.equal(await folders.folderPath(client, 'Sent'), 'Sent Items');
|
||||
assert.equal(await folders.folderPath(client, 'Folder:Projects/2026'), 'Projects/2026');
|
||||
await assert.rejects(() => folders.folderPath(client, 'Folder:Private'), /not available/);
|
||||
await assert.rejects(() => folders.folderPath(client, 'Folder:Missing'), /not available/);
|
||||
await assert.rejects(() => folders.folderPath(client, 'Unknown'), /not available/);
|
||||
});
|
||||
|
||||
test('lists sorted custom folders and excludes reserved and non-selectable mailboxes', async () => {
|
||||
const client = clientWith([
|
||||
{ path: 'INBOX', name: 'INBOX' },
|
||||
{ path: 'Sent Items', name: 'Sent Items' },
|
||||
{ path: 'Projects/Zeta', name: 'Zeta' },
|
||||
{ path: 'Projects/Alpha', name: 'Alpha' },
|
||||
{ path: 'Junk', name: 'Junk' },
|
||||
{ path: 'NoSelect', name: 'NoSelect', flags: new Set(['\\Noselect']) },
|
||||
{ path: 'Archive', name: 'Archive', specialUse: '\\Archive' }
|
||||
]);
|
||||
assert.deepEqual(await folders.listCustomFolders(client), [
|
||||
{ name: 'Alpha', path: 'Projects/Alpha', id: 'Folder:Projects/Alpha' },
|
||||
{ name: 'Zeta', path: 'Projects/Zeta', id: 'Folder:Projects/Zeta' }
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const {
|
||||
CUSTOM_FOLDER_PREFIX,
|
||||
filterMailboxMessages,
|
||||
normalizeAccount,
|
||||
publicAccount,
|
||||
validFolderName
|
||||
} = require('../desktop/mail-model.cjs');
|
||||
|
||||
const accountInput = {
|
||||
email: ' user@example.com ',
|
||||
password: 'secret',
|
||||
imapHost: ' imap.example.com ',
|
||||
smtpHost: ' smtp.example.com ',
|
||||
displayName: ' User ',
|
||||
rules: [{ senderContains: 'alerts', action: 'move', value: `${CUSTOM_FOLDER_PREFIX}Archive/Alerts` }]
|
||||
};
|
||||
|
||||
test('normalizes account values and allows only supported mail rules', () => {
|
||||
const account = normalizeAccount(accountInput, { createId: () => 'rule-1' });
|
||||
assert.equal(account.email, 'user@example.com');
|
||||
assert.equal(account.imapHost, 'imap.example.com');
|
||||
assert.equal(account.smtpHost, 'smtp.example.com');
|
||||
assert.equal(account.displayName, 'User');
|
||||
assert.equal(account.imapPort, 143);
|
||||
assert.equal(account.smtpPort, 587);
|
||||
assert.equal(account.rules[0].id, 'rule-1');
|
||||
assert.equal(account.rules[0].value, 'Folder:Archive/Alerts');
|
||||
});
|
||||
|
||||
test('rejects invalid account fields and malformed mail rules', () => {
|
||||
assert.throws(() => normalizeAccount({ ...accountInput, email: 'bad-address' }), /valid email/);
|
||||
assert.throws(() => normalizeAccount({ ...accountInput, displayName: '' }), /display name/);
|
||||
assert.throws(() => normalizeAccount({ ...accountInput, syncIntervalMinutes: 7 }), /sync interval/);
|
||||
assert.throws(() => normalizeAccount({
|
||||
...accountInput,
|
||||
rules: [{ action: 'flag' }]
|
||||
}), /needs a sender or subject condition/);
|
||||
assert.throws(() => normalizeAccount({
|
||||
...accountInput,
|
||||
rules: [{ subjectContains: 'invoice', action: 'move', value: 'Unknown' }]
|
||||
}), /must move messages/);
|
||||
});
|
||||
|
||||
test('public account projection does not expose the password or private mailbox state', () => {
|
||||
const account = normalizeAccount(accountInput);
|
||||
const result = publicAccount({
|
||||
...account,
|
||||
id: 'account-1',
|
||||
drafts: [{ text: 'private' }],
|
||||
mailOutbox: [{ data: 'private' }]
|
||||
});
|
||||
assert.equal(result.id, 'account-1');
|
||||
assert.equal(result.email, 'user@example.com');
|
||||
assert.equal('password' in result, false);
|
||||
assert.equal('drafts' in result, false);
|
||||
assert.equal('mailOutbox' in result, false);
|
||||
});
|
||||
|
||||
test('validates folder names while allowing ordinary nested server folders as rule targets', () => {
|
||||
assert.equal(validFolderName(' Receipts '), 'Receipts');
|
||||
assert.throws(() => validFolderName(''), /folder name/);
|
||||
assert.throws(() => validFolderName('Inbox'), /reserved/);
|
||||
assert.throws(() => validFolderName('folder/name'), /cannot contain/);
|
||||
});
|
||||
|
||||
test('filters messages by text, sender, subject, dates, and attachment presence', () => {
|
||||
const messages = [
|
||||
{
|
||||
sender: 'Alice Example', email: 'alice@example.com', subject: 'Quarterly report',
|
||||
snippet: 'Revenue update', body: ['Please review'], timestamp: Date.parse('2026-03-15T12:00:00Z'),
|
||||
attachments: [{ filename: 'report.pdf' }]
|
||||
},
|
||||
{
|
||||
sender: 'Bob Example', email: 'bob@example.com', subject: 'Lunch plans',
|
||||
snippet: 'See you soon', body: [], timestamp: Date.parse('2026-03-16T12:00:00Z'), attachments: []
|
||||
}
|
||||
];
|
||||
|
||||
assert.deepEqual(filterMailboxMessages(messages, { query: 'revenue review' }), [messages[0]]);
|
||||
assert.deepEqual(filterMailboxMessages(messages, { sender: 'ALICE' }), [messages[0]]);
|
||||
assert.deepEqual(filterMailboxMessages(messages, { subject: 'report' }), [messages[0]]);
|
||||
assert.deepEqual(filterMailboxMessages(messages, { after: '2026-03-16' }), [messages[1]]);
|
||||
assert.deepEqual(filterMailboxMessages(messages, { hasAttachments: true }), [messages[0]]);
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createMailReader } = require('../desktop/mail/read-service.cjs');
|
||||
|
||||
function setup({ exists = 3, fetched = [], mailboxPath = 'INBOX' } = {}) {
|
||||
const calls = { fetchRanges: [], cached: [], logout: 0, snoozed: [] };
|
||||
const client = {
|
||||
usable: true,
|
||||
async connect() {},
|
||||
async mailboxOpen(path, options) {
|
||||
assert.equal(path, mailboxPath);
|
||||
assert.deepEqual(options, { readOnly: true });
|
||||
return { exists };
|
||||
},
|
||||
async fetchAll(range, query) {
|
||||
calls.fetchRanges.push({ range, query });
|
||||
return fetched.map(item => ({ ...item, flags: item.flags || new Set() }));
|
||||
},
|
||||
async logout() { calls.logout += 1; }
|
||||
};
|
||||
const reader = createMailReader({
|
||||
imapClient() { return client; },
|
||||
async folderPath(_client, folder) { return folder === 'Missing' ? null : mailboxPath; },
|
||||
async toUiMessage(item, folder) {
|
||||
return {
|
||||
uid: Number(item.uid),
|
||||
id: Number(item.uid),
|
||||
folder,
|
||||
sender: item.sender || '',
|
||||
subject: item.subject || '',
|
||||
snippet: item.snippet || '',
|
||||
body: [],
|
||||
timestamp: item.timestamp || 0,
|
||||
tags: [folder]
|
||||
};
|
||||
},
|
||||
async cacheMailboxMessages(accountId, folder, messages) { calls.cached.push({ accountId, folder, messages }); },
|
||||
async fetchSnoozedMailbox(...args) { calls.snoozed.push(args); return { folder: 'Snoozed', messages: [] }; },
|
||||
filterMailboxMessages(messages, filters) {
|
||||
const query = String(filters.query || '').toLowerCase();
|
||||
return messages.filter(message => `${message.sender} ${message.subject} ${message.snippet}`.toLowerCase().includes(query));
|
||||
}
|
||||
});
|
||||
return { reader, calls };
|
||||
}
|
||||
|
||||
test('fetches the newest page, returns newest first, caches it, and logs out', async () => {
|
||||
const { reader, calls } = setup({
|
||||
fetched: [
|
||||
{ uid: 2, source: Buffer.from('two'), subject: 'Second' },
|
||||
{ uid: 3, source: Buffer.from('three'), subject: 'Third' }
|
||||
]
|
||||
});
|
||||
const result = await reader.fetchMailbox({ id: 'account-1' }, 'Inbox', 0, 2);
|
||||
|
||||
assert.deepEqual(calls.fetchRanges.map(call => call.range), ['2:3']);
|
||||
assert.deepEqual(result.messages.map(message => message.uid), [3, 2]);
|
||||
assert.deepEqual({ total: result.total, start: result.start, end: result.end }, { total: 3, start: 2, end: 3 });
|
||||
assert.equal(calls.cached.length, 1);
|
||||
assert.equal(calls.cached[0].accountId, 'account-1');
|
||||
assert.equal(calls.logout, 1);
|
||||
});
|
||||
|
||||
test('filtered fetch scans the bounded recent range, excludes snoozed messages, and applies labels', async () => {
|
||||
const { reader, calls } = setup({
|
||||
fetched: [
|
||||
{ uid: 1, source: Buffer.from('one'), sender: 'Alice', subject: 'Needle' },
|
||||
{ uid: 2, source: Buffer.from('two'), sender: 'Bob', subject: 'Other' },
|
||||
{ uid: 3, source: Buffer.from('three'), sender: 'Alice', subject: 'Needle' }
|
||||
]
|
||||
});
|
||||
const result = await reader.fetchMailbox({
|
||||
id: 'account-2',
|
||||
snoozedMessages: [{ uid: 3, folder: 'Inbox', dueAt: Date.now() + 60_000 }],
|
||||
ruleLabels: { 'Inbox:1': ['Important'] }
|
||||
}, 'Inbox', 0, 20, { query: 'needle' });
|
||||
|
||||
assert.deepEqual(calls.fetchRanges.map(call => call.range), ['1:3']);
|
||||
assert.deepEqual(result.messages.map(message => message.uid), [1]);
|
||||
assert.deepEqual(result.messages[0].tags, ['Inbox', 'Important']);
|
||||
assert.deepEqual(calls.cached[0].messages.map(message => message.uid), [1, 2]);
|
||||
assert.equal(calls.logout, 1);
|
||||
});
|
||||
|
||||
test('returns an empty result for an unavailable folder and still closes the connection', async () => {
|
||||
const { reader, calls } = setup({ mailboxPath: 'INBOX' });
|
||||
const result = await reader.fetchMailbox({ id: 'account-3' }, 'Missing');
|
||||
assert.deepEqual(result, { messages: [], total: 0 });
|
||||
assert.equal(calls.fetchRanges.length, 0);
|
||||
assert.equal(calls.logout, 1);
|
||||
});
|
||||
|
||||
test('delegates snoozed-folder reads without opening a separate IMAP client', async () => {
|
||||
const { reader, calls } = setup();
|
||||
const result = await reader.fetchMailbox({ id: 'account-4' }, 'Snoozed', 5, 10);
|
||||
assert.deepEqual(result, { folder: 'Snoozed', messages: [] });
|
||||
assert.deepEqual(calls.snoozed, [[{ id: 'account-4' }, 5, 10]]);
|
||||
assert.equal(calls.logout, 0);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { createMailSender } = require('../desktop/mail/send-service.cjs');
|
||||
|
||||
function makeSender({ sentMailboxFails = false, smtpFails = false } = {}) {
|
||||
const calls = { smtp: [], appended: [], closed: 0, loggedOut: 0 };
|
||||
const sender = createMailSender({
|
||||
smtpTransport() {
|
||||
return {
|
||||
async sendMail(message) {
|
||||
calls.smtp.push(message);
|
||||
if (smtpFails) throw new Error('SMTP rejected the message.');
|
||||
return { accepted: ['recipient@example.com'] };
|
||||
},
|
||||
close() { calls.closed += 1; }
|
||||
};
|
||||
},
|
||||
createTransport(options) {
|
||||
assert.deepEqual(options, { streamTransport: true, buffer: true, newline: 'windows' });
|
||||
return {
|
||||
async sendMail(message) { return { message: Buffer.from(JSON.stringify(message)) }; }
|
||||
};
|
||||
},
|
||||
imapClient() {
|
||||
return {
|
||||
usable: true,
|
||||
async connect() {
|
||||
if (sentMailboxFails) throw new Error('IMAP unavailable.');
|
||||
},
|
||||
async getMailboxLock(folder) {
|
||||
assert.equal(folder, 'Sent');
|
||||
return { release() {} };
|
||||
},
|
||||
async search() { return []; },
|
||||
async append(folder, content, flags) { calls.appended.push({ folder, content, flags }); },
|
||||
async logout() { calls.loggedOut += 1; }
|
||||
};
|
||||
},
|
||||
async findSentMailbox(_client, createIfMissing) {
|
||||
assert.equal(createIfMissing, true);
|
||||
return 'Sent';
|
||||
}
|
||||
});
|
||||
return { ...sender, calls };
|
||||
}
|
||||
|
||||
test('sends a message with bounded fields and attachments, then appends a Sent copy', async () => {
|
||||
const { sendMailNow, calls } = makeSender();
|
||||
const result = await sendMailNow({
|
||||
email: 'sender@example.com', displayName: 'Sender', signature: 'Regards'
|
||||
}, {
|
||||
to: ' recipient@example.com ',
|
||||
subject: 'A subject',
|
||||
text: 'Message body',
|
||||
messageId: '<test@ep-mail.local>',
|
||||
attachments: [{ filename: 'report.txt', contentBase64: Buffer.from('report').toString('base64') }]
|
||||
});
|
||||
|
||||
assert.deepEqual(result, { ok: true, savedToSent: true });
|
||||
assert.equal(calls.smtp.length, 1);
|
||||
assert.equal(calls.smtp[0].to, 'recipient@example.com');
|
||||
assert.equal(calls.smtp[0].text, 'Message body\n\nRegards');
|
||||
assert.equal(calls.smtp[0].messageId, '<test@ep-mail.local>');
|
||||
assert.deepEqual(calls.smtp[0].attachments[0].content, Buffer.from('report'));
|
||||
assert.equal(calls.appended.length, 1);
|
||||
assert.equal(calls.appended[0].folder, 'Sent');
|
||||
assert.deepEqual(calls.appended[0].flags, ['\\Seen']);
|
||||
assert.equal(calls.closed, 1);
|
||||
assert.equal(calls.loggedOut, 1);
|
||||
});
|
||||
|
||||
test('reports Sent-copy failures without retrying a message accepted by SMTP', async () => {
|
||||
const { sendMailNow, calls } = makeSender({ sentMailboxFails: true });
|
||||
const result = await sendMailNow({ email: 'sender@example.com' }, {
|
||||
to: 'recipient@example.com',
|
||||
text: 'Already sent'
|
||||
});
|
||||
|
||||
assert.deepEqual(result, { ok: true, savedToSent: false });
|
||||
assert.equal(calls.smtp.length, 1);
|
||||
assert.equal(calls.closed, 1);
|
||||
assert.equal(calls.appended.length, 0);
|
||||
});
|
||||
|
||||
test('closes SMTP transport and reports send failures', async () => {
|
||||
const { sendMailNow, calls } = makeSender({ smtpFails: true });
|
||||
await assert.rejects(
|
||||
() => sendMailNow({ email: 'sender@example.com' }, { to: 'recipient@example.com' }),
|
||||
/SMTP rejected/
|
||||
);
|
||||
assert.equal(calls.closed, 1);
|
||||
assert.equal(calls.appended.length, 0);
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { createSecureJsonStore } = require('../desktop/secure-json-store.cjs');
|
||||
|
||||
async function withStore(run, { available = true, assertSecureStorage = () => {} } = {}) {
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ep-mail-store-'));
|
||||
const file = path.join(directory, 'nested', 'store.enc');
|
||||
const safeStorage = {
|
||||
async isAsyncEncryptionAvailable() { return available; },
|
||||
async encryptStringAsync(value) { return Buffer.from(value, 'utf8'); },
|
||||
async decryptStringAsync(value) { return { result: Buffer.from(value).toString('utf8') }; }
|
||||
};
|
||||
const store = createSecureJsonStore({
|
||||
getFilePath: () => file,
|
||||
safeStorage,
|
||||
assertSecureStorage,
|
||||
unavailableMessage: 'Secure storage unavailable.'
|
||||
});
|
||||
try {
|
||||
await run({ directory, file, store });
|
||||
} finally {
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test('secure JSON store round-trips data and creates its parent directory', async () => {
|
||||
await withStore(async ({ file, store }) => {
|
||||
const value = { accounts: [{ email: 'user@example.com' }] };
|
||||
await store.save(value);
|
||||
assert.deepEqual(await store.load(), value);
|
||||
assert.equal(await fs.readFile(`${file}.tmp`).then(() => true, () => false), false);
|
||||
});
|
||||
});
|
||||
|
||||
test('secure JSON store checks the OS storage policy before reads and writes', async () => {
|
||||
let checks = 0;
|
||||
const assertSecureStorage = () => {
|
||||
checks += 1;
|
||||
if (checks > 0) throw new Error('Insecure backend.');
|
||||
};
|
||||
await withStore(async ({ store }) => {
|
||||
await assert.rejects(() => store.save({}), /Insecure backend/);
|
||||
await assert.rejects(() => store.load(), /Insecure backend/);
|
||||
}, { assertSecureStorage });
|
||||
});
|
||||
|
||||
test('secure JSON store refuses writes when asynchronous encryption is unavailable', async () => {
|
||||
await withStore(async ({ file, store }) => {
|
||||
await assert.rejects(() => store.save({ secret: true }), /Secure storage unavailable/);
|
||||
await assert.rejects(() => fs.access(file), { code: 'ENOENT' });
|
||||
}, { available: false });
|
||||
});
|
||||
|
||||
test('secure JSON store reports missing files to the caller', async () => {
|
||||
await withStore(async ({ store }) => {
|
||||
await assert.rejects(() => store.load(), { code: 'ENOENT' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
|
||||
const root = path.resolve(__dirname, '..');
|
||||
const generated = path.join(root, 'www');
|
||||
const webAssetExtensions = new Set(['.css', '.html', '.js', '.svg', '.webmanifest']);
|
||||
|
||||
test('generated www web assets match their root source files', async () => {
|
||||
const entries = await fs.readdir(root, { withFileTypes: true });
|
||||
const assets = entries
|
||||
.filter(entry => entry.isFile() && webAssetExtensions.has(path.extname(entry.name)))
|
||||
.map(entry => entry.name);
|
||||
|
||||
assert.ok(assets.length > 0, 'expected root web assets to be present');
|
||||
|
||||
for (const asset of assets) {
|
||||
const sourcePath = path.join(root, asset);
|
||||
const generatedPath = path.join(generated, asset);
|
||||
const [source, output] = await Promise.all([
|
||||
fs.readFile(sourcePath),
|
||||
fs.readFile(generatedPath).catch(error => {
|
||||
if (error.code === 'ENOENT') {
|
||||
assert.fail(`generated web asset is missing: www/${asset}`);
|
||||
}
|
||||
throw error;
|
||||
})
|
||||
]);
|
||||
|
||||
assert.deepEqual(output, source, `www/${asset} is stale; rebuild Android web assets`);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user