diff --git a/app/api/contact/route.js b/app/api/contact/route.js index be5116d1f..08b480ca3 100755 --- a/app/api/contact/route.js +++ b/app/api/contact/route.js @@ -1,10 +1,44 @@ import nodemailer from "nodemailer"; +function isValidEmail(email) { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return emailRegex.test(String(email).trim()); +} + +function escapeHtml(str) { + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + export async function POST(req) { try { const { name, email, subject, message } = await req.json(); - // Create transporter + // Validate required fields + if (!name || !email || !subject || !message) { + return new Response( + JSON.stringify({ message: "All fields are required" }), + { status: 400, headers: { "Content-Type": "application/json" } } + ); + } + + // Validate email format + if (!isValidEmail(email)) { + return new Response( + JSON.stringify({ message: "Invalid email address format" }), + { status: 400, headers: { "Content-Type": "application/json" } } + ); + } + + // Truncate fields to reasonable lengths + const safeName = escapeHtml(String(name).substring(0, 200)); + const safeSubject = escapeHtml(String(subject).substring(0, 200)); + const safeMessage = escapeHtml(String(message).substring(0, 5000)); + const transporter = nodemailer.createTransport({ service: "gmail", auth: { @@ -13,28 +47,21 @@ export async function POST(req) { }, }); - // Email options const mailOptions = { - from: email, + from: process.env.EMAIL_USER, to: process.env.EMAIL_USER, - subject: `New Contact Form Submission: ${subject}`, - text: ` - Name: ${name} - Email: ${email} - Subject: ${subject} - Message: ${message} - `, + subject: `New Contact Form Submission: ${safeSubject}`, + text: `Name: ${safeName}\nEmail: ${email}\nSubject: ${safeSubject}\nMessage: ${safeMessage}`, html: `

New Contact Form Submission

-

Name: ${name}

-

Email: ${email}

-

Subject: ${subject}

+

Name: ${safeName}

+

Email: ${escapeHtml(email)}

+

Subject: ${safeSubject}

Message:

-

${message.replace(/\n/g, "
")}

+

${safeMessage.replace(/\n/g, "
")}

`, }; - // Send email await transporter.sendMail(mailOptions); return Response.json({ message: "Email sent successfully" });