import express from 'express';import { verifyWebhookSignature } from './webhook-utils';const app = express();// Important: Use raw body parser for webhook routesapp.post( '/webhooks/pictify', express.raw({ type: 'application/json' }), (req, res) => { const signature = req.headers['x-pictify-signature'] as string; const payload = req.body.toString(); const { valid, error } = verifyWebhookSignature( payload, signature, process.env.PICTIFY_WEBHOOK_SECRET! ); if (!valid) { console.error('Webhook verification failed:', error); return res.status(401).send('Invalid signature'); } const event = JSON.parse(payload); // Process the webhook switch (event.event) { case 'render.completed': handleRenderCompleted(event.data); break; case 'render.failed': handleRenderFailed(event.data); break; } res.status(200).send('OK'); });
FastAPI
from fastapi import FastAPI, Request, HTTPException, Headerapp = FastAPI()@app.post("/webhooks/pictify")async def handle_webhook( request: Request, x_pictify_signature: str = Header(...)): payload = await request.body() valid, error = verify_webhook_signature( payload, x_pictify_signature, WEBHOOK_SECRET ) if not valid: raise HTTPException(status_code=401, detail=error) event = await request.json() # Process the webhook if event['event'] == 'render.completed': await handle_render_completed(event['data']) elif event['event'] == 'render.failed': await handle_render_failed(event['data']) return {"status": "ok"}
Rails
class WebhooksController < ApplicationController skip_before_action :verify_authenticity_token def pictify result = Pictify::WebhookVerifier.verify( payload: request.raw_post, signature_header: request.headers['X-Pictify-Signature'], secret: ENV['PICTIFY_WEBHOOK_SECRET'] ) unless result[:valid] Rails.logger.error "Webhook verification failed: #{result[:error]}" return head :unauthorized end event = JSON.parse(request.raw_post) case event['event'] when 'render.completed' HandleRenderCompletedJob.perform_later(event['data']) when 'render.failed' HandleRenderFailedJob.perform_later(event['data']) end head :ok endend
Security Best Practices
1. Store Secrets Securely
# Use environment variablesexport PICTIFY_WEBHOOK_SECRET=whsec_abc123...# Or use a secrets manageraws secretsmanager get-secret-value --secret-id pictify/webhook-secret
2. Use Constant-Time Comparison
Always use constant-time comparison to prevent timing attacks:
// ✅ Good - constant timecrypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))// ❌ Bad - vulnerable to timing attacksa === b
3. Enforce Timestamp Checks
Replay protection prevents attackers from resending old webhooks:
// Reject webhooks older than 5 minutesconst MAX_AGE = 300; // 5 minutes in secondsif (Math.abs(Date.now() / 1000 - timestamp) > MAX_AGE) { throw new Error('Webhook too old');}