Secure a webhook receiver
Webhooks are incoming HTTP requests. If your receiver does not check authenticity, anyone can forge events. This tutorial shows the minimum you have to do.
What Codemeta OS sends
Every webhook request contains:
- Body: JSON payload of the event.
- Header
X-Webhook-Signature: HMAC-SHA256 over the raw request body. - Header
Content-Type: application/json.
You receive the HMAC key when you create the webhook subscription. Store it as a secret – ideally in your stack’s vault.
Read the raw body. Important: before parsing. As soon as your framework parses the body as JSON and serializes it again, the whitespace layout may differ and the signature check fails.
In Express:
express.raw({ type: 'application/json' })as middleware before the route.Compute and compare the signature.
import crypto from 'node:crypto'; function verifyWebhook(rawBody: Buffer, signature: string, secret: string) { const expected = crypto .createHmac('sha256', secret) .update(rawBody) .digest('hex'); // timingSafeEqual protects against timing attacks return crypto.timingSafeEqual( Buffer.from(expected, 'hex'), Buffer.from(signature, 'hex'), ); }Process the event idempotently. Codemeta OS retries failed deliveries. So treat every event as something you may receive more than once. Store the
event.idin your DB and skip events you have already seen.if (await db.events.has(event.id)) return res.status(200).end(); await processEvent(event); await db.events.add(event.id);Respond quickly with 2xx. Codemeta OS waits a few seconds per delivery for your response. Do not do expensive work synchronously in the webhook handler – accept the event, respond with 204 No Content, and process it in a background job.