π Dissecting webhook-listener.js
Understanding serverless verification logic and civic-grade webhook security for GitHub events…
π¦ The Code
import crypto from 'crypto'; const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET; export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method Not Allowed' }); } try { const signature = req.headers['x-hub-signature-256'] || req.headers['X-Hub-Signature-256']; const payload = JSON.stringify(req.body); if (!signature || !WEBHOOK_SECRET) { throw new Error('Missing signature or secret'); } 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' }); } const event = req.headers['x-github-event'] || 'unknown'; const delivery = req.headers['x-github-delivery'] || 'unknown'; const timestamp = new Date().toISOString(); console.log(`[${timestamp}] ✅ Webhook received: ${event} | Delivery: ${delivery}`); res.status(200).json({ status: '✅ Verified webhook received', event, delivery, timestamp, }); } catch (err) { console.error(`❌ Webhook error: ${err.message}`); res.status(500).json({ status: '❌ Webhook failed', error: err.message, }); } } π§ What This Code Does
- Imports crypto: Uses Node.js crypto module to verify message authenticity
- Checks request method: Only allows
POSTrequests (as GitHub sends webhooks via POST) - Extracts signature: Reads the HMAC signature from GitHub headers
- Recalculates signature: Uses your secret to recreate the expected signature
- Compares signatures: If they don’t match, the request is rejected
- Logs metadata: Captures event type, delivery ID, and timestamp
- Sends response: Returns success or failure message
π Why It Matters
This function protects your civic API from fake or malicious requests. It ensures only GitHub can trigger your logic.
Without this verification, anyone could send spoofed data to your endpoint—breaking trust and polluting your dashboard.
π ️ What’s Missing
- ❌ No logic to extract or rotate hashtags
- ❌ No storage or update mechanism
- ❌ No raw body capture for HMAC integrity (needed on platforms like Vercel)
π Glossary of Terms (Kid-Friendly)
| Term | Meaning |
|---|---|
Webhook | A message GitHub sends to your app when something happens |
Serverless | A way to run code online without managing a server |
HMAC | A secret math check to make sure the message is real |
Payload | The actual message or data sent |
Signature | A special code that proves the message is safe |
Raw Body | The untouched message before it’s changed |
Rotate | To change or update something regularly |
No comments:
Post a Comment