Fix Insecure Webhooks in Express
Webhooks are essentially unauthenticated POST requests exposed to the public internet. If you aren't verifying the source, an attacker can spoof payloads to trigger unauthorized business logic, such as fulfilling unpaid orders or escalating privileges. To secure them, you must implement HMAC signature verification to ensure the payload hasn't been tampered with and originated from a trusted provider.
The Vulnerable Pattern
const express = require('express'); const app = express(); app.use(express.json());app.post(‘/webhook’, (req, res) => { // VULNERABILITY: Blindly trusting the request body const event = req.body;
if (event.type === ‘order.paid’) { console.log(
Fulfilling order: ${event.orderId}); }
res.status(200).end(); });
The Secure Implementation
The secure implementation uses HMAC (Hash-based Message Authentication Code) with SHA-256. Key steps: 1. Use express.raw() to capture the exact bytes of the payload, as standard JSON parsing can alter spacing and break the hash. 2. Recompute the HMAC using your shared secret and the raw body. 3. Use crypto.timingSafeEqual to compare the provided signature against your computed hash; this mitigates side-channel timing attacks that could leak the signature byte-by-byte. If the hashes don't match, the request is discarded before any logic executes.
const express = require('express'); const crypto = require('crypto'); const app = express();// Use raw body for verification; signature fails if body is pre-parsed app.post(‘/webhook’, express.raw({ type: ‘application/json’ }), (req, res) => { const signature = req.headers[‘x-webhook-signature’]; const secret = process.env.WEBHOOK_SECRET;
if (!signature) return res.status(400).send(‘Missing signature’);
const hmac = crypto.createHmac(‘sha256’, secret); const digest = Buffer.from(hmac.update(req.body).digest(‘hex’), ‘utf8’); const checksum = Buffer.from(signature, ‘utf8’);
// Prevent timing attacks using timingSafeEqual if (checksum.length !== digest.length || !crypto.timingSafeEqual(digest, checksum)) { return res.status(401).send(‘Signature mismatch’); }
const event = JSON.parse(req.body); // Business logic here… res.status(200).send(‘Verified’); });
Your Express API
might be exposed to Insecure Webhooks
74% of Express apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.