import { NextResponse } from 'next/server'; import { simpleParser } from 'mailparser'; import DOMPurify from 'dompurify'; import { JSDOM } from 'jsdom'; // Create a window object for DOMPurify const window = new JSDOM('').window; const purify = DOMPurify(window); function cleanHtml(html: string): string { try { return purify.sanitize(html, { ALLOWED_TAGS: ['p', 'br', 'div', 'span', 'a', 'img', 'strong', 'em', 'u', 'ul', 'ol', 'li', 'blockquote', 'pre', 'code', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'], ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'style'], ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i }); } catch (error) { console.error('Error cleaning HTML:', error); return html; } } export async function POST(request: Request) { try { const { emailContent } = await request.json(); if (!emailContent) { return NextResponse.json( { error: 'Email content is required' }, { status: 400 } ); } const parsed = await simpleParser(emailContent); return NextResponse.json({ subject: parsed.subject || null, from: parsed.from?.text || null, to: parsed.to?.text || null, cc: parsed.cc?.text || null, bcc: parsed.bcc?.text || null, date: parsed.date || null, html: parsed.html ? cleanHtml(parsed.html) : null, text: parsed.text || null, attachments: parsed.attachments || [], headers: Object.fromEntries(parsed.headers) }); } catch (error) { console.error('Error parsing email:', error); return NextResponse.json( { error: 'Failed to parse email' }, { status: 500 } ); } }