import { ImapFlow } from 'imapflow' import { simpleParser } from 'mailparser' import nodemailer from 'nodemailer' import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider' import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, InlineImage, Attachment } from '@shared/types/message' import { SpecialFolderRole } from '@shared/types/folder' import type { Folder } from '@shared/types/folder' import type { AccountConfig, ImapCredentials } from '@shared/types/account' import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention' import { sanitizeHtml } from '../lib/html-sanitizer' import { convertImapMessage } from '../lib/imap-message-mapper' // imapflow MailboxObject type interface ImapMailbox { name: string path: string specialUse?: string folders?: ImapMailbox[] } export class ImapProvider implements IEmailProvider { private client: ImapFlow private connected = false private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null // folderId → last known unseen count for polling private lastUnseenCount = new Map() // uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message private notifiedUids = new Map() private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes // Промис с именем отправителя из Sent-папки; await-ится в sendMessage() private senderNamePromise: Promise = Promise.resolve(null) constructor(private config: AccountConfig) { const creds = config.credentials as ImapCredentials this.client = new ImapFlow({ host: creds.host, port: creds.port, secure: creds.secure, auth: { user: creds.username, pass: creds.password }, logger: false }) } async connect(): Promise { let timeoutId: ReturnType | undefined const timeoutPromise = new Promise((_, reject) => { timeoutId = setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000) }) try { await Promise.race([this.client.connect(), timeoutPromise]) } catch (err) { // Close any socket imapflow opened or is opening (timeout race case) this.client.logout().catch(() => {}) throw err } finally { clearTimeout(timeoutId) } this.connected = true // Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке this.senderNamePromise = this.fetchSenderName().catch(() => null) } async disconnect(): Promise { this.offNewMail() if (this.connected) { try { await this.client.logout() } catch { /* ignore */ } this.connected = false } } isConnected(): boolean { return this.connected } async listFolders(): Promise { // listTree() returns { root: true, folders: ImapMailbox[] } const tree = await this.client.listTree() as { folders?: ImapMailbox[] } const folders = this.convertMailboxArray(tree.folders ?? []) await this.populateUnreadCounts(folders) return { folders } } private async populateUnreadCounts(folders: Folder[]): Promise { // Собираем все папки в плоский список (включая вложенные) const flatten = (list: Folder[]): Folder[] => list.flatMap((f) => [f, ...flatten(f.children)]) const all = flatten(folders) // Параллельные STATUS запросы с concurrency limit 5 const CONCURRENCY = 5 for (let i = 0; i < all.length; i += CONCURRENCY) { const batch = all.slice(i, i + CONCURRENCY) await Promise.all( batch.map(async (folder) => { try { const status = await this.client.status(folder.id, { unseen: true, messages: true }) as { unseen?: number; messages?: number } | null if (status) { folder.unreadCount = status.unseen ?? 0 folder.totalCount = status.messages ?? 0 } } catch { // Некоторые папки могут не поддерживать STATUS } }) ) } } async listMessages(options: MessageListOptions): Promise { const lock = await this.client.getMailboxLock(options.folderId) try { if (options.unseenOnly) { return await this.listUnseenMessages(options) } const total = (this.client.mailbox as { exists?: number })?.exists ?? 0 if (total === 0) return { messages: [], total: 0, unseen: 0 } // IMAP sequence numbers are 1-based, newest = highest number const end = Math.max(1, total - options.offset) const start = Math.max(1, end - options.limit + 1) if (start > total) return { messages: [], total, unseen: 0 } const messages: MessageEnvelope[] = [] for await (const msg of this.client.fetch(`${start}:${end}`, { uid: true, envelope: true, flags: true, bodyStructure: true })) { messages.push(convertImapMessage(msg, options.folderId)) } // Newest first messages.reverse() return { messages, total, unseen: 0 } } finally { lock.release() } } private async listUnseenMessages(options: MessageListOptions): Promise { // Mailbox lock is already held by listMessages caller const uids = await this.client.search({ seen: false }, { uid: true }) as number[] if (!uids || uids.length === 0) return { messages: [], total: 0, unseen: 0 } const total = uids.length // Sort descending — higher UID = newer message const sorted = [...uids].sort((a, b) => b - a) const page = sorted.slice(options.offset, options.offset + options.limit) if (page.length === 0) return { messages: [], total, unseen: total } const uidSet = page.join(',') const messages: MessageEnvelope[] = [] for await (const msg of this.client.fetch(uidSet, { uid: true, envelope: true, flags: true, bodyStructure: true }, { uid: true })) { messages.push(convertImapMessage(msg, options.folderId)) } // Fetch returns ascending order → reverse to newest first messages.sort((a, b) => Number(b.id) - Number(a.id)) return { messages, total, unseen: total } } async fetchMessageBody(folderId: string, messageId: string): Promise { const lock = await this.client.getMailboxLock(folderId) try { // imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится const download = await this.client.download(messageId, undefined, { uid: true }) if (!download?.content) { return { id: messageId, html: null, text: null, references: null, inlineImages: [], attachments: [] } } const parsed = await simpleParser(download.content) const inlineImages: InlineImage[] = [] const attachments: Attachment[] = [] for (const att of parsed.attachments) { if (att.contentDisposition === 'inline' && att.contentId && att.contentType.startsWith('image/')) { inlineImages.push({ cid: att.contentId.replace(/[<>]/g, ''), contentType: att.contentType, data: att.content.toString('base64') }) } else if (att.contentDisposition === 'attachment' || att.filename) { attachments.push({ id: att.checksum ?? att.filename ?? '', filename: att.filename ?? 'attachment', contentType: att.contentType, size: att.size ?? 0 }) } } // References header: mailparser returns string[] — join to space-separated string const refsArray = (parsed as unknown as { references?: string | string[] }).references const references = Array.isArray(refsArray) ? refsArray.join(' ') : (typeof refsArray === 'string' ? refsArray : null) const sanitizedHtml = parsed.html ? sanitizeHtml(parsed.html) : null // Если text/plain части нет — деривируем из HTML (правильно: style/script уже отфильтрованы) const text = parsed.text ?? (parsed.html ? this.htmlToPlainText(parsed.html) : null) return { id: messageId, html: sanitizedHtml, text, references, inlineImages, attachments } } finally { lock.release() } } async downloadAttachment(folderId: string, messageId: string, attachmentId: string): Promise { // TODO: имапфлоу поддерживает частичный download по part-номеру из BODYSTRUCTURE // (client.download(uid, '2', {uid:true})). Оптимизация требует хранить part в Attachment.id // и пробрасывать через IPC. Сейчас скачивается всё письмо целиком. const lock = await this.client.getMailboxLock(folderId) try { const download = await this.client.download(messageId, undefined, { uid: true }) if (!download) throw new Error('Message not found') const parsed = await simpleParser(download.content) const att = parsed.attachments.find( (a) => (a.checksum ?? a.filename ?? '') === attachmentId || a.filename === attachmentId ) if (!att) throw new Error('Attachment not found') return att.content } finally { lock.release() } } async updateFlags(folderId: string, messageIds: string[], flags: Partial): Promise { const lock = await this.client.getMailboxLock(folderId) try { const uidSet = messageIds.join(',') const addFlags: string[] = [] const removeFlags: string[] = [] if (flags.seen === true) addFlags.push('\\Seen') if (flags.seen === false) removeFlags.push('\\Seen') if (flags.flagged === true) addFlags.push('\\Flagged') if (flags.flagged === false) removeFlags.push('\\Flagged') if (flags.answered === true) addFlags.push('\\Answered') if (flags.deleted === true) addFlags.push('\\Deleted') if (addFlags.length > 0) { await this.client.messageFlagsAdd(uidSet, addFlags, { uid: true }) } if (removeFlags.length > 0) { await this.client.messageFlagsRemove(uidSet, removeFlags, { uid: true }) } } finally { lock.release() } } async markAllRead(folderId: string): Promise { const lock = await this.client.getMailboxLock(folderId) try { const uids = await this.client.search({ seen: false }, { uid: true }) as number[] if (!uids || uids.length === 0) return await this.client.messageFlagsAdd(uids.join(','), ['\\Seen'], { uid: true }) } finally { lock.release() } } async deleteMessages(folderId: string, messageIds: string[]): Promise { const lock = await this.client.getMailboxLock(folderId) try { const uidSet = messageIds.join(',') await this.client.messageDelete(uidSet, { uid: true }) } finally { lock.release() } } async enforceRetention(rules: FolderRetentionRule[]): Promise { if (rules.length === 0) return [] const tree = await this.client.listTree() as { folders?: ImapMailbox[] } const folders = this.convertMailboxArray(tree.folders ?? []) const results: RetentionCleanupResult[] = [] await this.enforceRetentionTree(folders, rules, null, results) return results } // inheritedLimit — лимит, унаследованный от ближайшего предка с recursive: true (null — нет ограничения) private async enforceRetentionTree( folders: Folder[], rules: FolderRetentionRule[], inheritedLimit: number | null, results: RetentionCleanupResult[] ): Promise { for (const folder of folders) { const ownRule = rules.find((r) => r.folderId === folder.id) const effectiveLimit = ownRule ? ownRule.maxMessages : inheritedLimit if (effectiveLimit !== null) { try { const deletedUids = await this.trimFolder(folder.id, effectiveLimit) if (deletedUids.length > 0) results.push({ folderId: folder.id, deletedCount: deletedUids.length, deletedUids }) } catch (err) { console.warn(`[IMAP:retention] folder error ${folder.id}:`, (err as Error).message) } } const childInheritedLimit = ownRule ? (ownRule.recursive ? ownRule.maxMessages : null) : inheritedLimit if (folder.children.length > 0) { await this.enforceRetentionTree(folder.children, rules, childInheritedLimit, results) } } } // Удаляет самые старые письма сверх maxMessages. Сортировка по sequence number — // тот же порядок "старое → новое", что используется в listMessages. // Возвращает UID удалённых писем — вызывающий код убирает их из локального поискового индекса. private async trimFolder(folderId: string, maxMessages: number): Promise { const lock = await this.client.getMailboxLock(folderId) try { const total = (this.client.mailbox as { exists?: number })?.exists ?? 0 const excess = total - maxMessages if (excess <= 0) return [] const uidsToDelete: number[] = [] for await (const msg of this.client.fetch(`1:${excess}`, { uid: true })) { uidsToDelete.push((msg as { uid: number }).uid) } if (uidsToDelete.length === 0) return [] await this.client.messageDelete(uidsToDelete.join(','), { uid: true }) return uidsToDelete.map(String) } finally { lock.release() } } async sendMessage(compose: ComposeData): Promise { const creds = this.config.credentials as ImapCredentials // SMTP-настройки: явные или авто-вывод из IMAP-хоста const smtpHost = creds.smtpHost ?? creds.host.replace(/^imap\./i, 'smtp.') const smtpPort = creds.smtpPort ?? 587 const smtpSecure = creds.smtpSecure ?? smtpPort === 465 const transporter = nodemailer.createTransport({ host: smtpHost, port: smtpPort, secure: smtpSecure, auth: { user: creds.username, pass: creds.password }, tls: creds.smtpAllowSelfSigned ? { rejectUnauthorized: false } : undefined }) // Если email хранится без домена (только логин) — достраиваем из IMAP-хоста const emailAddress = this.config.email.includes('@') ? this.config.email : `${this.config.email}@${creds.host.replace(/^[^.]+\./, '')}` // Имя отправителя: await-им промис из connect() — гарантирует что имя готово const senderName = await this.senderNamePromise const displayName = senderName ?? this.config.label const from = displayName ? { name: displayName, address: emailAddress } : emailAddress // Собираем text + html из отдельных частей const fullText = compose.quotedText ? compose.body + '\n\n' + compose.quotedText : compose.body const fullHtml = compose.htmlBody ? ImapProvider.textToHtml(compose.body) + compose.htmlBody : undefined if (process.env.NODE_ENV !== 'production') { console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j', smtpHost, smtpPort, smtpSecure, from, compose.to) } const info = await transporter.sendMail({ from, to: compose.to.join(', '), cc: compose.cc.length ? compose.cc.join(', ') : undefined, bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined, subject: compose.subject, text: fullText, html: fullHtml, inReplyTo: compose.inReplyTo, references: compose.references, attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? [] }) // Сохраняем в папку Sent (best-effort) try { const raw = await this.buildRawMessage(info.messageId ?? '', compose, from) const sentFolder = await this.findSentFolder() if (sentFolder && raw) { await this.client.append(sentFolder, raw, ['\\Seen']) } } catch { /* не критично — письмо уже отправлено */ } } private async findSentFolder(): Promise { try { const tree = await this.client.listTree() as { folders?: ImapMailbox[] } return this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent) } catch { return null } } private findFolderByRole(folders: ImapMailbox[], role: SpecialFolderRole): string | null { for (const f of folders) { const detected = this.detectFolderRole(f.specialUse, f.name) if (detected === role) return f.path if (f.folders?.length) { const found = this.findFolderByRole(f.folders, role) if (found) return found } } return null } private async buildRawMessage( messageId: string, compose: ComposeData, from: string | { name: string; address: string } ): Promise { try { const transporter = nodemailer.createTransport({ streamTransport: true, newline: 'unix' }) const fullText = compose.quotedText ? compose.body + '\n\n' + compose.quotedText : compose.body const fullHtml = compose.htmlBody ? ImapProvider.textToHtml(compose.body) + compose.htmlBody : undefined const mail = await transporter.sendMail({ from, to: compose.to.join(', '), cc: compose.cc.length ? compose.cc.join(', ') : undefined, bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined, subject: compose.subject, text: fullText, html: fullHtml, messageId, inReplyTo: compose.inReplyTo, references: compose.references, date: new Date(), attachments: compose.attachments?.map((a) => ({ path: a.path, filename: a.filename })) ?? [] }) const chunks: Buffer[] = [] await new Promise((res, rej) => { ;(mail.message as NodeJS.ReadableStream).on('data', (c: Buffer) => chunks.push(c)) ;(mail.message as NodeJS.ReadableStream).on('end', res) ;(mail.message as NodeJS.ReadableStream).on('error', rej) }) return Buffer.concat(chunks) } catch { return null } } onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void { this.newMailCallback = callback this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => { // Игнорируем первое EXISTS при выборе ящика (prevCount === 0 → не реальное новое письмо) if (data.prevCount > 0 && data.count > data.prevCount) { // Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения this.pollSingleFolder(data.path).catch(() => {}) } }) } offNewMail(): void { this.newMailCallback = null this.client.removeAllListeners('exists') } async pollNewMessages(): Promise { if (!this.newMailCallback) return try { const tree = await this.client.listTree() as { folders?: ImapMailbox[] } await this.pollFolderTree(tree.folders ?? []) } catch (err) { console.warn('[IMAP] pollNewMessages error:', (err as Error).message) } } // Немедленная проверка одной папки — вызывается из exists-события private async pollSingleFolder(folderPath: string): Promise { if (!this.newMailCallback) return try { await this.pollFolderTree([{ name: folderPath, path: folderPath }]) } catch { /* ignore */ } } private async pollFolderTree(folders: ImapMailbox[]): Promise { for (const folder of folders) { try { const status = await this.client.status(folder.path, { unseen: true }) as { unseen?: number } | null // Если STATUS вернул null или упал — не трогаем сохранённый счётчик if (status) { const unseen = status.unseen ?? 0 const prev = this.lastUnseenCount.get(folder.path) this.lastUnseenCount.set(folder.path, unseen) if (prev !== undefined && unseen > prev && this.newMailCallback) { // Получаем последнее непрочитанное письмо для уведомления const lock = await this.client.getMailboxLock(folder.path) try { const uids = await this.client.search({ seen: false }, { uid: true }) as number[] if (uids?.length) { const latestUid = Math.max(...uids).toString() const dedupKey = `${folder.path}:${latestUid}` if (!this.isRecentlyNotified(dedupKey)) { for await (const msg of this.client.fetch(latestUid, { uid: true, envelope: true, flags: true }, { uid: true })) { this.markNotified(dedupKey) this.newMailCallback(folder.path, convertImapMessage(msg, folder.path)) break } } } } finally { lock.release() } } } } catch (err) { console.warn(`[IMAP] pollFolderTree error for ${folder.path}:`, (err as Error).message) } if (folder.folders?.length) { await this.pollFolderTree(folder.folders) } } } private isRecentlyNotified(key: string): boolean { const expiry = this.notifiedUids.get(key) if (expiry === undefined) return false if (Date.now() < expiry) return true this.notifiedUids.delete(key) return false } private markNotified(key: string): void { // Чистим старые записи при росте кэша if (this.notifiedUids.size > 200) { const now = Date.now() for (const [k, exp] of this.notifiedUids) { if (now >= exp) this.notifiedUids.delete(k) } } this.notifiedUids.set(key, Date.now() + ImapProvider.NOTIF_TTL_MS) } // ---- Private helpers ---- private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] { return mailboxes.map((mb) => ({ id: mb.path, name: mb.name, role: this.detectFolderRole(mb.specialUse, mb.name), parentId, unreadCount: 0, totalCount: 0, children: mb.folders ? this.convertMailboxArray(mb.folders, mb.path) : [] })) } private detectFolderRole(specialUse?: string, name?: string): SpecialFolderRole { if (specialUse) { const u = specialUse.toLowerCase() if (u.includes('inbox')) return SpecialFolderRole.Inbox if (u.includes('sent')) return SpecialFolderRole.Sent if (u.includes('draft')) return SpecialFolderRole.Drafts if (u.includes('trash') || u.includes('deleted')) return SpecialFolderRole.Trash if (u.includes('junk') || u.includes('spam')) return SpecialFolderRole.Spam if (u.includes('archive') || u.includes('all')) return SpecialFolderRole.Archive } if (name) { const n = name.toLowerCase() if (n === 'inbox') return SpecialFolderRole.Inbox if (n === 'sent' || n === 'sent mail' || n === 'sent items') return SpecialFolderRole.Sent if (n === 'drafts' || n === 'draft') return SpecialFolderRole.Drafts if (n === 'trash' || n === 'deleted items' || n === 'deleted messages') return SpecialFolderRole.Trash if (n === 'spam' || n === 'junk' || n === 'junk e-mail') return SpecialFolderRole.Spam if (n === 'archive' || n === 'all mail') return SpecialFolderRole.Archive } return SpecialFolderRole.None } /** * Конвертирует plain text в минимальный HTML (параграфы + переносы строк). */ private static textToHtml(text: string): string { if (!text) return '' const escaped = text .replace(/&/g, '&') .replace(//g, '>') const paragraphs = escaped.split(/\n\n+/).filter((p) => p.trim()) if (paragraphs.length === 0) return '

' return paragraphs .map((p) => `

${p.replace(/\n/g, '
')}

`) .join('\n') } /** * Ищет имя отправителя в последнем письме папки Sent. * Возвращает display name из заголовка From или null если Sent пуста / не найдена. */ private async fetchSenderName(): Promise { try { const tree = await this.client.listTree() as { folders?: ImapMailbox[] } const sentPath = this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent) if (!sentPath) return null const status = await this.client.status(sentPath, { messages: true }) as { messages?: number } | null const total = status?.messages ?? 0 if (total === 0) return null const lock = await this.client.getMailboxLock(sentPath) try { let name: string | null = null // Берём только самое последнее письмо for await (const msg of this.client.fetch(`${total}:${total}`, { envelope: true })) { const fromList = (msg as { envelope?: { from?: Array<{ name?: string }> } }).envelope?.from const candidate = fromList?.[0]?.name?.trim() if (candidate) { name = candidate; break } } return name } finally { lock.release() } } catch { return null } } private htmlToPlainText(html: string): string { return html // Убираем целиком блоки