const { app, BrowserWindow, shell, ipcMain, safeStorage, dialog } = require('electron'); const path = require('node:path'); const fs = require('node:fs/promises'); const { ImapFlow } = require('imapflow'); const nodemailer = require('nodemailer'); const { simpleParser } = require('mailparser'); const { randomUUID } = require('node:crypto'); const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.enc'); 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(); if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || !password || !imapHost || !smtpHost) { throw new Error('Enter a valid email, password, and both mail server names.'); } return { email, password, imapHost, smtpHost, imapPort: 143, smtpPort: 587 }; } function imapClient(account) { return new ImapFlow({ host: account.imapHost, port: account.imapPort, secure: false, doSTARTTLS: true, auth: { user: account.email, pass: account.password }, tls: { rejectUnauthorized: true }, logger: false, connectionTimeout: 15000, greetingTimeout: 10000, socketTimeout: 20000 }); } function smtpTransport(account) { return nodemailer.createTransport({ host: account.smtpHost, port: account.smtpPort, secure: false, requireTLS: true, auth: { user: account.email, pass: account.password }, tls: { rejectUnauthorized: true, servername: account.smtpHost }, connectionTimeout: 15000, greetingTimeout: 10000, socketTimeout: 20000 }); } async function readAccountStore() { try { if (!safeStorage.isEncryptionAvailable()) throw new Error('OS credential storage is unavailable.'); 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; } } async function saveAccountStore(store) { 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); } async function readAccount(accountId = null) { const store = await readAccountStore(); if (!store?.accounts.length) return null; return store.accounts.find(account => account.id === (accountId || store.activeId)) || null; } function publicAccount(account) { return { id: account.id, email: account.email, imapHost: account.imapHost, smtpHost: account.smtpHost }; } async function saveAccount(account) { const store = (await readAccountStore()) || { accounts: [], activeId: null }; const existing = store.accounts.find(item => item.email.toLowerCase() === account.email.toLowerCase() && item.imapHost.toLowerCase() === account.imapHost.toLowerCase()); const saved = { ...account, id: existing?.id || randomUUID() }; store.accounts = [...store.accounts.filter(item => item.id !== saved.id), saved]; store.activeId = saved.id; await saveAccountStore(store); return saved; } async function connectMail(account) { const client = imapClient(account); let transport; try { await client.connect(); const mailbox = await client.mailboxOpen('INBOX', { readOnly: true }); transport = smtpTransport(account); await transport.verify(); return { mailbox: mailbox.name, messages: mailbox.exists }; } finally { if (transport) transport.close(); if (client.usable) await client.logout().catch(() => {}); } } 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 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) throw new Error('This folder is not available on the mail server.'); return findSpecialMailbox(client, ...definition.slice(0, 2), createIfMissing ? definition[2] : null); } async function fetchMailbox(account, folder = 'Inbox', offset = 0, limit = 20) { 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 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) continue; const parsed = await simpleParser(item.source); const sender = parsed.from?.value?.[0]; const bodyText = String(parsed.text || '').replace(/\r/g, '').trim(); 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 date = parsed.date || item.internalDate || new Date(); messages.push({ id: Number(item.uid), initials: (sender?.name || sender?.address || '?').split(/[\s@]+/).filter(Boolean).map(word => word[0]).join('').slice(0, 2).toUpperCase(), color: '#dce6df', sender: sender?.name || sender?.address || 'Unknown sender', email: sender?.address || '', subject: parsed.subject || '(no subject)', snippet: (bodyText || parsed.subject || '').replace(/\s+/g, ' ').slice(0, 180), time: new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' }).format(date), date: new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date), unread: !item.flags?.has('\\Seen'), star: item.flags?.has('\\Flagged') || false, tags: [folder], sent: folder === 'Sent', archived: folder === 'Archive', deleted: folder === 'Trash', body, uid: Number(item.uid), attachments: (parsed.attachments || []).map(file => ({ filename: file.filename || 'attachment', size: file.size || 0 })), attachment: parsed.attachments?.[0]?.filename || null, size: parsed.attachments?.[0]?.size ? `${(parsed.attachments[0].size / 1048576).toFixed(1)} MB` : '' }); } return { messages, total: mailbox.exists, start: first, end: Math.min(end, mailbox.exists), folder }; } finally { if (client.usable) await client.logout().catch(() => {}); } } ipcMain.handle('mail:get-account', async () => { const account = await readAccount(); return account ? publicAccount(account) : null; }); ipcMain.handle('mail:list-accounts', async () => { const store = (await readAccountStore()) || { accounts: [], activeId: null }; return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; }); ipcMain.handle('mail:select-account', async (_event, accountId) => { const store = await readAccountStore(); const account = store?.accounts.find(item => item.id === accountId); if (!account) throw new Error('That mail account is no longer available.'); store.activeId = account.id; await saveAccountStore(store); return publicAccount(account); }); ipcMain.handle('mail:remove-account', async (_event, accountId) => { const store = await readAccountStore(); if (!store) return { accounts: [], activeId: null }; store.accounts = store.accounts.filter(account => account.id !== accountId); if (store.activeId === accountId) store.activeId = store.accounts[0]?.id || null; if (store.accounts.length) await saveAccountStore(store); else await fs.rm(credentialsPath(), { force: true }); return { accounts: store.accounts.map(publicAccount), activeId: store.activeId }; }); ipcMain.handle('mail:connect', async (_event, input) => { const account = normalizeAccount(input); try { const status = await connectMail(account); const saved = await saveAccount(account); return { ok: true, ...publicAccount(saved), ...status }; } catch (error) { throw new Error(`Could not connect to the mailbox: ${error.message}`); } }); ipcMain.handle('mail:sync-folder', async (_event, requestedFolder, offset = 0) => { 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 folder = allowedFolders.has(requestedFolder) ? requestedFolder : 'Inbox'; return fetchMailbox(account, folder, offset); }); ipcMain.handle('mail:update-message', async (_event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before changing messages.'); 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'].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') : await findSpecialMailbox(client, '\\Trash', ['trash', 'deleted items', 'deleted messages'], 'Trash'); if (action === 'delete' && sourcePath === target) await client.messageDelete(uid, { uid: true }); else await client.messageMove(uid, target, { uid: true }); } } finally { lock.release(); } return { ok: true }; } finally { if (client.usable) await client.logout().catch(() => {}); } }); ipcMain.handle('mail:save-attachment', async (event, input) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before downloading attachments.'); const uid = Number(input?.uid); const folder = String(input?.folder || 'Inbox'); const filename = String(input?.filename || 'attachment'); const safeFilename = filename.replace(/[\\/:*?"<>|]/g, '_'); if (!Number.isInteger(uid) || uid < 1) throw new Error('That message could not be identified.'); const client = imapClient(account); try { await client.connect(); const mailboxPath = await folderPath(client, folder); if (!mailboxPath) throw new Error('That mail folder could not be found.'); const lock = await client.getMailboxLock(mailboxPath); try { const item = await client.fetchOne(uid, { uid: true, source: true }, { uid: true }); if (!item?.source) throw new Error('The message is no longer available.'); const parsed = await simpleParser(item.source); const attachment = parsed.attachments?.find(file => (file.filename || 'attachment') === filename) || parsed.attachments?.[0]; if (!attachment) throw new Error('No attachment was found in this message.'); const result = await dialog.showSaveDialog(BrowserWindow.fromWebContents(event.sender), { defaultPath: (attachment.filename || safeFilename).replace(/[\\/:*?"<>|]/g, '_') }); if (result.canceled || !result.filePath) return { canceled: true }; await fs.writeFile(result.filePath, attachment.content); return { saved: true }; } finally { lock.release(); } } finally { if (client.usable) await client.logout().catch(() => {}); } }); ipcMain.handle('mail:sync-inbox', async () => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before syncing.'); return fetchMailbox(account, 'Inbox'); }); ipcMain.handle('mail:send', async (_event, message) => { const account = await readAccount(); if (!account) throw new Error('Add a mail account before sending.'); const to = String(message?.to || '').trim(); if (!to) throw new Error('Add at least one recipient.'); const transport = smtpTransport(account); const sentMessageId = `<${require('node:crypto').randomUUID()}@daybreak-mail.local>`; const messageOptions = { from: { name: account.email, address: account.email }, to, cc: String(message.cc || '').trim() || undefined, subject: String(message.subject || '(no subject)').slice(0, 998), text: String(message.text || '').slice(0, 500000), messageId: sentMessageId }; try { await transport.sendMail(messageOptions); } finally { transport.close(); } let savedToSent = false; const copy = nodemailer.createTransport({ streamTransport: true, buffer: true, newline: 'windows' }); try { const rendered = 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 }; }); ipcMain.handle('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 }; }); function createWindow() { const window = new BrowserWindow({ width: 1440, height: 920, minWidth: 920, minHeight: 680, title: 'Daybreak Mail', backgroundColor: '#f4f5f1', autoHideMenuBar: true, icon: path.join(__dirname, '..', 'icon.svg'), webPreferences: { preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true } }); window.loadFile(path.join(__dirname, '..', 'index.html')); window.webContents.setWindowOpenHandler(({ url }) => { if (url.startsWith('https://') || url.startsWith('mailto:')) shell.openExternal(url); return { action: 'deny' }; }); window.webContents.on('will-navigate', (event, url) => { if (!url.startsWith('file:')) event.preventDefault(); }); } app.whenReady().then(() => { app.setAppUserModelId('studio.daybreak.mail'); createWindow(); app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); }); app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });