Harden contact endpoint + protect admin routes
POST /api/contact (public): - Server-side honeypot: requests with a non-empty 'website' field get a fake 201 success, nothing stored, no emails sent (matches the fake success the site already shows client-side) - Rate limit: 5 submissions per 15 min per IP (existing rateLimit middleware, now actually used) - Type checks: non-string name/email/message/company rejected with 400 - Length caps: name/company 200, email 320, message 10,000 chars Admin routes (GET /, GET /:id, PUT /:id/status, DELETE /:id): - Were publicly accessible despite 'admin only' docs — now protected with authenticateToken + requireAdmin, matching the users.js pattern (admin.html already sends Bearer tokens on these calls) middleware/auth.js rateLimit fix: - Per-instance stores with window-aware cleanup (old global cleanup deleted entries older than 60s, breaking any window > 60s); timer unref'd so it can't hold the process open
This commit is contained in:
parent
9e766424fc
commit
0dc2d24716
@ -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();
|
||||
|
||||
@ -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 {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user