Cursor prompt

Build Idempotent Webhook Handler

Idempotent webhook handler with HMAC signature verification, event deduplication, async processing, and dead letter handling.

Build a production-grade webhook handler for {{webhook_source}} in {{project_name}}.

### Security: Signature Verification (Required First)
```typescript
import { createHmac, timingSafeEqual } from 'crypto';

function verifySignature(payload: Buffer, signature: string, secret: string): boolean {
  const expected = createHmac('sha256', secret).update(payload).digest('hex');
  return timingSafeEqual(Buffer.from(signature), Buffer.from(expected));
}
```
Use timingSafeEqual — NEVER regular string comparison (timing attack vulnerability).
Reject with 401 if signature invalid or missing.

### Idempotency
Before processing any event:
1. Check Redis/DB for eventId
2. If found: return 200 immediately (already processed)
3. If not found: mark as "processing", then process, then mark "done"
Use atomic check-and-set to handle concurrent duplicate deliveries.

### Async Processing Pattern
Webhook handler: validate → store raw event → return 200 immediately (< 3s).
Worker: pick up event → process → mark done → handle errors with retry.
Never do real work synchronously in the webhook handler.

### Events to Handle: {{event_types}}
For each event type, implement the business logic separately.

### Retry and Dead Letter
- Failed events: retry with backoff: 1min, 5min, 30min (3 attempts total)
- After 3 failures: move to dead letter queue + alert on-call
- Manual retry: POST /api/admin/webhooks/:id/retry

### Monitoring
Log all events: eventId, source, type, receivedAt, processedAt, status, duration.

### Output
Webhook route, signature verifier, event store, async worker, retry logic.

Fill in: {{webhook_source}}, {{project_name}}, {{event_types}}. In Loopy you fill these in a form and copy the finished prompt in one click.