diff --git a/src/middleware/auth.js b/src/middleware/auth.js index 84f13e4..4e589ae 100644 --- a/src/middleware/auth.js +++ b/src/middleware/auth.js @@ -236,17 +236,38 @@ export const requireActiveUser = (req, res, next) => { /** * Rate limiting middleware (simple in-memory implementation) * In production, use Redis or similar + * + * Each middleware instance keeps its own store and cleans entries older + * than its own window, so windows longer than 60s work correctly. */ -const rateLimitStore = new Map(); +const rateLimitInstances = new Set(); export const rateLimit = (maxRequests = 100, windowMs = 60000) => { + const store = new Map(); + + const cleanup = () => { + const windowStart = Date.now() - windowMs; + for (const [ip, requests] of store.entries()) { + const filtered = requests.filter(time => time > windowStart); + if (filtered.length === 0) { + store.delete(ip); + } else { + store.set(ip, filtered); + } + } + }; + + const timer = setInterval(cleanup, Math.min(windowMs, 60000)); + if (typeof timer.unref === 'function') timer.unref(); // don't keep the process alive + rateLimitInstances.add(timer); + return (req, res, next) => { - const ip = req.ip || req.connection.remoteAddress; + const ip = req.ip || req.connection?.remoteAddress || 'unknown'; const now = Date.now(); const windowStart = now - windowMs; // Get or create request log for IP - let requests = rateLimitStore.get(ip) || []; + let requests = store.get(ip) || []; // Filter out old requests requests = requests.filter(time => time > windowStart); @@ -256,25 +277,12 @@ export const rateLimit = (maxRequests = 100, windowMs = 60000) => { } requests.push(now); - rateLimitStore.set(ip, requests); + store.set(ip, requests); next(); }; }; -// Clean up rate limit store periodically -setInterval(() => { - const now = Date.now(); - for (const [ip, requests] of rateLimitStore.entries()) { - const filtered = requests.filter(time => time > now - 60000); - if (filtered.length === 0) { - rateLimitStore.delete(ip); - } else { - rateLimitStore.set(ip, filtered); - } - } -}, 60000); - // Clean up userinfo cache periodically setInterval(() => { const now = Date.now(); diff --git a/src/routes/contact.js b/src/routes/contact.js index ea67543..2d0d7c1 100644 --- a/src/routes/contact.js +++ b/src/routes/contact.js @@ -2,16 +2,47 @@ import express from 'express'; import { dbRun, dbAll, dbGet } from '../db/database.js'; import { generateId, ApiResponse, asyncHandler } from '../utils/helpers.js'; import { sendContactEmail, sendAutoReply } from '../services/email.js'; +import { authenticateToken, requireAdmin, rateLimit } from '../middleware/auth.js'; const router = express.Router(); +// Per-IP rate limit for public contact submissions: 5 per 15 minutes +const contactSubmitRateLimit = rateLimit(5, 15 * 60 * 1000); + +// Max accepted field lengths (guards against oversized junk payloads) +const FIELD_LIMITS = { + name: 200, + company: 200, + email: 320, + message: 10000 +}; + +const tooLong = (field) => `${field.charAt(0).toUpperCase() + field.slice(1)} is too long (max ${FIELD_LIMITS[field]} characters)`; + /** * @route POST /api/contact * @desc Submit a contact form * @access Public */ -router.post('/', asyncHandler(async (req, res) => { - const { name, email, company, message } = req.body; +router.post('/', contactSubmitRateLimit, asyncHandler(async (req, res) => { + const { name, email, company, message, website } = req.body; + + // Honeypot: the public form ships a hidden 'website' field that humans never + // fill. Bots that auto-fill every field trip it — respond with a fake success + // (nothing stored, no emails) so they have no signal that they were caught. + if (typeof website === 'string' && website.trim()) { + console.warn(`[Contact] Honeypot triggered from IP ${req.ip} — submission dropped`); + return res.status(201).json(ApiResponse(true, { + id: generateId(), + message: 'Thank you for your message! We\'ll get back to you soon.' + })); + } + + // Type checks — reject non-string payloads outright + if (typeof name !== 'string' || typeof email !== 'string' || typeof message !== 'string' || + (company !== undefined && company !== null && typeof company !== 'string')) { + return res.status(400).json(ApiResponse(false, null, 'Invalid input')); + } // Validate required fields if (!name || !name.trim()) { @@ -30,6 +61,20 @@ router.post('/', asyncHandler(async (req, res) => { return res.status(400).json(ApiResponse(false, null, 'Invalid email format')); } + // Enforce length caps + if (name.length > FIELD_LIMITS.name) { + return res.status(400).json(ApiResponse(false, null, tooLong('name'))); + } + if (email.length > FIELD_LIMITS.email) { + return res.status(400).json(ApiResponse(false, null, tooLong('email'))); + } + if (company && company.length > FIELD_LIMITS.company) { + return res.status(400).json(ApiResponse(false, null, tooLong('company'))); + } + if (message.length > FIELD_LIMITS.message) { + return res.status(400).json(ApiResponse(false, null, tooLong('message'))); + } + try { // Create contact_submissions table if not exists await dbRun(` @@ -107,7 +152,7 @@ router.post('/', asyncHandler(async (req, res) => { * @desc List all contact submissions (admin only) * @access Private (Admin) */ -router.get('/', asyncHandler(async (req, res) => { +router.get('/', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { try { const submissions = await dbAll( `SELECT * FROM contact_submissions ORDER BY created_at DESC` @@ -124,7 +169,7 @@ router.get('/', asyncHandler(async (req, res) => { * @desc Get a specific contact submission (admin only) * @access Private (Admin) */ -router.get('/:id', asyncHandler(async (req, res) => { +router.get('/:id', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { const { id } = req.params; try { @@ -149,7 +194,7 @@ router.get('/:id', asyncHandler(async (req, res) => { * @desc Update contact submission status (admin only) * @access Private (Admin) */ -router.put('/:id/status', asyncHandler(async (req, res) => { +router.put('/:id/status', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { const { id } = req.params; const { status } = req.body; @@ -180,7 +225,7 @@ router.put('/:id/status', asyncHandler(async (req, res) => { * @desc Delete a contact submission (admin only) * @access Private (Admin) */ -router.delete('/:id', asyncHandler(async (req, res) => { +router.delete('/:id', authenticateToken, requireAdmin, asyncHandler(async (req, res) => { const { id } = req.params; try {