Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 33 additions & 7 deletions netlify/functions/contact.js
Original file line number Diff line number Diff line change
@@ -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, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}

// Simple in-memory rate limiting (resets on function cold start)
const rateLimitMap = new Map();
const RATE_LIMIT_WINDOW = 60000; // 1 minute
Expand Down Expand Up @@ -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, '<br/>');

const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: +process.env.SMTP_PORT,
Expand All @@ -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: `
<h3>New message from your portfolio</h3>
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Subject:</strong> ${subject}</p>
<p><strong>Message:</strong><br/>${message.replace(/\n/g, '<br/>')}</p>
<p><strong>Name:</strong> ${safeName}</p>
<p><strong>Email:</strong> ${safeEmail}</p>
<p><strong>Subject:</strong> ${safeSubject}</p>
<p><strong>Message:</strong><br/>${safeMessage}</p>
`,
});

Expand All @@ -87,13 +113,13 @@ export async function handler(event) {
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333;">
<h2 style="color: #3B82F6; border-bottom: 2px solid #3B82F6; padding-bottom: 10px;">Message Received</h2>

<p>Dear ${name},</p>
<p>Dear ${safeName},</p>

<p>Thank you for taking the time to reach out through my portfolio website. I have successfully received your message and truly appreciate your interest.</p>

<div style="background-color: #F3F4F6; border-left: 4px solid #3B82F6; padding: 15px; margin: 20px 0;">
<p style="margin: 0;"><strong>Your Message Details:</strong></p>
<p style="margin: 10px 0 0 0;"><strong>Subject:</strong> ${subject}</p>
<p style="margin: 10px 0 0 0;"><strong>Subject:</strong> ${safeSubject}</p>
</div>

<p>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.</p>
Expand Down
70 changes: 62 additions & 8 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}

// 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,
Expand All @@ -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, '<br/>');

try {
// Send notification email to yourself
await transporter.sendMail({
from: `Portfolio Contact <${process.env.SMTP_USER}>`,
to: process.env.RECIPIENT,
subject: `[Portfolio] ${subject} (from ${name})`,
subject: `[Portfolio] ${safeSubject} (from ${safeName})`,
html: `
<p><strong>Name:</strong> ${name}</p>
<p><strong>Email:</strong> ${email}</p>
<p><strong>Message:</strong><br/>${message.replace(/\n/g, '<br/>')}</p>
<p><strong>Name:</strong> ${safeName}</p>
<p><strong>Email:</strong> ${safeEmail}</p>
<p><strong>Message:</strong><br/>${safeMessage}</p>
`
});

Expand All @@ -46,13 +100,13 @@ app.post('/api/contact', async (req, res) => {
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; color: #333;">
<h2 style="color: #3B82F6; border-bottom: 2px solid #3B82F6; padding-bottom: 10px;">Message Received</h2>

<p>Dear ${name},</p>
<p>Dear ${safeName},</p>

<p>Thank you for taking the time to reach out through my portfolio website. I have successfully received your message and truly appreciate your interest.</p>

<div style="background-color: #F3F4F6; border-left: 4px solid #3B82F6; padding: 15px; margin: 20px 0;">
<p style="margin: 0;"><strong>Your Message Details:</strong></p>
<p style="margin: 10px 0 0 0;"><strong>Subject:</strong> ${subject}</p>
<p style="margin: 10px 0 0 0;"><strong>Subject:</strong> ${safeSubject}</p>
</div>

<p>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.</p>
Expand Down Expand Up @@ -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.' });
}
});

Expand Down