433 lines
18 KiB
JavaScript
433 lines
18 KiB
JavaScript
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,
|
|
authorizeOAuthAccount,
|
|
listOAuthProviders,
|
|
requestBackgroundSync,
|
|
CUSTOM_FOLDER_PREFIX,
|
|
flushMailOutbox,
|
|
fetchMailbox,
|
|
cachedMailbox,
|
|
listCustomFolders,
|
|
imapClient,
|
|
validFolderName,
|
|
isConnectivityFailure,
|
|
randomUUID,
|
|
serializeOutgoingAttachments,
|
|
normalizeOutgoingAttachments,
|
|
sendMailSyncUpdate,
|
|
applyMessageAction,
|
|
mailOutbox,
|
|
pgpMail,
|
|
PgpError,
|
|
getMailparser,
|
|
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:list-oauth-providers', async () => listOAuthProviders());
|
|
|
|
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.');
|
|
let account = normalizeAccount({
|
|
...existing,
|
|
...input,
|
|
authMethod: input?.authMethod || existing.authMethod || 'password',
|
|
password: String(input?.password || '') || existing.password || ''
|
|
});
|
|
account.id = existing.id;
|
|
if (account.authMethod === 'oauth2') {
|
|
if (!input?.reauthorizeOAuth && existing.authMethod === 'oauth2' && existing.oauthProvider === account.oauthProvider && existing.oauthRefreshToken) {
|
|
account.oauthAccessToken = existing.oauthAccessToken;
|
|
account.oauthRefreshToken = existing.oauthRefreshToken;
|
|
account.oauthAccessTokenExpiresAt = existing.oauthAccessTokenExpiresAt;
|
|
} else {
|
|
account = await authorizeOAuthAccount(account);
|
|
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) => {
|
|
let account = normalizeAccount(input);
|
|
try {
|
|
if (account.authMethod === 'oauth2') account = await authorizeOAuthAccount(account);
|
|
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 = await 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 = await 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),
|
|
inReplyTo: String(input?.inReplyTo || '').slice(0, 254),
|
|
references: String(input?.references || '').slice(0, 900),
|
|
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 { simpleParser } = await getMailparser();
|
|
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>`,
|
|
inReplyTo: message.inReplyTo,
|
|
references: message.references,
|
|
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,
|
|
inReplyTo: queuedMessage.inReplyTo,
|
|
references: queuedMessage.references,
|
|
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 };
|