diff --git a/netlify/functions/contact.js b/netlify/functions/contact.js
index 9e6de2f..bdb2e2e 100644
--- a/netlify/functions/contact.js
+++ b/netlify/functions/contact.js
@@ -1,5 +1,15 @@
import nodemailer from 'nodemailer';
+// HTML-escape user input to prevent HTML injection in emails
+function escapeHtml(str) {
+ return String(str)
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
+}
+
// Simple in-memory rate limiting (resets on function cold start)
const rateLimitMap = new Map();
const RATE_LIMIT_WINDOW = 60000; // 1 minute
@@ -53,6 +63,22 @@ export async function handler(event) {
};
}
+ // Email format validation
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/;
+ if (!emailRegex.test(email)) {
+ return {
+ statusCode: 400,
+ headers,
+ body: JSON.stringify({ ok: false, error: 'Invalid email address' }),
+ };
+ }
+
+ // Sanitize user inputs
+ const safeName = escapeHtml(name);
+ const safeEmail = escapeHtml(email);
+ const safeSubject = escapeHtml(subject);
+ const safeMessage = escapeHtml(message).replace(/\n/g, '
');
+
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: +process.env.SMTP_PORT,
@@ -68,13 +94,13 @@ export async function handler(event) {
from: `Portfolio Contact <${process.env.SMTP_USER}>`,
to: process.env.RECIPIENT,
replyTo: email,
- subject: `[Portfolio] ${subject} (from ${name})`,
+ subject: `[Portfolio] ${safeSubject} (from ${safeName})`,
html: `
Name: ${name}
-Email: ${email}
-Subject: ${subject}
-Message:
${message.replace(/\n/g, '
')}
Name: ${safeName}
+Email: ${safeEmail}
+Subject: ${safeSubject}
+Message:
${safeMessage}
Dear ${name},
+Dear ${safeName},
Thank you for taking the time to reach out through my portfolio website. I have successfully received your message and truly appreciate your interest.
Your Message Details:
-Subject: ${subject}
+Subject: ${safeSubject}
I make it a priority to respond to all inquiries promptly and will get back to you as soon as possible, typically within 24-48 hours.
diff --git a/server/index.js b/server/index.js index ca67713..a4f0b1a 100644 --- a/server/index.js +++ b/server/index.js @@ -10,7 +10,22 @@ dotenv.config({ path: join(__dirname, '.env') }); const app = express(); app.use(cors()); -app.use(express.json()); +app.use(express.json({ limit: '1kb' })); + +// HTML-escape user input to prevent HTML injection in emails +function escapeHtml(str) { + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +// Simple in-memory rate limiting +const rateLimitMap = new Map(); +const RATE_LIMIT_WINDOW = 60000; // 1 minute +const CLEANUP_THRESHOLD = 5 * RATE_LIMIT_WINDOW; // 5 minutes const transporter = nodemailer.createTransport({ host: process.env.SMTP_HOST, @@ -23,17 +38,56 @@ const transporter = nodemailer.createTransport({ }); app.post('/api/contact', async (req, res) => { + // Rate limiting + const clientIP = req.headers['x-forwarded-for'] || req.socket.remoteAddress || 'unknown'; + const now = Date.now(); + const lastSubmission = rateLimitMap.get(clientIP); + + if (lastSubmission && (now - lastSubmission) < RATE_LIMIT_WINDOW) { + return res.status(429).json({ + ok: false, + error: 'Too many requests. Please wait a minute before submitting again.' + }); + } + + rateLimitMap.set(clientIP, now); + + // Clean up old entries + for (const [ip, timestamp] of rateLimitMap.entries()) { + if (now - timestamp > CLEANUP_THRESHOLD) { + rateLimitMap.delete(ip); + } + } + const { name, email, subject, message } = req.body; + + // Input validation + if (!name || !email || !subject || !message) { + return res.status(400).json({ ok: false, error: 'All fields are required' }); + } + + // Email format validation + const emailRegex = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/; + if (!emailRegex.test(email)) { + return res.status(400).json({ ok: false, error: 'Invalid email address' }); + } + + // Sanitize user inputs + const safeName = escapeHtml(name); + const safeEmail = escapeHtml(email); + const safeSubject = escapeHtml(subject); + const safeMessage = escapeHtml(message).replace(/\n/g, 'Name: ${name}
-Email: ${email}
-Message:
${message.replace(/\n/g, '
')}
Name: ${safeName}
+Email: ${safeEmail}
+Message:
${safeMessage}
Dear ${name},
+Dear ${safeName},
Thank you for taking the time to reach out through my portfolio website. I have successfully received your message and truly appreciate your interest.
Your Message Details:
-Subject: ${subject}
+Subject: ${safeSubject}
I make it a priority to respond to all inquiries promptly and will get back to you as soon as possible, typically within 24-48 hours.
@@ -82,7 +136,7 @@ app.post('/api/contact', async (req, res) => { res.json({ ok: true }); } catch (error) { console.error(error); - res.status(500).json({ ok: false, error: error.message }); + res.status(500).json({ ok: false, error: 'Failed to send email. Please try again later.' }); } });