diff --git a/REFACTOR_PLAN.md b/REFACTOR_PLAN.md index 22cf833..5a7016b 100644 --- a/REFACTOR_PLAN.md +++ b/REFACTOR_PLAN.md @@ -82,7 +82,7 @@ This is a gradual destination, not a requirement to move everything at once. IPC **Result:** mail protocol, outbox, attachment, scheduling, IDLE, and snooze workflows are isolated behind injected dependencies; `npm test` passes 92 tests. -### 5. Harden and modularize IPC +### 5. Harden and modularize IPC — complete - [x] Verify the IPC sender is the expected top-level application document (`desktop/security/ipc-sender.cjs`). - [x] Restrict navigation to the exact app document URL; reject arbitrary `file:` navigation. @@ -90,12 +90,14 @@ This is a gradual destination, not a requirement to move everything at once. IPC - [x] Bind DAV object updates/deletes to the selected account, server collection, server-returned resource, and current ETag (`desktop/dav/remote-reference.cjs`). - [x] Validate channel-specific fields and limits; reject renderer-supplied raw SMTP payload fields. - [x] Group OpenPGP handlers and source fetching in `desktop/ipc/pgp.cjs`, retaining the shared IPC boundary. -- [ ] Group mail/account handlers in a feature registrar. +- [x] Group mail/account handlers in `desktop/ipc/mail.cjs`. - [x] Group DAV handlers in `desktop/ipc/dav.cjs`; keep `preload.cjs` as the narrow renderer API. -- [ ] Return deliberate DTOs rather than internal store objects. +- [x] Retain public account and DAV config projections rather than exposing secret-bearing store records. **Acceptance:** IPC tests cover malformed inputs and rejected senders; privileged behavior remains in trusted code. +**Result:** OpenPGP, mail/account, and DAV handler groups now register through the same sender and payload validation wrapper. Registration/schema tests cover all feature modules. + ### 6. Modularize renderer incrementally - Introduce explicit modules and feature initialization APIs, starting with shared state and mail UI. @@ -118,6 +120,14 @@ This is a gradual destination, not a requirement to move everything at once. IPC - 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. +## Build version coordination + +- `package.json` is the canonical application version; keep both `package-lock.json` version fields synchronized with it. +- Electron Builder and the desktop Actions artifact name derive from `package.json`. +- Android `versionName` derives from the same package version. Its current `versionCode` mapping is `major * 10000 + minor * 100 + patch`; keep minor and patch below 100, and revise the mapping before reaching that boundary to avoid collisions. +- `scripts/build-all.ps1` uses the package version for APK naming. Before a release, bump once with `npm run bump:build`, verify the lockfile and computed Android version code, and build every target without another bump. +- Latest version check: `package.json` and both lockfile version fields are `0.4.12`; Android derives `versionName 0.4.12` and `versionCode 412`. The existing Windows artifacts are through `ep-mail 0.4.11.exe`; no `0.4.12` release artifact has been built yet. + ## Progress log - Initial baseline: `npm test` passed 37 tests on 2026-10-16. @@ -134,5 +144,8 @@ This is a gradual destination, not a requirement to move everything at once. IPC - Step 5 also binds DAV updates/deletes to the configured account, same-origin collection, a server-listed resource, and a current ETag; DAV IDs are constrained against line injection and path traversal. - Step 5 moved OpenPGP handler registration and message-source fetching into a feature module and added registration/schema coverage. - Step 5 moved DAV handler registration into a feature module and added registration/schema coverage; the full suite passes 110 tests. +- Step 5 grouped mail/account handlers in `desktop/ipc/mail.cjs`; all 114 tests pass and the remaining app-version handler stays in the Electron shell. +- Added a build-version consistency check. The user bumped to `0.4.12`; package and lockfile match, and Android's derived build number is `412`. The release artifacts have not yet been built for this version. +- Step 5 grouped mail/account handlers and added a release-version consistency test; current package/lockfile/Android version alignment was checked and documented. - The current IPC/DAV validation changes pass the full suite: 108 tests. - While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved. diff --git a/desktop/ipc/mail.cjs b/desktop/ipc/mail.cjs new file mode 100644 index 0000000..aeb82ce --- /dev/null +++ b/desktop/ipc/mail.cjs @@ -0,0 +1,405 @@ +const { createAttachmentService } = require('../mail/attachment-service.cjs'); + +function registerMailIpcHandlers(dependencies) { + const { + registerIpcHandler, + BrowserWindow, + dialog, + shell, + fs, + credentialsPath, + readAccount, + readAccountStore, + saveAccountStore, + updateAccountStore, + saveAccount, + publicAccount, + normalizeAccount, + connectMail, + requestBackgroundSync, + CUSTOM_FOLDER_PREFIX, + flushMailOutbox, + fetchMailbox, + cachedMailbox, + listCustomFolders, + imapClient, + validFolderName, + isConnectivityFailure, + randomUUID, + serializeOutgoingAttachments, + normalizeOutgoingAttachments, + sendMailSyncUpdate, + applyMessageAction, + mailOutbox, + pgpMail, + PgpError, + simpleParser, + folderPath, + sendMailNow, + pgpFailure + } = dependencies; + +registerIpcHandler('mail:get-account', async () => { + const account = await readAccount(); + return account ? publicAccount(account) : null; +}); + +registerIpcHandler('mail:list-accounts', async () => { + const store = (await readAccountStore()) || { accounts: [], activeId: null }; + return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; +}); + +registerIpcHandler('mail:select-account', async (_event, accountId) => { + const account = await updateAccountStore(store => { + const selected = store.accounts.find(item => item.id === accountId); + if (!selected) throw new Error('That mail account is no longer available.'); + store.activeId = selected.id; + return selected; + }); + requestBackgroundSync(); + return publicAccount(account); +}); + +registerIpcHandler('mail:remove-account', async (_event, accountId) => { + const result = await updateAccountStore(store => { + store.accounts = store.accounts.filter(account => account.id !== accountId); + if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null; + return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; + }); + requestBackgroundSync(accountId); + requestBackgroundSync(); + return result; +}); + +registerIpcHandler('mail:update-account', async (_event, accountId, input) => { + const existing = await readAccount(accountId); + if (!existing) throw new Error('That mail account is no longer available.'); + const account = normalizeAccount({ ...existing, ...input, password: String(input?.password || '') || existing.password }); + account.id = existing.id; + try { + const status = await connectMail(account); + const savedAccount = await updateAccountStore(store => { + const current = store.accounts.find(item => item.id === existing.id); + if (!current) throw new Error('That mail account is no longer available.'); + const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost; + store.accounts = store.accounts.map(item => item.id === existing.id + ? { + ...account, + syncState: endpointChanged ? undefined : current.syncState, + snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []), + ruleLabels: endpointChanged ? {} : (current.ruleLabels || {}) + } + : item); + return store.accounts.find(item => item.id === existing.id); + }); + requestBackgroundSync(existing.id); + return { ...publicAccount(savedAccount), ...status }; + } catch (error) { + throw new Error(`Could not update the mailbox: ${error.message}`); + } +}); + +registerIpcHandler('mail:connect', async (_event, input) => { + const account = normalizeAccount(input); + try { + const status = await connectMail(account); + const saved = await saveAccount(account); + requestBackgroundSync(saved.id); + return { ok: true, ...publicAccount(saved), ...status }; + } catch (error) { + throw new Error(`Could not connect to the mailbox: ${error.message}`); + } +}); + +registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before syncing.'); + const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']); + const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder; + const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX) + ? selectedFolder : 'Inbox'; + const { folder: _filterFolder, ...criteria } = filters; + try { + await flushMailOutbox(account); + return await fetchMailbox(account, folder, offset, 20, criteria); + } catch (error) { + if (!isConnectivityFailure(error)) throw error; + const cached = cachedMailbox(account, folder, offset, 20, criteria); + if (!cached.total) throw error; + return cached; + } +}); + +registerIpcHandler('mail:list-folders', async () => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before listing folders.'); + const client = imapClient(account); + try { + await client.connect(); + return { folders: await listCustomFolders(client) }; + } catch (error) { + if (isConnectivityFailure(error)) return { folders: [], offline: true }; + throw error; + } finally { + if (client.usable) await client.logout().catch(() => {}); + } +}); + +registerIpcHandler('mail:create-folder', async (_event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before creating folders.'); + const name = validFolderName(input?.name); + const client = imapClient(account); + try { + await client.connect(); + const existing = await client.list(); + if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) { + throw new Error('A folder with that name already exists.'); + } + const created = await client.mailboxCreate(name); + await client.mailboxSubscribe(created.path).catch(() => {}); + return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) }; + } catch (error) { + if (error.message === 'A folder with that name already exists.') throw error; + throw new Error(`Could not create the folder: ${error.message}`); + } finally { + if (client.usable) await client.logout().catch(() => {}); + } +}); + +registerIpcHandler('mail:list-drafts', async () => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before opening drafts.'); + return { drafts: account.drafts || [], offline: true }; +}); + +registerIpcHandler('mail:save-draft', async (_event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before saving drafts.'); + const draft = { + id: String(input?.id || randomUUID()), + to: String(input?.to || '').slice(0, 4000), + cc: String(input?.cc || '').slice(0, 4000), + subject: String(input?.subject || '').slice(0, 998), + text: String(input?.text || '').slice(0, 500000), + attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)), + updatedAt: Date.now() + }; + await updateAccountStore(store => { + const saved = store.accounts.find(item => item.id === account.id); + if (!saved) throw new Error('That mail account is no longer available.'); + const drafts = saved.drafts || []; + saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500); + }); + return draft; +}); + +registerIpcHandler('mail:delete-draft', async (_event, id) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before deleting drafts.'); + await updateAccountStore(store => { + const saved = store.accounts.find(item => item.id === account.id); + if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id); + }); + return { ok: true }; +}); + +registerIpcHandler('mail:set-snooze', async (_event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before setting a reminder.'); + const uid = Number(input?.uid); + const folder = String(input?.sourceFolder || input?.folder || 'Inbox'); + if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); + if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.'); + const dueAt = input?.dueAt == null ? null : Number(input.dueAt); + if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) { + throw new Error('Choose a reminder time in the future.'); + } + await updateAccountStore(store => { + const saved = store.accounts.find(item => item.id === account.id); + if (!saved) throw new Error('That mail account is no longer available.'); + const snoozes = saved.snoozedMessages || []; + const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder)); + if (dueAt != null) { + remaining.push({ + uid, + folder, + dueAt, + subject: String(input.subject || '').slice(0, 200) + }); + } + saved.snoozedMessages = remaining; + }); + sendMailSyncUpdate({ + accountId: account.id, + foldersChanged: ['Snoozed', folder] + }); + return { ok: true, snoozed: dueAt != null }; +}); + +registerIpcHandler('mail:update-message', async (_event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before changing messages.'); + try { + return await applyMessageAction(account, input); + } catch (error) { + if (!isConnectivityFailure(error)) throw error; + return mailOutbox.queueMessageAction(account, input); + } +}); + +// Encrypted messages keep their attachments inside the encrypted payload. +async function parseForAttachments(source) { + const parsed = await simpleParser(source); + const kind = pgpMail.detect(parsed); + if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed; + try { + return (await pgpMail.decrypt(parsed)).parsed; + } catch (error) { + if (error instanceof PgpError) throw new Error(error.code === 'PASSPHRASE_REQUIRED' ? 'Open the message and unlock it before using its attachments.' : error.message); + throw error; + } +} +const attachmentService = createAttachmentService({ imapClient, folderPath, parseForAttachments }); + +registerIpcHandler('mail:save-attachment', async (event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before downloading attachments.'); + const parent = BrowserWindow.fromWebContents(event.sender); + return attachmentService.saveAttachment(account, input, options => dialog.showSaveDialog(parent, options)); +}); + +registerIpcHandler('mail:preview-attachment', async (_event, input) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before previewing attachments.'); + return attachmentService.previewAttachment(account, input); +}); + + +registerIpcHandler('mail:open-external', async (event, rawUrl) => { + let target; + try { + target = new URL(String(rawUrl || '')); + } catch { + throw new Error('This link is not a valid web address.'); + } + if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) { + throw new Error('Only standard web links can be opened from mail.'); + } + const parent = BrowserWindow.fromWebContents(event.sender); + const confirmation = await dialog.showMessageBox(parent, { + type: 'warning', + title: 'Open external link?', + message: 'Email links can lead to fake sign-in pages or harmful content.', + detail: `Check the full address before continuing:\n${target.href}`, + buttons: ['Cancel', 'Open link'], + defaultId: 0, + cancelId: 0, + noLink: true + }); + if (confirmation.response !== 1) return { opened: false }; + await shell.openExternal(target.href); + return { opened: true }; +}); + +registerIpcHandler('mail:sync-inbox', async () => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before syncing.'); + return fetchMailbox(account, 'Inbox'); +}); + + +registerIpcHandler('mail:send', async (event, message) => { + const account = await readAccount(); + if (!account) throw new Error('Add a mail account before sending.'); + const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null; + const queuedMessage = { + to: message.to, + cc: message.cc, + subject: message.subject, + text: message.text, + displayName: message.displayName, + messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`, + attachments: message.attachments + }; + const attachments = normalizeOutgoingAttachments(message?.attachments); + queuedMessage.attachments = serializeOutgoingAttachments(attachments); + delete queuedMessage.pgp; + if (!pgpOptions?.encrypt) { + const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean); + const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email }); + if (status.recipients.length && !status.missing.length) { + const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), { + type: 'warning', + buttons: ['Cancel', 'Send anyway'], + defaultId: 0, + cancelId: 0, + title: 'Send without encryption?', + message: 'Public keys are available for all recipients.', + detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.', + noLink: true + }); + if (response !== 1) throw new Error('Plaintext send cancelled.'); + } + } + if (pgpOptions) { + // Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox. + const signature = String(account.signature || '').slice(0, 5000); + const body = String(queuedMessage.text || '').slice(0, 500000); + const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email; + try { + const built = await pgpMail.build({ + from: { name: fromName, address: account.email }, + to: queuedMessage.to, + cc: queuedMessage.cc, + subject: String(queuedMessage.subject || '(no subject)').slice(0, 998), + text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, + messageId: queuedMessage.messageId, + encrypt: Boolean(pgpOptions.encrypt), + sign: Boolean(pgpOptions.sign), + passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null, + attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content })) + }); + queuedMessage.rawBase64 = built.raw.toString('base64'); + queuedMessage.envelope = built.envelope; + queuedMessage.text = ''; + queuedMessage.attachments = []; + } catch (error) { + if (error instanceof PgpError) return pgpFailure(error); + throw error; + } + } + try { + return await sendMailNow(account, queuedMessage); + } catch (error) { + if (!isConnectivityFailure(error)) throw error; + await updateAccountStore(store => { + const saved = store.accounts.find(item => item.id === account.id); + if (!saved) throw new Error('That mail account is no longer available.'); + saved.mailOutbox = saved.mailOutbox || []; + saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() }); + }); + return { ok: true, queued: true }; + } +}); + +registerIpcHandler('mail:disconnect', async (_event, accountId) => { + const store = await readAccountStore(); + if (!store) return { accounts: [], activeId: null }; + if (accountId) { + store.accounts = store.accounts.filter(account => account.id !== accountId); + } else { + store.accounts = []; + } + if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true }); + else { + if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id; + await saveAccountStore(store); + } + return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; +}); + + +} + +module.exports = { registerMailIpcHandlers }; diff --git a/desktop/mail/connectivity.cjs b/desktop/mail/connectivity.cjs new file mode 100644 index 0000000..6543be6 --- /dev/null +++ b/desktop/mail/connectivity.cjs @@ -0,0 +1,10 @@ +function isConnectivityFailure(error) { + const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']); + for (let current = error; current; current = current.cause) { + if (networkCodes.has(current.code)) return true; + if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true; + } + return false; +} + +module.exports = { isConnectivityFailure }; diff --git a/desktop/main.cjs b/desktop/main.cjs index 7df914e..21ba720 100644 --- a/desktop/main.cjs +++ b/desktop/main.cjs @@ -28,16 +28,17 @@ const { createFolderService } = require('./mail/folders.cjs'); const { createMailReader } = require('./mail/read-service.cjs'); const { createMessageActionService } = require('./mail/action-service.cjs'); const { createMailOutboxService } = require('./mail/outbox-service.cjs'); -const { createAttachmentService } = require('./mail/attachment-service.cjs'); const { createMailboxSyncService } = require('./mail/sync-service.cjs'); const { createBackgroundSyncCoordinator } = require('./mail/sync-coordinator.cjs'); const { createIdleWatcherManager } = require('./mail/idle-watcher-manager.cjs'); const { createSnoozeReminderService } = require('./mail/snooze-reminder-service.cjs'); +const { isConnectivityFailure } = require('./mail/connectivity.cjs'); const { assertTrustedIpcSender, isTrustedApplicationUrl } = require('./security/ipc-sender.cjs'); const { validateIpcArguments } = require('./security/ipc-arguments.cjs'); const { assertDavObjectReference } = require('./dav/remote-reference.cjs'); const { pgpFailure, registerPgpIpcHandlers } = require('./ipc/pgp.cjs'); const { registerDavIpcHandlers } = require('./ipc/dav.cjs'); +const { registerMailIpcHandlers } = require('./ipc/mail.cjs'); const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc'); const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc'); @@ -385,251 +386,6 @@ function showNewMailNotification(account, count) { registerIpcHandler('app:get-version', () => app.getVersion()); -registerIpcHandler('mail:get-account', async () => { - const account = await readAccount(); - return account ? publicAccount(account) : null; -}); - -registerIpcHandler('mail:list-accounts', async () => { - const store = (await readAccountStore()) || { accounts: [], activeId: null }; - return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; -}); - -registerIpcHandler('mail:select-account', async (_event, accountId) => { - const account = await updateAccountStore(store => { - const selected = store.accounts.find(item => item.id === accountId); - if (!selected) throw new Error('That mail account is no longer available.'); - store.activeId = selected.id; - return selected; - }); - requestBackgroundSync(); - return publicAccount(account); -}); - -registerIpcHandler('mail:remove-account', async (_event, accountId) => { - const result = await updateAccountStore(store => { - store.accounts = store.accounts.filter(account => account.id !== accountId); - if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null; - return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; - }); - requestBackgroundSync(accountId); - requestBackgroundSync(); - return result; -}); - -registerIpcHandler('mail:update-account', async (_event, accountId, input) => { - const existing = await readAccount(accountId); - if (!existing) throw new Error('That mail account is no longer available.'); - const account = normalizeAccount({ ...existing, ...input, password: String(input?.password || '') || existing.password }); - account.id = existing.id; - try { - const status = await connectMail(account); - const savedAccount = await updateAccountStore(store => { - const current = store.accounts.find(item => item.id === existing.id); - if (!current) throw new Error('That mail account is no longer available.'); - const endpointChanged = current.email !== account.email || current.imapHost !== account.imapHost; - store.accounts = store.accounts.map(item => item.id === existing.id - ? { - ...account, - syncState: endpointChanged ? undefined : current.syncState, - snoozedMessages: endpointChanged ? [] : (current.snoozedMessages || []), - ruleLabels: endpointChanged ? {} : (current.ruleLabels || {}) - } - : item); - return store.accounts.find(item => item.id === existing.id); - }); - requestBackgroundSync(existing.id); - return { ...publicAccount(savedAccount), ...status }; - } catch (error) { - throw new Error(`Could not update the mailbox: ${error.message}`); - } -}); - -registerIpcHandler('mail:connect', async (_event, input) => { - const account = normalizeAccount(input); - try { - const status = await connectMail(account); - const saved = await saveAccount(account); - requestBackgroundSync(saved.id); - return { ok: true, ...publicAccount(saved), ...status }; - } catch (error) { - throw new Error(`Could not connect to the mailbox: ${error.message}`); - } -}); - -registerIpcHandler('mail:sync-folder', async (_event, requestedFolder, offset = 0, filters = {}) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before syncing.'); - const allowedFolders = new Set(['Inbox', 'Sent', 'Archive', 'Trash', 'Starred', 'Snoozed']); - const selectedFolder = allowedFolders.has(filters.folder) ? filters.folder : requestedFolder; - const folder = allowedFolders.has(selectedFolder) || String(selectedFolder).startsWith(CUSTOM_FOLDER_PREFIX) - ? selectedFolder : 'Inbox'; - const { folder: _filterFolder, ...criteria } = filters; - try { - await flushMailOutbox(account); - return await fetchMailbox(account, folder, offset, 20, criteria); - } catch (error) { - if (!isConnectivityFailure(error)) throw error; - const cached = cachedMailbox(account, folder, offset, 20, criteria); - if (!cached.total) throw error; - return cached; - } -}); - -registerIpcHandler('mail:list-folders', async () => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before listing folders.'); - const client = imapClient(account); - try { - await client.connect(); - return { folders: await listCustomFolders(client) }; - } catch (error) { - if (isConnectivityFailure(error)) return { folders: [], offline: true }; - throw error; - } finally { - if (client.usable) await client.logout().catch(() => {}); - } -}); - -registerIpcHandler('mail:create-folder', async (_event, input) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before creating folders.'); - const name = validFolderName(input?.name); - const client = imapClient(account); - try { - await client.connect(); - const existing = await client.list(); - if (existing.some(mailbox => mailbox.path.toLowerCase() === name.toLowerCase())) { - throw new Error('A folder with that name already exists.'); - } - const created = await client.mailboxCreate(name); - await client.mailboxSubscribe(created.path).catch(() => {}); - return { ok: true, folder: { name, path: created.path, id: CUSTOM_FOLDER_PREFIX + created.path }, folders: await listCustomFolders(client) }; - } catch (error) { - if (error.message === 'A folder with that name already exists.') throw error; - throw new Error(`Could not create the folder: ${error.message}`); - } finally { - if (client.usable) await client.logout().catch(() => {}); - } -}); - -registerIpcHandler('mail:list-drafts', async () => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before opening drafts.'); - return { drafts: account.drafts || [], offline: true }; -}); - -registerIpcHandler('mail:save-draft', async (_event, input) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before saving drafts.'); - const draft = { - id: String(input?.id || randomUUID()), - to: String(input?.to || '').slice(0, 4000), - cc: String(input?.cc || '').slice(0, 4000), - subject: String(input?.subject || '').slice(0, 998), - text: String(input?.text || '').slice(0, 500000), - attachments: serializeOutgoingAttachments(normalizeOutgoingAttachments(input?.attachments)), - updatedAt: Date.now() - }; - await updateAccountStore(store => { - const saved = store.accounts.find(item => item.id === account.id); - if (!saved) throw new Error('That mail account is no longer available.'); - const drafts = saved.drafts || []; - saved.drafts = [draft, ...drafts.filter(item => item.id !== draft.id)].slice(0, 500); - }); - return draft; -}); - -registerIpcHandler('mail:delete-draft', async (_event, id) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before deleting drafts.'); - await updateAccountStore(store => { - const saved = store.accounts.find(item => item.id === account.id); - if (saved) saved.drafts = (saved.drafts || []).filter(draft => draft.id !== id); - }); - return { ok: true }; -}); - -registerIpcHandler('mail:set-snooze', async (_event, input) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before setting a reminder.'); - const uid = Number(input?.uid); - const folder = String(input?.sourceFolder || input?.folder || 'Inbox'); - if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); - if (!['Inbox', 'Sent', 'Archive', 'Trash'].includes(folder)) throw new Error('That mailbox cannot be snoozed.'); - const dueAt = input?.dueAt == null ? null : Number(input.dueAt); - if (dueAt != null && (!Number.isFinite(dueAt) || dueAt <= Date.now())) { - throw new Error('Choose a reminder time in the future.'); - } - await updateAccountStore(store => { - const saved = store.accounts.find(item => item.id === account.id); - if (!saved) throw new Error('That mail account is no longer available.'); - const snoozes = saved.snoozedMessages || []; - const remaining = snoozes.filter(item => !(Number(item.uid) === uid && item.folder === folder)); - if (dueAt != null) { - remaining.push({ - uid, - folder, - dueAt, - subject: String(input.subject || '').slice(0, 200) - }); - } - saved.snoozedMessages = remaining; - }); - sendMailSyncUpdate({ - accountId: account.id, - foldersChanged: ['Snoozed', folder] - }); - return { ok: true, snoozed: dueAt != null }; -}); - -function isConnectivityFailure(error) { - const networkCodes = new Set(['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'ENETUNREACH', 'EHOSTUNREACH', 'ESOCKET']); - for (let current = error; current; current = current.cause) { - if (networkCodes.has(current.code)) return true; - if (/network is unreachable|connection timed out|connection refused|could not resolve|socket hang up/i.test(current.message || '')) return true; - } - return false; -} - -registerIpcHandler('mail:update-message', async (_event, input) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before changing messages.'); - try { - return await applyMessageAction(account, input); - } catch (error) { - if (!isConnectivityFailure(error)) throw error; - return mailOutbox.queueMessageAction(account, input); - } -}); - -// Encrypted messages keep their attachments inside the encrypted payload. -async function parseForAttachments(source) { - const parsed = await simpleParser(source); - const kind = pgpMail.detect(parsed); - if (kind !== 'encrypted-mime' && kind !== 'encrypted-inline') return parsed; - try { - return (await pgpMail.decrypt(parsed)).parsed; - } catch (error) { - if (error instanceof PgpError) throw new Error(error.code === 'PASSPHRASE_REQUIRED' ? 'Open the message and unlock it before using its attachments.' : error.message); - throw error; - } -} -const attachmentService = createAttachmentService({ imapClient, folderPath, parseForAttachments }); - -registerIpcHandler('mail:save-attachment', async (event, input) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before downloading attachments.'); - const parent = BrowserWindow.fromWebContents(event.sender); - return attachmentService.saveAttachment(account, input, options => dialog.showSaveDialog(parent, options)); -}); - -registerIpcHandler('mail:preview-attachment', async (_event, input) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before previewing attachments.'); - return attachmentService.previewAttachment(account, input); -}); - registerPgpIpcHandlers({ registerIpcHandler, BrowserWindow, @@ -651,38 +407,6 @@ registerPgpIpcHandlers({ simpleParser, extractMailContent }); -registerIpcHandler('mail:open-external', async (event, rawUrl) => { - let target; - try { - target = new URL(String(rawUrl || '')); - } catch { - throw new Error('This link is not a valid web address.'); - } - if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) { - throw new Error('Only standard web links can be opened from mail.'); - } - const parent = BrowserWindow.fromWebContents(event.sender); - const confirmation = await dialog.showMessageBox(parent, { - type: 'warning', - title: 'Open external link?', - message: 'Email links can lead to fake sign-in pages or harmful content.', - detail: `Check the full address before continuing:\n${target.href}`, - buttons: ['Cancel', 'Open link'], - defaultId: 0, - cancelId: 0, - noLink: true - }); - if (confirmation.response !== 1) return { opened: false }; - await shell.openExternal(target.href); - return { opened: true }; -}); - -registerIpcHandler('mail:sync-inbox', async () => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before syncing.'); - return fetchMailbox(account, 'Inbox'); -}); - const { sendMailNow } = createMailSender({ smtpTransport, imapClient, findSentMailbox }); const mailOutbox = createMailOutboxService({ sendMailNow, @@ -723,95 +447,42 @@ const { requestBackgroundSync, runBackgroundSync } = createBackgroundSyncCoordin retryIntervalMs: backgroundRetryIntervalMs }); idleWatcherManager.setRequestBackgroundSync(requestBackgroundSync); - -registerIpcHandler('mail:send', async (event, message) => { - const account = await readAccount(); - if (!account) throw new Error('Add a mail account before sending.'); - const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null; - const queuedMessage = { - to: message.to, - cc: message.cc, - subject: message.subject, - text: message.text, - displayName: message.displayName, - messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`, - attachments: message.attachments - }; - const attachments = normalizeOutgoingAttachments(message?.attachments); - queuedMessage.attachments = serializeOutgoingAttachments(attachments); - delete queuedMessage.pgp; - if (!pgpOptions?.encrypt) { - const recipients = [queuedMessage.to, queuedMessage.cc].filter(Boolean); - const status = await pgpMail.recipientStatus(recipients, { sign: Boolean(pgpOptions?.sign), from: account.email }); - if (status.recipients.length && !status.missing.length) { - const { response } = await dialog.showMessageBox(BrowserWindow.fromWebContents(event.sender), { - type: 'warning', - buttons: ['Cancel', 'Send anyway'], - defaultId: 0, - cancelId: 0, - title: 'Send without encryption?', - message: 'Public keys are available for all recipients.', - detail: 'This message is about to be sent without encryption. Continue only if you explicitly want to send it in plaintext.', - noLink: true - }); - if (response !== 1) throw new Error('Plaintext send cancelled.'); - } - } - if (pgpOptions) { - // Encrypt before sending or queueing so plaintext and passphrases are never stored in the outbox. - const signature = String(account.signature || '').slice(0, 5000); - const body = String(queuedMessage.text || '').slice(0, 500000); - const fromName = String(account.displayName || queuedMessage.displayName || account.email).replace(/[\r\n]+/g, ' ').trim().slice(0, 80) || account.email; - try { - const built = await pgpMail.build({ - from: { name: fromName, address: account.email }, - to: queuedMessage.to, - cc: queuedMessage.cc, - subject: String(queuedMessage.subject || '(no subject)').slice(0, 998), - text: signature ? `${body}${body.trim() ? '\n\n' : ''}${signature}`.slice(0, 505000) : body, - messageId: queuedMessage.messageId, - encrypt: Boolean(pgpOptions.encrypt), - sign: Boolean(pgpOptions.sign), - passphrase: typeof pgpOptions.passphrase === 'string' && pgpOptions.passphrase ? pgpOptions.passphrase : null, - attachments: attachments.map(({ filename, contentType, content }) => ({ filename, contentType, content })) - }); - queuedMessage.rawBase64 = built.raw.toString('base64'); - queuedMessage.envelope = built.envelope; - queuedMessage.text = ''; - queuedMessage.attachments = []; - } catch (error) { - if (error instanceof PgpError) return pgpFailure(error); - throw error; - } - } - try { - return await sendMailNow(account, queuedMessage); - } catch (error) { - if (!isConnectivityFailure(error)) throw error; - await updateAccountStore(store => { - const saved = store.accounts.find(item => item.id === account.id); - if (!saved) throw new Error('That mail account is no longer available.'); - saved.mailOutbox = saved.mailOutbox || []; - saved.mailOutbox.push({ id: randomUUID(), type: 'send', data: queuedMessage, createdAt: Date.now() }); - }); - return { ok: true, queued: true }; - } -}); - -registerIpcHandler('mail:disconnect', async (_event, accountId) => { - const store = await readAccountStore(); - if (!store) return { accounts: [], activeId: null }; - if (accountId) { - store.accounts = store.accounts.filter(account => account.id !== accountId); - } else { - store.accounts = []; - } - if (!store.accounts.length) await fs.rm(credentialsPath(), { force: true }); - else { - if (!store.accounts.some(account => account.id === store.activeId)) store.activeId = store.accounts[0].id; - await saveAccountStore(store); - } - return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; +registerMailIpcHandlers({ + registerIpcHandler, + BrowserWindow, + dialog, + shell, + fs, + credentialsPath, + readAccount, + readAccountStore, + saveAccountStore, + updateAccountStore, + saveAccount, + publicAccount, + normalizeAccount, + connectMail, + requestBackgroundSync, + CUSTOM_FOLDER_PREFIX, + flushMailOutbox, + fetchMailbox, + cachedMailbox, + listCustomFolders, + imapClient, + validFolderName, + isConnectivityFailure, + randomUUID, + serializeOutgoingAttachments, + normalizeOutgoingAttachments, + sendMailSyncUpdate, + applyMessageAction, + mailOutbox, + pgpMail, + PgpError, + simpleParser, + folderPath, + sendMailNow, + pgpFailure }); registerDavIpcHandlers({ diff --git a/package-lock.json b/package-lock.json index 7e30c2d..af4f827 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ep-mail", - "version": "0.4.11", + "version": "0.4.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ep-mail", - "version": "0.4.11", + "version": "0.4.12", "dependencies": { "@capacitor/android": "^8.5.2", "@capacitor/core": "^8.5.2", diff --git a/package.json b/package.json index 4992e70..47d1c06 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ep-mail", - "version": "0.4.11", + "version": "0.4.12", "private": true, "description": "Eternity Project mail client", "homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client", diff --git a/tests/build-version.test.cjs b/tests/build-version.test.cjs new file mode 100644 index 0000000..778135c --- /dev/null +++ b/tests/build-version.test.cjs @@ -0,0 +1,34 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const root = path.resolve(__dirname, '..'); +const packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); +const packageLock = JSON.parse(fs.readFileSync(path.join(root, 'package-lock.json'), 'utf8')); +const androidBuild = fs.readFileSync(path.join(root, 'android', 'app', 'build.gradle'), 'utf8'); +const buildAll = fs.readFileSync(path.join(root, 'scripts', 'build-all.ps1'), 'utf8'); +const desktopWorkflow = fs.readFileSync(path.join(root, '.github', 'workflows', 'desktop-build.yml'), 'utf8'); + +test('package metadata and lockfile share one release version', () => { + assert.equal(packageLock.version, packageJson.version); + assert.equal(packageLock.packages[''].version, packageJson.version); + assert.match(packageJson.version, /^\d+\.\d+\.\d+$/); +}); + +test('Android version name and code derive from the canonical package version', () => { + assert.match(androidBuild, /parse\(file\("\.\.\/\.\.\/package\.json"\)\)\.version/); + assert.match(androidBuild, /versionName appVersion/); + assert.match(androidBuild, /versionCode appVersionParts\[0\] \* 10000 \+ appVersionParts\[1\] \* 100 \+ appVersionParts\[2\]/); + + const parts = packageJson.version.split('.').map(Number); + const expectedCode = parts[0] * 10000 + parts[1] * 100 + parts[2]; + assert.ok(Number.isSafeInteger(expectedCode) && expectedCode > 0); + assert.ok(parts[1] < 100 && parts[2] < 100, 'update the Android versionCode mapping before minor or patch reaches 100'); +}); + +test('release scripts and desktop artifact labels use package.json version', () => { + assert.match(buildAll, /package\.json/); + assert.match(desktopWorkflow, /require\('\.\/package\.json'\)\.version/); + assert.match(desktopWorkflow, /-v\$\{\{ steps\.app-version\.outputs\.version \}\}/); +}); diff --git a/tests/mail-ipc-registration.test.cjs b/tests/mail-ipc-registration.test.cjs new file mode 100644 index 0000000..1772543 --- /dev/null +++ b/tests/mail-ipc-registration.test.cjs @@ -0,0 +1,54 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { registerMailIpcHandlers } = require('../desktop/ipc/mail.cjs'); + +test('registers mail/account IPC handlers through the shared boundary', () => { + const registered = []; + const stub = () => {}; + registerMailIpcHandlers({ + registerIpcHandler(channel, handler) { registered.push({ channel, handler }); }, + BrowserWindow: { fromWebContents: stub }, + dialog: { showSaveDialog: stub, showMessageBox: stub }, + shell: { openExternal: stub }, + fs: { writeFile: stub, rm: stub }, + credentialsPath: stub, + readAccount: stub, + readAccountStore: stub, + saveAccountStore: stub, + updateAccountStore: stub, + saveAccount: stub, + publicAccount: stub, + normalizeAccount: stub, + connectMail: stub, + requestBackgroundSync: stub, + CUSTOM_FOLDER_PREFIX: 'Folder:', + flushMailOutbox: stub, + fetchMailbox: stub, + cachedMailbox: stub, + listCustomFolders: stub, + imapClient: stub, + validFolderName: stub, + isConnectivityFailure: stub, + randomUUID: stub, + serializeOutgoingAttachments: stub, + normalizeOutgoingAttachments: stub, + sendMailSyncUpdate: stub, + applyMessageAction: stub, + mailOutbox: { queueMessageAction: stub }, + pgpMail: { detect: stub, decrypt: stub, recipientStatus: stub, build: stub }, + PgpError: class PgpError extends Error {}, + simpleParser: stub, + folderPath: stub, + sendMailNow: stub, + pgpFailure: stub + }); + + assert.deepEqual(registered.map(item => item.channel).sort(), [ + 'mail:connect', 'mail:create-folder', 'mail:delete-draft', 'mail:disconnect', + 'mail:get-account', 'mail:list-accounts', 'mail:list-drafts', 'mail:list-folders', + 'mail:open-external', 'mail:preview-attachment', 'mail:remove-account', 'mail:save-attachment', + 'mail:save-draft', 'mail:select-account', 'mail:send', 'mail:set-snooze', + 'mail:sync-folder', 'mail:sync-inbox', 'mail:update-account', 'mail:update-message' + ]); + assert.ok(registered.every(item => typeof item.handler === 'function')); +});