Refractoring Stage 2 Add Refractor plan.md

This commit is contained in:
2026-10-16 16:27:09 +03:00
parent e5391dbb62
commit e398bc4e1a
23 changed files with 1259 additions and 370 deletions
+123
View File
@@ -0,0 +1,123 @@
# Modularity and security refactoring plan
## Goal
Improve the maintainability and auditability of ep-mail without changing its product behavior or weakening the existing Electron/renderer security boundary. Refactor incrementally, keeping each step testable and reversible.
## Current assessment
- `desktop/main.cjs` combines Electron lifecycle, IPC registration, account persistence, IMAP/SMTP work, background sync, outbox processing, DAV, and attachment workflows.
- Renderer code is loaded as classic scripts with shared global state and implicit load-order dependencies.
- Root web assets are copied into `www/` for Capacitor. Treat root assets as source and `www/` as generated output; do not hand-edit generated copies.
- Electron currently enables context isolation and sandboxing, and disables Node integration. Keep these controls in place.
- Existing tests focus mainly on OpenPGP and attachments; IPC, storage, and mail workflow boundaries need more coverage.
- The web content is sanitized and remote images are approval-gated. Preserve and add regression coverage for these protections.
## Target boundaries
```text
desktop/
main.cjs # Electron startup and lifecycle
ipc/ # Request validation and handler registration
mail/ # Account, IMAP, SMTP, sync, outbox, message mapping
dav/ # DAV services and iCalendar/vCard codecs
security/ # Secure storage and shared boundary validation
pgp/ # OpenPGP services (existing focused modules)
renderer/
app/ mail/ accounts/ dav/ pgp/ shared/
```
This is a gradual destination, not a requirement to move everything at once. IPC modules should validate and translate renderer requests, then call services. Services should not depend on Electron IPC or window objects. Pass dependencies such as storage, network clients, clocks, and notification callbacks explicitly where practical.
## Steps and acceptance criteria
### 1. Baseline and guardrails — in progress
- [x] Record the current test baseline.
- [x] Confirm the current root/`www/` web assets match.
- [x] Document source-versus-generated asset ownership and add a regression check for drift.
- [x] Preserve unrelated working-tree changes.
**Acceptance:** `npm test` passes, the asset check passes, and no runtime behavior changes in this step.
**Result:** all acceptance checks passed; the suite now contains 38 passing tests.
### 2. Extract pure helpers — complete
- [x] Extract account/input normalization and public account mapping (`desktop/mail-model.cjs`).
- [x] Extract folder validation and message filtering (`desktop/mail-model.cjs`).
- [x] Extract parsed-message display projection (`desktop/mail-content.cjs`).
- [x] Extract DAV iCalendar/vCard serialization (`desktop/dav-codecs.cjs`).
- [x] Add isolated unit tests for these helpers.
**Acceptance:** helper tests do not need Electron or live mail/DAV servers; existing tests remain green.
**Result:** helper modules are tested independently; `npm test` passes 47 tests. Runtime-facing call sites in `desktop/main.cjs` now import the extracted functions.
### 3. Isolate secure persistence — complete
- [x] Move account, DAV, and OpenPGP encrypted JSON file I/O behind `desktop/secure-json-store.cjs`.
- [x] Move legacy account-record migration behind `desktop/account-store.cjs`.
- [x] Keep OS-backed encryption checks, migration behavior, atomic writes, and Linux `basic_text` rejection intact.
- [x] Add tests using injected storage/encryption adapters.
**Acceptance:** services no longer manage secure-store paths directly, and persistence behavior is covered by tests.
**Result:** persistence adapters and legacy migration are covered independently; `npm test` passes 54 tests.
### 4. Split mail services — in progress
- [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.
**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.
### 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.
**Acceptance:** IPC tests cover malformed inputs and rejected senders; privileged behavior remains in trusted code.
### 6. Modularize renderer incrementally
- Introduce explicit modules and feature initialization APIs, starting with shared state and mail UI.
- Replace hidden globals and script-order dependencies with imports or passed dependencies.
- Keep root web assets canonical and generated copies out of hand-edited workflows.
- Preserve CSP, HTML sanitization, and per-message remote-image approval behavior.
**Acceptance:** both desktop and Android builds include the intended modules and existing user-visible flows still work.
### 7. Security regression coverage and review
- Add coverage for HTML sanitization, remote images, DAV URL/object handling, send downgrade decisions, and OpenPGP trust/replacement paths.
- Review pending items from `SECURITY_REVIEW.md`, including key-store/IPC/signature UI review, dependency audit, and Android encryption limitations.
**Acceptance:** security-sensitive behaviors have regression tests, and unresolved risks are documented rather than silently treated as fixed.
## Execution notes
- Do not combine architectural refactoring with feature work or broad dependency upgrades.
- Run `npm test` after each extraction; run desktop/Android build checks at relevant integration points.
- Keep changes small and inspect generated output before replacing it. The Android preparation script recreates `www/`, so edits there are not authoritative.
## Progress log
- Initial baseline: `npm test` passed 37 tests on 2026-10-16.
- Initial inspection found matching root/`www/` web assets.
- `package.json` has a pre-existing user change allowing the `esbuild@0.28.2` install script; it is being preserved.
- 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.
- While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved.
+28
View File
@@ -0,0 +1,28 @@
const { randomUUID } = require('node:crypto');
function createAccountStore(secureStore, { createId = randomUUID } = {}) {
return {
async load() {
try {
const stored = await secureStore.load();
if (Array.isArray(stored.accounts)) return stored;
if (stored.email) {
const account = { ...stored, id: stored.id || createId() };
const migrated = { accounts: [account], activeId: account.id };
await secureStore.save(migrated);
return migrated;
}
return { accounts: [], activeId: null };
} catch (error) {
if (error.code === 'ENOENT') return null;
throw error;
}
},
save(store) {
return secureStore.save(store);
}
};
}
module.exports = { createAccountStore };
+31
View File
@@ -0,0 +1,31 @@
const { randomUUID } = require('node:crypto');
function escapeIcal(value = '') {
return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;');
}
function escapeVcard(value = '') {
return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;');
}
function makeCalendarData(event, { createId = randomUUID, now = () => new Date() } = {}) {
const uid = event._dav?.uid || createId();
const stamp = now().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
const start = event.time
? new Date(`${event.date}T${event.time}:00`).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
: event.date.replace(/-/g, '');
const endDate = event.time
? new Date(new Date(`${event.date}T${event.time}:00`).getTime() + 3600000)
.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '')
: null;
return `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${uid}\r\nDTSTAMP:${stamp}\r\n${event.time ? `DTSTART:${start}\r\nDTEND:${endDate}\r\n` : `DTSTART;VALUE=DATE:${start}\r\n`}SUMMARY:${escapeIcal(event.title)}\r\n${event.place ? `LOCATION:${escapeIcal(event.place)}\r\n` : ''}${event.notes ? `DESCRIPTION:${escapeIcal(event.notes)}\r\n` : ''}END:VEVENT\r\nEND:VCALENDAR\r\n`;
}
function makeVcard(contact, { createId = randomUUID } = {}) {
const name = String(contact.name || '').trim().split(/\s+/);
const first = name.shift() || '';
const last = name.join(' ');
return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${contact._dav?.uid || createId()}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`;
}
module.exports = { escapeIcal, escapeVcard, makeCalendarData, makeVcard };
+24
View File
@@ -0,0 +1,24 @@
function extractMailContent(parsed) {
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
const body = bodyText
? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40)
: ['This message has no plain-text body.'];
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
.map(match => (match[1] || match[2] || match[3] || '').replace(/&amp;/gi, '&').replace(/&#x2f;/gi, '/'))
.filter(Boolean)
.slice(0, 30);
const files = (parsed.attachments || [])
.filter(file => !/^application\/pgp-(signature|encrypted)/i.test(file.contentType || ''));
return {
bodyText,
body,
html: html.slice(0, 100000),
links,
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: files[0]?.filename || null,
size: files[0]?.size ? `${(files[0].size / 1048576).toFixed(1)} MB` : ''
};
}
module.exports = { extractMailContent };
+99
View File
@@ -0,0 +1,99 @@
const { randomUUID } = require('node:crypto');
const CUSTOM_FOLDER_PREFIX = 'Folder:';
const RESERVED_FOLDER_NAMES = new Set(['inbox', 'sent', 'drafts', 'archive', 'trash', 'starred', 'snoozed', 'junk', 'spam']);
function normalizeAccount(input, { createId = randomUUID } = {}) {
const email = String(input?.email || '').trim();
const password = String(input?.password || '');
const imapHost = String(input?.imapHost || '').trim();
const smtpHost = String(input?.smtpHost || '').trim();
const displayName = String(input?.displayName || '').trim().slice(0, 80);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
throw new Error('Enter a valid email, password, and both mail server names.');
}
if (!displayName) throw new Error('Enter a display name for this mail account.');
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
throw new Error('Choose a supported mailbox sync interval.');
}
const inputRules = Array.isArray(input?.rules) ? input.rules : [];
if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.');
const rules = inputRules.map((rule, index) => {
const senderContains = String(rule?.senderContains || '').trim().slice(0, 200);
const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200);
const action = String(rule?.action || '');
const value = String(rule?.value || '').trim().slice(0, 200);
if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) {
throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`);
}
if ((action === 'move' || action === 'label') && !value) {
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
}
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value) && !value.startsWith(CUSTOM_FOLDER_PREFIX)) {
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders.`);
}
return { id: String(rule.id || createId()), senderContains, subjectContains, action, value };
});
return {
email, password, displayName, imapHost, smtpHost,
signature: String(input?.signature || '').slice(0, 5000),
notificationsEnabled: input?.notificationsEnabled !== false,
syncIntervalMinutes,
rules,
imapPort: 143,
smtpPort: 587
};
}
function publicAccount(account) {
return {
id: account.id,
email: account.email,
displayName: account.displayName || '',
imapHost: account.imapHost,
smtpHost: account.smtpHost,
signature: account.signature || '',
notificationsEnabled: account.notificationsEnabled !== false,
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
rules: Array.isArray(account.rules) ? account.rules : []
};
}
function isReservedFolderName(name) {
return RESERVED_FOLDER_NAMES.has(String(name).toLowerCase());
}
function validFolderName(input) {
const name = String(input || '').trim();
if (!name || name.length > 100) throw new Error('Enter a folder name of up to 100 characters.');
if (/[\\/.*%#&\u0000-\u001f]/.test(name)) throw new Error('Folder names cannot contain / \\ . * % # & or control characters.');
if (isReservedFolderName(name)) throw new Error('That folder name is reserved.');
return name;
}
function filterMailboxMessages(messages, filters = {}) {
const text = String(filters.query || '').trim().toLowerCase();
const sender = String(filters.sender || '').trim().toLowerCase();
const subject = String(filters.subject || '').trim().toLowerCase();
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
return messages.filter(message => {
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
const date = Number(message.timestamp || 0);
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
(!after || date >= after) && (!before || date <= before) &&
(!filters.hasAttachments || (message.attachments || []).length > 0);
});
}
module.exports = {
CUSTOM_FOLDER_PREFIX,
filterMailboxMessages,
isReservedFolderName,
normalizeAccount,
publicAccount,
validFolderName
};
+53
View File
@@ -0,0 +1,53 @@
function createMessageActionService({ imapClient, folderPath, findSpecialMailbox, updateAccountStore }) {
async function applyMessageAction(account, input) {
const uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox');
const action = String(input?.action || '');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
const client = imapClient(account);
try {
await client.connect();
const sourcePath = await folderPath(client, folder);
if (!sourcePath) throw new Error('That mail folder could not be found.');
const lock = await client.getMailboxLock(sourcePath);
try {
if (action === 'star') {
if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true });
} else if (action === 'unread') {
if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true });
else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true });
} else {
const target = action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: action === 'delete'
? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
: 'INBOX';
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
if (action === 'delete') await client.messageDelete(uid, { uid: true });
}
else await client.messageMove(uid, target, { uid: true });
}
} finally {
lock.release();
}
if (action === 'archive' || action === 'delete' || action === 'inbox') {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) {
saved.snoozedMessages = (saved.snoozedMessages || [])
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
}
});
}
return { ok: true };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
return { applyMessageAction };
}
module.exports = { createMessageActionService };
+47
View File
@@ -0,0 +1,47 @@
function createFolderService({ customFolderPrefix = 'Folder:', isReservedFolderName = () => false } = {}) {
async function findSpecialMailbox(client, specialUse, fallbackNames, createName = null) {
const mailboxes = await client.list();
const match = mailboxes.find(mailbox => mailbox.specialUse?.toLowerCase() === specialUse.toLowerCase()) ||
mailboxes.find(mailbox => fallbackNames.includes(mailbox.path.toLowerCase().split(/[./]/).pop()));
if (match) return match.path;
if (!createName) return null;
return (await client.mailboxCreate(createName)).path;
}
async function findSentMailbox(client, createIfMissing = false) {
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
}
async function listCustomFolders(client) {
return (await client.list())
.filter(mailbox => !mailbox.flags?.has('\\Noselect') && !mailbox.specialUse &&
mailbox.path.toUpperCase() !== 'INBOX' &&
!isReservedFolderName(mailbox.path.toLowerCase().split(/[./]/).pop()) &&
!['sent items', 'sent mail', 'sent messages', 'archives', 'all mail', 'deleted items', 'deleted messages']
.includes(mailbox.path.toLowerCase().split(/[./]/).pop()))
.map(mailbox => ({ name: mailbox.name, path: mailbox.path, id: customFolderPrefix + mailbox.path }))
.sort((a, b) => a.path.localeCompare(b.path));
}
async function folderPath(client, folder, createIfMissing = false) {
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
const definitions = {
Sent: ['\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], 'Sent'],
Archive: ['\\Archive', ['archive', 'archives', 'all mail'], 'Archive'],
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
};
const definition = definitions[folder];
if (!definition && typeof folder === 'string' && folder.startsWith(customFolderPrefix)) {
const path = folder.slice(customFolderPrefix.length);
const match = (await client.list()).find(mailbox => mailbox.path === path);
if (!match || match.flags?.has('\\Noselect')) throw new Error('This folder is not available on the mail server.');
return match.path;
}
if (!definition) throw new Error('This folder is not available on the mail server.');
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
}
return { findSpecialMailbox, findSentMailbox, folderPath, listCustomFolders };
}
module.exports = { createFolderService };
+65
View File
@@ -0,0 +1,65 @@
function createMailReader({
imapClient,
folderPath,
toUiMessage,
cacheMailboxMessages,
fetchSnoozedMailbox,
filterMailboxMessages
}) {
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
const client = imapClient(account);
try {
await client.connect();
const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) return { messages: [], total: 0 };
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
const snoozed = new Set((account.snoozedMessages || [])
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
.map(item => Number(item.uid)));
if (Object.values(filters).some(value => value && value !== false)) {
const searchStart = Math.max(1, mailbox.exists - 4999);
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}) : [];
const all = [];
for (const item of fetched) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
all.push(message);
}
await cacheMailboxMessages(account.id, folder, all);
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
const start = Math.max(0, Number(offset) || 0);
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
}
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
const fetched = await client.fetchAll(`${first}:${end}`, {
uid: true,
envelope: true,
flags: true,
internalDate: true,
source: true
});
const messages = [];
for (const item of fetched.reverse()) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
messages.push(message);
}
await cacheMailboxMessages(account.id, folder, messages);
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
return { fetchMailbox };
}
module.exports = { createMailReader };
+64
View File
@@ -0,0 +1,64 @@
const { randomUUID } = require('node:crypto');
const nodemailer = require('nodemailer');
const { normalizeOutgoingAttachments } = require('../mail-attachments.cjs');
function createMailSender({ smtpTransport, imapClient, findSentMailbox, createTransport = nodemailer.createTransport }) {
async function sendMailNow(account, message) {
const to = String(message?.to || '').trim();
if (!to) throw new Error('Add at least one recipient.');
const attachments = normalizeOutgoingAttachments(message?.attachments);
const transport = smtpTransport(account);
const sentMessageId = String(message.messageId || `<${randomUUID()}@ep-mail.local>`);
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
const body = String(message?.text || '').slice(0, 500000);
const signature = String(account.signature || '').slice(0, 5000);
const messageOptions = {
from: { name: fromName, address: account.email },
to,
cc: String(message.cc || '').trim() || undefined,
subject: String(message.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: sentMessageId,
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
};
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
try {
if (rawMessage) await transport.sendMail({ envelope: message.envelope, raw: rawMessage });
else await transport.sendMail(messageOptions);
} finally {
transport.close();
}
let savedToSent = false;
const copy = createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
try {
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
const client = imapClient(account);
try {
await client.connect();
const sentPath = await findSentMailbox(client, true);
const lock = await client.getMailboxLock(sentPath);
try {
const existing = await client.search({ header: { 'message-id': sentMessageId } }, { uid: true });
if (!existing.length) await client.append(sentPath, rendered.message, ['\\Seen'], new Date());
savedToSent = true;
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
} catch {
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
}
return { ok: true, savedToSent };
}
return { sendMailNow };
}
module.exports = { createMailSender };
+64 -366
View File
@@ -11,9 +11,45 @@ const ICAL = require('ical.js');
const openpgp = require('openpgp');
const { createKeyServerService, listServers, MAX_CUSTOM_SERVERS, normalizeCustomServer } = require('./pgp-keyservers.cjs');
const { normalizeOutgoingAttachments, serializeOutgoingAttachments } = require('./mail-attachments.cjs');
const {
CUSTOM_FOLDER_PREFIX,
filterMailboxMessages,
isReservedFolderName,
normalizeAccount,
publicAccount,
validFolderName
} = require('./mail-model.cjs');
const { makeCalendarData, makeVcard } = require('./dav-codecs.cjs');
const { extractMailContent } = require('./mail-content.cjs');
const { createSecureJsonStore } = require('./secure-json-store.cjs');
const { createAccountStore } = require('./account-store.cjs');
const { createMailSender } = require('./mail/send-service.cjs');
const { createFolderService } = require('./mail/folders.cjs');
const { createMailReader } = require('./mail/read-service.cjs');
const { createMessageActionService } = require('./mail/action-service.cjs');
const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc');
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
const accountJsonStore = createSecureJsonStore({
getFilePath: credentialsPath,
safeStorage,
assertSecureStorage,
unavailableMessage: 'Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.'
});
const accountRepository = createAccountStore(accountJsonStore);
const davJsonStore = createSecureJsonStore({
getFilePath: davCredentialsPath,
safeStorage,
assertSecureStorage,
unavailableMessage: 'Secure credential storage is unavailable.'
});
const pgpJsonStore = createSecureJsonStore({
getFilePath: pgpKeysPath,
safeStorage,
assertSecureStorage,
unavailableMessage: 'Secure key storage is unavailable.'
});
const backgroundSyncIntervalMs = 30 * 1000;
const backgroundRetryIntervalMs = 2 * 60 * 1000;
const backgroundSyncConcurrency = 2;
@@ -203,37 +239,29 @@ async function reconcileIdleWatchers() {
const { createKeyStore } = require('./pgp-keystore.cjs');
const { createPgpMail, createPassphraseCache, PgpError } = require('./pgp-mail.cjs');
const pgpKeysPath = () => path.join(app.getPath('userData'), 'pgp-keys.enc');
const pgpKeys = createKeyStore({
async load() {
try {
assertSecureStorage();
const { result } = await safeStorage.decryptStringAsync(await fs.readFile(pgpKeysPath()));
return JSON.parse(result);
return await pgpJsonStore.load();
} catch (error) {
if (error.code === 'ENOENT') return { keys: [] };
throw error;
}
},
async save(data) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure key storage is unavailable.');
await fs.mkdir(path.dirname(pgpKeysPath()), { recursive: true });
await fs.writeFile(`${pgpKeysPath()}.tmp`, await safeStorage.encryptStringAsync(JSON.stringify(data)), { mode: 0o600 });
await fs.rename(`${pgpKeysPath()}.tmp`, pgpKeysPath());
}
save(data) { return pgpJsonStore.save(data); }
});
const pgpCache = createPassphraseCache(async () => (await pgpKeys.getSettings()).cacheMinutes);
const pgpMail = createPgpMail({ keyStore: pgpKeys, cache: pgpCache });
const pgpKeyServers = createKeyServerService();
const { findSpecialMailbox, findSentMailbox, listCustomFolders, folderPath } = createFolderService({
customFolderPrefix: CUSTOM_FOLDER_PREFIX,
isReservedFolderName
});
async function readDavStore() {
try {
assertSecureStorage();
const encrypted = await fs.readFile(davCredentialsPath());
const { result } = await safeStorage.decryptStringAsync(encrypted);
return JSON.parse(result);
return await davJsonStore.load();
} catch (error) {
if (error.code === 'ENOENT') return { caldav: [], carddav: [], activeCaldavId: null, activeCarddavId: null };
throw error;
@@ -241,12 +269,7 @@ async function readDavStore() {
}
async function saveDavStore(store) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error('Secure credential storage is unavailable.');
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
await fs.mkdir(path.dirname(davCredentialsPath()), { recursive: true });
await fs.writeFile(`${davCredentialsPath()}.tmp`, encrypted, { mode: 0o600 });
await fs.rename(`${davCredentialsPath()}.tmp`, davCredentialsPath());
return davJsonStore.save(store);
}
function davPublicConfig(config) {
@@ -263,65 +286,6 @@ function activeDavConfig(store, type, id = null) {
return store[key].find(item => item.id === (id || store[activeKey])) || null;
}
function escapeIcal(value = '') { return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;'); }
function escapeVcard(value = '') { return String(value).replace(/\\/g, '\\\\').replace(/\r?\n/g, '\\n').replace(/,/g, '\\,').replace(/;/g, '\\;'); }
function makeCalendarData(event) {
const uid = event._dav?.uid || randomUUID();
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
const start = event.time ? new Date(`${event.date}T${event.time}:00`).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') : event.date.replace(/-/g, '');
const endDate = event.time ? new Date(new Date(`${event.date}T${event.time}:00`).getTime() + 3600000).toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '') : null;
return `BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Eternity Project//ep-mail CalDAV\r\nBEGIN:VEVENT\r\nUID:${uid}\r\nDTSTAMP:${stamp}\r\n${event.time ? `DTSTART:${start}\r\nDTEND:${endDate}\r\n` : `DTSTART;VALUE=DATE:${start}\r\n` }SUMMARY:${escapeIcal(event.title)}\r\n${event.place ? `LOCATION:${escapeIcal(event.place)}\r\n` : ''}${event.notes ? `DESCRIPTION:${escapeIcal(event.notes)}\r\n` : ''}END:VEVENT\r\nEND:VCALENDAR\r\n`;
}
function makeVcard(contact) {
const name = String(contact.name || '').trim().split(/\s+/);
const first = name.shift() || '';
const last = name.join(' ');
return `BEGIN:VCARD\r\nVERSION:3.0\r\nUID:${contact._dav?.uid || randomUUID()}\r\nFN:${escapeVcard(contact.name)}\r\nN:${escapeVcard(last)};${escapeVcard(first)};;;\r\nEMAIL:${escapeVcard(contact.email)}\r\n${contact.note ? `NOTE:${escapeVcard(contact.note)}\r\n` : ''}END:VCARD\r\n`;
}
function normalizeAccount(input) {
const email = String(input?.email || '').trim();
const password = String(input?.password || '');
const imapHost = String(input?.imapHost || '').trim();
const smtpHost = String(input?.smtpHost || '').trim();
const displayName = String(input?.displayName || '').trim().slice(0, 80);
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) {
throw new Error('Enter a valid email, password, and both mail server names.');
}
if (!displayName) throw new Error('Enter a display name for this mail account.');
const syncIntervalMinutes = Number(input?.syncIntervalMinutes ?? 2);
if (![2, 5, 15, 30, 60].includes(syncIntervalMinutes)) {
throw new Error('Choose a supported mailbox sync interval.');
}
const inputRules = Array.isArray(input?.rules) ? input.rules : [];
if (inputRules.length > 50) throw new Error('You can set up to 50 mail rules per account.');
const rules = inputRules.map((rule, index) => {
const senderContains = String(rule?.senderContains || '').trim().slice(0, 200);
const subjectContains = String(rule?.subjectContains || '').trim().slice(0, 200);
const action = String(rule?.action || '');
const value = String(rule?.value || '').trim().slice(0, 200);
if ((!senderContains && !subjectContains) || !['archive', 'move', 'label', 'flag'].includes(action)) {
throw new Error(`Mail rule ${index + 1} needs a sender or subject condition and a valid action.`);
}
if ((action === 'move' || action === 'label') && !value) {
throw new Error(`Mail rule ${index + 1} needs a destination folder or label.`);
}
if (action === 'move' && !['Inbox', 'Archive', 'Trash'].includes(value) && !value.startsWith(CUSTOM_FOLDER_PREFIX)) {
throw new Error(`Mail rule ${index + 1} must move messages to Inbox, Archive, Trash, or one of your folders.`);
}
return { id: String(rule.id || randomUUID()), senderContains, subjectContains, action, value };
});
return {
email, password, displayName, imapHost, smtpHost,
signature: String(input?.signature || '').slice(0, 5000),
notificationsEnabled: input?.notificationsEnabled !== false,
syncIntervalMinutes,
rules,
imapPort: 143,
smtpPort: 587
};
}
function imapClient(account, options = {}) {
return new ImapFlow({
host: account.imapHost,
@@ -363,35 +327,11 @@ function assertSecureStorage() {
}
async function readAccountStore() {
try {
assertSecureStorage();
const encrypted = await fs.readFile(credentialsPath());
const { result } = await safeStorage.decryptStringAsync(encrypted);
const stored = JSON.parse(result);
if (Array.isArray(stored.accounts)) return stored;
if (stored.email) {
const account = { ...stored, id: stored.id || randomUUID() };
const migrated = { accounts: [account], activeId: account.id };
await saveAccountStore(migrated);
return migrated;
}
return { accounts: [], activeId: null };
} catch (error) {
if (error.code === 'ENOENT') return null;
throw error;
}
return accountRepository.load();
}
async function saveAccountStore(store) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) {
throw new Error('Secure credential storage is unavailable on this computer. Set up its system keyring, then try again.');
}
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(store));
const file = credentialsPath();
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 });
await fs.rename(`${file}.tmp`, file);
return accountRepository.save(store);
}
async function readAccount(accountId = null) {
@@ -400,20 +340,6 @@ async function readAccount(accountId = null) {
return store.accounts.find(account => account.id === (accountId || store.activeId)) || null;
}
function publicAccount(account) {
return {
id: account.id,
email: account.email,
displayName: account.displayName || '',
imapHost: account.imapHost,
smtpHost: account.smtpHost,
signature: account.signature || '',
notificationsEnabled: account.notificationsEnabled !== false,
syncIntervalMinutes: Number(account.syncIntervalMinutes) || 2,
rules: Array.isArray(account.rules) ? account.rules : []
};
}
async function saveAccount(account) {
return updateAccountStore(store => {
const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase());
@@ -439,76 +365,6 @@ async function connectMail(account) {
}
}
async function findSpecialMailbox(client, specialUse, fallbackNames, createName = null) {
const mailboxes = await client.list();
const match = mailboxes.find(mailbox => mailbox.specialUse?.toLowerCase() === specialUse.toLowerCase()) ||
mailboxes.find(mailbox => fallbackNames.includes(mailbox.path.toLowerCase().split(/[./]/).pop()));
if (match) return match.path;
if (!createName) return null;
return (await client.mailboxCreate(createName)).path;
}
async function findSentMailbox(client, createIfMissing = false) {
return findSpecialMailbox(client, '\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], createIfMissing ? 'Sent' : null);
}
const CUSTOM_FOLDER_PREFIX = 'Folder:';
const RESERVED_FOLDER_NAMES = new Set(['inbox', 'sent', 'drafts', 'archive', 'trash', 'starred', 'snoozed', 'junk', 'spam']);
async function listCustomFolders(client) {
return (await client.list())
.filter(mailbox => !mailbox.flags?.has('\\Noselect') && !mailbox.specialUse &&
mailbox.path.toUpperCase() !== 'INBOX' &&
!RESERVED_FOLDER_NAMES.has(mailbox.path.toLowerCase().split(/[./]/).pop()) &&
!['sent items', 'sent mail', 'sent messages', 'archives', 'all mail', 'deleted items', 'deleted messages']
.includes(mailbox.path.toLowerCase().split(/[./]/).pop()))
.map(mailbox => ({ name: mailbox.name, path: mailbox.path, id: CUSTOM_FOLDER_PREFIX + mailbox.path }))
.sort((a, b) => a.path.localeCompare(b.path));
}
function validFolderName(input) {
const name = String(input || '').trim();
if (!name || name.length > 100) throw new Error('Enter a folder name of up to 100 characters.');
if (/[\\/.*%#&\u0000-\u001f]/.test(name)) throw new Error('Folder names cannot contain / \\ . * % # & or control characters.');
if (RESERVED_FOLDER_NAMES.has(name.toLowerCase())) throw new Error('That folder name is reserved.');
return name;
}
async function folderPath(client, folder, createIfMissing = false) {
if (folder === 'Inbox' || folder === 'Starred' || folder === 'Snoozed') return 'INBOX';
const definitions = {
Sent: ['\\Sent', ['sent', 'sent items', 'sent mail', 'sent messages'], 'Sent'],
Archive: ['\\Archive', ['archive', 'archives', 'all mail'], 'Archive'],
Trash: ['\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash']
};
const definition = definitions[folder];
if (!definition && typeof folder === 'string' && folder.startsWith(CUSTOM_FOLDER_PREFIX)) {
const path = folder.slice(CUSTOM_FOLDER_PREFIX.length);
const match = (await client.list()).find(mailbox => mailbox.path === path);
if (!match || match.flags?.has('\\Noselect')) throw new Error('This folder is not available on the mail server.');
return match.path;
}
if (!definition) throw new Error('This folder is not available on the mail server.');
return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null);
}
function filterMailboxMessages(messages, filters = {}) {
const text = String(filters.query || '').trim().toLowerCase();
const sender = String(filters.sender || '').trim().toLowerCase();
const subject = String(filters.subject || '').trim().toLowerCase();
const after = filters.after ? new Date(`${filters.after}T00:00:00`).getTime() : null;
const before = filters.before ? new Date(`${filters.before}T23:59:59.999`).getTime() : null;
return messages.filter(message => {
const haystack = `${message.sender || ''} ${message.email || ''} ${message.subject || ''} ${message.snippet || ''} ${(message.body || []).join(' ')}`.toLowerCase();
const date = Number(message.timestamp || 0);
return (!text || text.split(/\s+/).every(term => haystack.includes(term))) &&
(!sender || `${message.sender || ''} ${message.email || ''}`.toLowerCase().includes(sender)) &&
(!subject || String(message.subject || '').toLowerCase().includes(subject)) &&
(!after || date >= after) && (!before || date <= before) &&
(!filters.hasAttachments || (message.attachments || []).length > 0);
});
}
async function cacheMailboxMessages(accountId, folder, messages) {
if (!messages.length) return;
await updateAccountStore(store => {
@@ -530,59 +386,6 @@ function cachedMailbox(account, folder, offset = 0, limit = 20, filters = {}) {
return { messages, total: all.length, start: all.length ? start + 1 : 0, end: start + messages.length, folder, offline: true };
}
async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20, filters = {}) {
if (folder === 'Snoozed') return fetchSnoozedMailbox(account, offset, limit);
const client = imapClient(account);
try {
await client.connect();
const mailboxPath = await folderPath(client, folder);
if (!mailboxPath) return { messages: [], total: 0 };
const mailbox = await client.mailboxOpen(mailboxPath, { readOnly: true });
const snoozed = new Set((account.snoozedMessages || [])
.filter(item => item.folder === folder && Number(item.dueAt) > Date.now())
.map(item => Number(item.uid)));
if (Object.values(filters).some(value => value && value !== false)) {
const searchStart = Math.max(1, mailbox.exists - 4999);
const fetched = mailbox.exists ? await client.fetchAll(`${searchStart}:${mailbox.exists}`, {
uid: true, envelope: true, flags: true, internalDate: true, source: true
}) : [];
const all = [];
for (const item of fetched) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
all.push(message);
}
await cacheMailboxMessages(account.id, folder, all);
const matches = filterMailboxMessages(all, filters).sort((a, b) => Number(b.timestamp) - Number(a.timestamp));
const start = Math.max(0, Number(offset) || 0);
const messages = matches.slice(start, start + Math.max(1, Math.min(50, Number(limit) || 20)));
return { messages, total: matches.length, start: matches.length ? start + 1 : 0, end: start + messages.length, folder };
}
const end = Math.max(0, mailbox.exists - Math.max(0, Number(offset) || 0));
if (!end) return { messages: [], total: mailbox.exists, start: 0, end: 0, folder };
const first = Math.max(1, end - Math.max(1, Math.min(50, Number(limit) || 20)) + 1);
const fetched = await client.fetchAll(`${first}:${end}`, {
uid: true,
envelope: true,
flags: true,
internalDate: true,
source: true
});
const messages = [];
for (const item of fetched.reverse()) {
if (!item.source || snoozed.has(Number(item.uid))) continue;
const message = await toUiMessage(item, folder);
message.tags.push(...(account.ruleLabels?.[`${folder}:${item.uid}`] || []));
messages.push(message);
}
await cacheMailboxMessages(account.id, folder, messages);
return { messages, total: mailbox.exists - snoozed.size, start: first, end: Math.min(end, mailbox.exists), folder };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
async function toUiMessage(item, folder) {
const parsed = await simpleParser(item.source);
const sender = parsed.from?.value?.[0];
@@ -590,7 +393,7 @@ async function toUiMessage(item, folder) {
const encrypted = pgpKind === 'encrypted-mime' || pgpKind === 'encrypted-inline';
const content = encrypted
? { bodyText: '', body: ['This message is encrypted with OpenPGP. Open it and enter your key passphrase to read it.'], links: [], attachments: [], attachment: null, size: '' }
: mailContent(parsed);
: extractMailContent(parsed);
const { bodyText, body, links } = content;
const pgpSignatures = pgpKind && !encrypted ? await pgpMail.verifySigned(parsed, item.source) : null;
const date = parsed.date || item.internalDate || new Date();
@@ -624,26 +427,6 @@ async function toUiMessage(item, folder) {
};
}
function mailContent(parsed) {
const bodyText = String(parsed.text || '').replace(/\r/g, '').trim().slice(0, 20000);
const body = bodyText ? bodyText.split(/\n\s*\n/).map(part => part.trim()).filter(Boolean).slice(0, 40) : ['This message has no plain-text body.'];
const html = Array.isArray(parsed.html) ? parsed.html.join('') : String(parsed.html || '');
const links = [...html.matchAll(/<a\b[^>]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/gi)]
.map(match => (match[1] || match[2] || match[3] || '').replace(/&amp;/gi, '&').replace(/&#x2f;/gi, '/'))
.filter(Boolean)
.slice(0, 30);
const files = (parsed.attachments || []).filter(file => !/^application\/pgp-(signature|encrypted)/i.test(file.contentType || ''));
return {
bodyText,
body,
html: html.slice(0, 100000),
links,
attachments: files.map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })),
attachment: files[0]?.filename || null,
size: files[0]?.size ? `${(files[0].size / 1048576).toFixed(1)} MB` : ''
};
}
async function fetchSnoozedMailbox(account, offset, limit) {
const now = Date.now();
const pending = (account.snoozedMessages || [])
@@ -681,6 +464,21 @@ async function fetchSnoozedMailbox(account, offset, limit) {
return { messages, total: pending.length, start: selected.length ? offset + 1 : 0, end: offset + messages.length, folder: 'Snoozed' };
}
const { fetchMailbox } = createMailReader({
imapClient,
folderPath,
toUiMessage,
cacheMailboxMessages,
fetchSnoozedMailbox,
filterMailboxMessages
});
const { applyMessageAction } = createMessageActionService({
imapClient,
folderPath,
findSpecialMailbox,
updateAccountStore
});
async function saveAccountSyncState(accountId, generation, folders) {
return updateAccountStore(store => {
const account = store.accounts.find(item => item.id === accountId);
@@ -1089,54 +887,6 @@ ipcMain.handle('mail:set-snooze', async (_event, input) => {
return { ok: true, snoozed: dueAt != null };
});
async function applyMessageAction(account, input) {
const uid = Number(input?.uid);
const folder = String(input?.folder || 'Inbox');
const action = String(input?.action || '');
if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.');
if (!['star', 'unread', 'archive', 'delete', 'inbox'].includes(action)) throw new Error('That mail action is not supported.');
const client = imapClient(account);
try {
await client.connect();
const sourcePath = await folderPath(client, folder);
if (!sourcePath) throw new Error('That mail folder could not be found.');
const lock = await client.getMailboxLock(sourcePath);
try {
if (action === 'star') {
if (input.enabled) await client.messageFlagsAdd(uid, ['\\Flagged'], { uid: true });
else await client.messageFlagsRemove(uid, ['\\Flagged'], { uid: true });
} else if (action === 'unread') {
if (input.enabled) await client.messageFlagsRemove(uid, ['\\Seen'], { uid: true });
else await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true });
} else {
const target = action === 'archive'
? await findSpecialMailbox(client, '\\Archive', ['archive', 'archives', 'all mail'], 'Archive')
: action === 'delete'
? await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash')
: 'INBOX';
if ((action === 'delete' || action === 'inbox') && sourcePath === target) {
if (action === 'delete') await client.messageDelete(uid, { uid: true });
}
else await client.messageMove(uid, target, { uid: true });
}
} finally {
lock.release();
}
if (action === 'archive' || action === 'delete' || action === 'inbox') {
await updateAccountStore(store => {
const saved = store.accounts.find(item => item.id === account.id);
if (saved) {
saved.snoozedMessages = (saved.snoozedMessages || [])
.filter(item => Number(item.uid) !== uid || item.folder !== folder);
}
});
}
return { ok: true };
} finally {
if (client.usable) await client.logout().catch(() => {});
}
}
function isConnectivityFailure(error) {
const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']);
for (let current = error; current; current = current.cause) {
@@ -1380,7 +1130,7 @@ ipcMain.handle('pgp:decrypt-message', async (_event, input) => {
const outer = await simpleParser(source);
try {
const result = await pgpMail.decrypt(outer, { passphrase: typeof input?.passphrase === 'string' && input.passphrase ? input.passphrase : null });
const content = mailContent(result.parsed);
const content = extractMailContent(result.parsed);
return {
ok: true,
body: content.body,
@@ -1600,59 +1350,7 @@ ipcMain.handle('mail:sync-inbox', async () => {
return fetchMailbox(account, 'Inbox');
});
async function sendMailNow(account, message) {
const to = String(message?.to || '').trim();
if (!to) throw new Error('Add at least one recipient.');
const attachments = normalizeOutgoingAttachments(message?.attachments);
const transport = smtpTransport(account);
const sentMessageId = String(message.messageId || `<${require('node:crypto').randomUUID()}@ep-mail.local>`);
const fromName = String(account.displayName || message.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email;
const body = String(message?.text || '').slice(0, 500000);
const signature = String(account.signature || '').slice(0, 5000);
const messageOptions = {
from: { name: fromName, address: account.email },
to,
cc: String(message.cc || '').trim() || undefined,
subject: String(message.subject || '(no subject)').slice(0, 998),
text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body,
messageId: sentMessageId,
attachments: attachments.map(file => ({
filename: file.filename,
contentType: file.contentType,
content: file.content
}))
};
const rawMessage = message.rawBase64 ? Buffer.from(String(message.rawBase64), 'base64') : null;
try {
if (rawMessage) await transport.sendMail({ envelope: message.envelope, raw: rawMessage });
else await transport.sendMail(messageOptions);
} finally {
transport.close();
}
let savedToSent = false;
const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' });
try {
const rendered = rawMessage ? { message: rawMessage } : await copy.sendMail(messageOptions);
const client = imapClient(account);
try {
await client.connect();
const sentPath = await findSentMailbox(client, true);
const lock = await client.getMailboxLock(sentPath);
try {
const existing = await client.search({ header: { 'message-id': sentMessageId } }, { uid: true });
if (!existing.length) await client.append(sentPath, rendered.message, ['\\Seen'], new Date());
savedToSent = true;
} finally {
lock.release();
}
} finally {
if (client.usable) await client.logout().catch(() => {});
}
} catch {
// SMTP accepted the message; report a sent-copy problem separately to avoid duplicate sends.
}
return { ok: true, savedToSent };
}
const { sendMailNow } = createMailSender({ smtpTransport, imapClient, findSentMailbox });
ipcMain.handle('mail:send', async (event, message) => {
const account = await readAccount();
+33
View File
@@ -0,0 +1,33 @@
const fs = require('node:fs/promises');
const path = require('node:path');
function createSecureJsonStore({ getFilePath, safeStorage, assertSecureStorage, unavailableMessage }) {
if (typeof getFilePath !== 'function') throw new TypeError('A file path provider is required.');
if (!safeStorage || typeof safeStorage.encryptStringAsync !== 'function' ||
typeof safeStorage.decryptStringAsync !== 'function' ||
typeof safeStorage.isAsyncEncryptionAvailable !== 'function') {
throw new TypeError('An asynchronous safe storage adapter is required.');
}
if (typeof assertSecureStorage !== 'function') throw new TypeError('A secure-storage check is required.');
return {
async load() {
assertSecureStorage();
const encrypted = await fs.readFile(getFilePath());
const { result } = await safeStorage.decryptStringAsync(encrypted);
return JSON.parse(result);
},
async save(value) {
assertSecureStorage();
if (!await safeStorage.isAsyncEncryptionAvailable()) throw new Error(unavailableMessage);
const file = getFilePath();
const encrypted = await safeStorage.encryptStringAsync(JSON.stringify(value));
await fs.mkdir(path.dirname(file), { recursive: true });
await fs.writeFile(`${file}.tmp`, encrypted, { mode: 0o600 });
await fs.rename(`${file}.tmp`, file);
}
};
}
module.exports = { createSecureJsonStore };
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
"version": "0.4.4",
"version": "0.4.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
"version": "0.4.4",
"version": "0.4.6",
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "ep-mail",
"version": "0.4.4",
"version": "0.4.6",
"private": true,
"description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
@@ -89,7 +89,8 @@
},
"allowScripts": {
"electron@44.5.1": true,
"electron-winstaller@5.4.0": true
"electron-winstaller@5.4.0": true,
"esbuild@0.28.2": true
},
"dependencies": {
"@capacitor/android": "^8.5.2",
+38
View File
@@ -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/);
});
+34
View File
@@ -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');
});
+72
View File
@@ -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);
});
+37
View File
@@ -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&amp;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, []);
});
+70
View File
@@ -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' }
]);
});
+86
View File
@@ -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]]);
});
+99
View File
@@ -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);
});
+93
View File
@@ -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);
});
+61
View File
@@ -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' });
});
});
+33
View File
@@ -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`);
}
});