đ HMAC Verification in webhook-listener.js
Secure your civic API with signature checks, no spoofing, and verified GitHub events…
đ§ What Is HMAC Verification?
HMAC stands for Hash-based Message Authentication Code. It’s a cryptographic technique used to verify that a message (like a webhook from GitHub) is:
- ✅ Authentic — sent by the real source
- ✅ Untampered — not changed during transit
Think of it as a secret handshake between GitHub and your server. If the handshake doesn’t match, the message gets rejected.
đĻ Why Is It in api/webhook-listener.js?
This file is a serverless API endpoint that listens for incoming webhooks from GitHub. Webhooks are automated messages GitHub sends when something happens—like a push, star, or issue.
But anyone could try to fake a webhook. That’s where HMAC comes in.
đ ️ How It Works
- GitHub sends a webhook with a special header called
x-hub-signature-256. - Your server uses the same secret key to generate its own hash of the message.
- It compares the two hashes:
- If they match → ✅ Message is real
- If they don’t → ❌ Message is rejected
đ Code Snippet
const signature = req.headers['x-hub-signature-256']; const payload = JSON.stringify(req.body); const hmac = crypto.createHmac('sha256', WEBHOOK_SECRET); hmac.update(payload); const expectedSignature = `sha256=${hmac.digest('hex')}`; if (signature !== expectedSignature) { return res.status(401).json({ error: 'Invalid signature' }); } đ§Š Why It Matters
- đĄ️ Security: Prevents fake or malicious data from entering your civic dashboard
- đ Integrity: Ensures only verified GitHub events trigger updates
- đ Auditability: Logs every verified event with timestamp and metadata
- đĢ No Spoofing: Blocks bots or attackers from injecting false data
đ Glossary (Kid-Friendly)
| Term | Meaning |
|---|---|
HMAC | A secret math check to prove a message is real |
Webhook | A message GitHub sends when something happens |
Signature | A special code that proves the message is safe |
Secret Key | A password used to generate and verify the signature |
Hash | A scrambled version of the message used for verification |
Serverless | Code that runs online without managing a physical server |
No comments:
Post a Comment