// secure-webhook-receiver.js
// A secure Node.js webhook receiver with:
// - Signature verification (HMAC SHA256 of raw body)
// - Idempotency (via idempotency-key header, stored in Redis for 24h)
// - Ordering (per account_id sequence number; only process if sequence == expected_next)
//
// Features:
// - At-least-once delivery with idempotency.
// - Strict ordering: skips out-of-order or duplicate sequences.
// - Assumes payload JSON: { account_id: string, sequence: number, event_type: string, data: object }
// - Headers: X-Webhook-Signature: <hex>, Idempotency-Key: <uuid>
// - Uses Redis for storage (fast, distributed). In-memory fallback commented.
//
// Production notes:
// - Use HTTPS only.
// - Add rate limiting (e.g., express-rate-limit).
// - Handle errors gracefully, log everything.
// - Scale with multiple instances (Redis ensures consistency).
// - Test with tools like ngrok + curl.
// - Customize secret, Redis URL.
const express = require('express');
const crypto = require('crypto');
const Redis = require('ioredis'); // npm i ioredis
const app = express();
const port = process.env.PORT || 3000;
// Config
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || 'your-super-secret-key-change-me';
const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379';
const redis = new Redis(REDIS_URL);
// Middleware: Enable JSON parsing for convenience (but use rawBody for sig)
app.use(express.json({ verify: (req, res, buf) => { req.rawBody = buf; } }));
// Health check
app.get('/health', (req, res) => res.status(200).json({ status: 'ok' }));
// Main webhook endpoint
app.post('/webhook', async (req, res) => {
try {
const rawBody = req.rawBody.toString('utf8');
const signature = req.headers['x-webhook-signature'];
const idempotencyKey = req.headers['idempotency-key'];
if (!signature || !idempotencyKey) {
return res.status(400).json({ error: 'Missing signature or idempotency-key' });
}
// 1. Verify signature (HMAC SHA256 of raw body)
const expectedSignature = `sha256=${crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(rawBody)
.digest('hex')}`;
if (signature !== expectedSignature) {
console.error('Invalid signature');
return res.status(401).send('Unauthorized');
}
const payload = req.body;
const { account_id, sequence } = payload;
if (!account_id || typeof sequence !== 'number') {
return res.status(400).json({ error: 'Missing account_id or sequence' });
}
// 2. Idempotency check (prevents duplicate processing even across restarts)
const processedKey = `idempotent:${idempotencyKey}`;
const alreadyProcessed = await redis.get(processedKey);
if (alreadyProcessed) {
console.log(`Idempotent skip: ${idempotencyKey}`);
return res.status(200).send('OK'); // 200 for at-least-once semantics
}
// 3. Ordering check (strict: must be exactly next expected)
const lastSeqKey = `last_seq:${account_id}`;
const lastSeq = parseInt(await redis.get(lastSeqKey) || '0', 10);
if (sequence !== lastSeq + 1) {
console.log(`Out-of-order: account ${account_id}, got ${sequence}, expected ${lastSeq + 1}`);
// Optionally store as processed to avoid retries, but here we ack to unblock sender
await redis.set(processedKey, '1', 'EX', 86400); // 24h TTL
return res.status(200).send('OK'); // Ack to prevent retries, but skip processing
}
// 4. Process the event (your business logic here)
console.log(`Processing event: ${payload.event_type} for account ${account_id}, seq ${sequence}`);
await processEvent(payload); // Replace with your handler
// 5. Mark as processed
await redis.set(processedKey, '1', 'EX', 86400); // Idempotency TTL 24h
await redis.set(lastSeqKey, sequence.toString()); // Persist last sequence (no TTL needed)
res.status(200).send('OK');
} catch (error) {
console.error('Webhook error:', error);
res.status(500).send('Internal Server Error');
}
});
// Example processEvent (customize!)
async function processEvent(payload) {
// Simulate async work: save to DB, send email, etc.
// e.g., await db.events.insert(payload);
await new Promise(resolve => setTimeout(resolve, 10)); // Fake delay
console.log('Event processed:', payload.event_type, payload.data);
}
// Graceful shutdown
process.on('SIGTERM', async () => {
await redis.quit();
process.exit(0);
});
app.listen(port, () => {
console.log(`Webhook receiver listening on port ${port}`);
console.log(`Secret: ${WEBHOOK_SECRET.substring(0, 10)}...`);
console.log(`Redis: ${REDIS_URL}`);
});
Quick Start
-
Install dependencies:
npm init -y
npm i express ioredis
-
Run Redis (local dev):
- Docker:
docker run -p 6379:6379 redis:alpine
- Or install Redis locally.
-
Set env vars:
export WEBHOOK_SECRET="sk_verysecret123"
export REDIS_URL="redis://127.0.0.1:6379" # optional
-
Run server:
node secure-webhook-receiver.js
Test It
Use curl or Postman. Expose with ngrok: ngrok http 3000.
Valid payload (JSON):
{
"account_id": "acc_123",
"sequence": 1,
"event_type": "user.created",
"data": { "user_id": "u_456", "name": "Alice" }
}
Test curl (seq 1):
curl -X POST http://localhost:3000/webhook \
-H "Content-Type: application/json" \
-H "X-Webhook-Signature: sha256=efccfb613e266ebe65d3dc9b4f6d3b6c3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b3b" \
-H "Idempotency-Key: idemp-uuid-v4-123" \
-d '{"account_id":"acc_123","sequence":1,"event_type":"user.created","data":{"user_id":"u_456"}}'
- Compute real sig:
echo -n '{"account_id"...}' | openssl dgst -sha256 -hmac "your-super-secret-key-change-me" | cut -d' ' -f2
- Prefix with
sha256=.
Tests:
- Duplicate idemp-key → 200 (skip).
- Out-of-order seq (e.g., 3 before 2) → 200 (skip).
- Valid next seq → Process + 200.
In-Memory Fallback (No Redis)
Replace Redis calls:
const idempotents = new Map(); // key → expiry timestamp
const lastSeqs = new Map(); // account_id → seq
// Get idempotent:
const alreadyProcessed = idempotents.has(idempotencyKey) && Date.now() < idempotents.get(idempotencyKey);
// Set idempotent:
idempotents.set(idempotencyKey, Date.now() + 86400000); // 24h ms
// Similar for lastSeq
Not production-ready (not persistent/distributed).
Security & Extensibility
- Sig: Timestamped? Add
t=<ts>,v1=<sig> parsing (Stripe-style).
- Order: Handle gaps? Use
>= lastSeq +1 and retry logic.
- Retries: Sender should retry on 5xx, idempotent handles duplicates.
- Monitoring: Add Prometheus, Sentry.
- Queue: For heavy processing, publish to BullMQ/SQS after validation.
This is production-grade starter code. Ping for customizations! 🕵️