// securityMw.js require('dotenv').config(); const fetch = require('node-fetch'); module.exports = { formSecurityCheck: async (req, res, next) => { // 1. Honeypot check (first line of defense) if (req.body.url) { console.warn('Bot detected! Honeypot field was filled.'); return res.status(200).json({ success: true, message: 'Thank you for your submission.' }); } // 2. hCaptcha verification (second line of defense) const hCaptchaResponse = req.body.hCaptchaResponse; if (!hCaptchaResponse) { return res.status(400).json({ success: false, message: 'CAPTCHA token missing.' }); } try { const secretKey = process.env.HCAPTCHA_SECRET; const verificationUrl = 'https://hcaptcha.com/siteverify'; const verificationResponse = await fetch(verificationUrl, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ secret: secretKey, response: hCaptchaResponse }) }); const verificationData = await verificationResponse.json(); if (!verificationData.success) { console.error('hCaptcha verification failed:', verificationData['error-codes']); return res.status(400).json({ success: false, message: 'CAPTCHA verification failed. Please try again.' }); } // If all checks pass, move to the next middleware or controller next(); } catch (error) { console.error('An error occurred during hCaptcha verification:', error); return res.status(500).json({ success: false, message: 'Internal server error during CAPTCHA verification.' }); } } };