From d32d70399f7dd5ae2900db162052378dfb877942 Mon Sep 17 00:00:00 2001 From: becarta Date: Fri, 13 Jun 2025 00:02:48 +0200 Subject: [PATCH] Add HTML escaping utility in email handler for enhanced security - Introduced a utility function to escape HTML special characters in email content, preventing potential XSS vulnerabilities. - Updated email templates to utilize the escapeHtml function for user inputs, including name, email, message, IP address, and user agent. - Ensured that all dynamic content in emails is properly sanitized before being rendered, enhancing overall security and reliability. --- src/utils/email-handler.ts | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/src/utils/email-handler.ts b/src/utils/email-handler.ts index 7137ca8..41c6756 100644 --- a/src/utils/email-handler.ts +++ b/src/utils/email-handler.ts @@ -171,6 +171,16 @@ export async function sendEmail(to: string, subject: string, html: string, text: } } +// Utility to escape HTML special characters +function escapeHtml(str: string): string { + return str + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + // Send admin notification email export async function sendAdminNotification( name: string, @@ -195,7 +205,7 @@ export async function sendAdminNotification( return false; } - const subject = `New Contact Form Submission from ${name}`; + const subject = `New Contact Form Submission from ${escapeHtml(name)}`; const html = ` @@ -271,19 +281,19 @@ export async function sendAdminNotification(
Name
-
${name}
+
${escapeHtml(name)}
Email
-
${email}
+
${escapeHtml(email)}
Message
-
${message.replace(/\n/g, '
')}
+
${escapeHtml(message).replace(/\n/g, '
')}
- ${ipAddress ? `
IP Address: ${ipAddress}
` : ''} - ${userAgent ? `
User Agent: ${userAgent}
` : ''} + ${ipAddress ? `
IP Address: ${escapeHtml(ipAddress)}
` : ''} + ${userAgent ? `
User Agent: ${escapeHtml(userAgent)}
` : ''}
Time: ${new Date().toLocaleString()}
-

Dear ${name},

+

Dear ${escapeHtml(name)},

Thank you for contacting ${WEBSITE_NAME}. We have received your message and will get back to you as soon as possible.

Your Message:

-

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

+

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

If you have any additional information to share, please don't hesitate to reply to this email.