|
| 1 | +import { Injectable, Logger } from '@nestjs/common'; |
| 2 | +import * as crypto from 'crypto'; |
| 3 | + |
| 4 | +export interface WebhookSubscription { |
| 5 | + id: string; |
| 6 | + url: string; |
| 7 | + secret: string; |
| 8 | + events: string[]; |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * Outbound webhooks: delivers signed event payloads to subscriber URLs with |
| 13 | + * retries. |
| 14 | + * |
| 15 | + * Each delivery is signed with the subscription secret (HMAC-SHA256) in an |
| 16 | + * `X-Signature` header so receivers can verify authenticity. Failed deliveries |
| 17 | + * are retried with exponential backoff. |
| 18 | + */ |
| 19 | +@Injectable() |
| 20 | +export class WebhooksService { |
| 21 | + private readonly logger = new Logger(WebhooksService.name); |
| 22 | + |
| 23 | + /** Compute the signature a receiver uses to verify a delivery. */ |
| 24 | + sign(secret: string, payload: string): string { |
| 25 | + return crypto.createHmac('sha256', secret).update(payload).digest('hex'); |
| 26 | + } |
| 27 | + |
| 28 | + /** Deliver an event to every subscription registered for it. */ |
| 29 | + async dispatch( |
| 30 | + subscriptions: WebhookSubscription[], |
| 31 | + event: string, |
| 32 | + data: unknown, |
| 33 | + ): Promise<void> { |
| 34 | + const payload = JSON.stringify({ event, data, timestamp: Date.now() }); |
| 35 | + for (const sub of subscriptions.filter((s) => s.events.includes(event))) { |
| 36 | + await this.deliver(sub, payload); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private async deliver( |
| 41 | + sub: WebhookSubscription, |
| 42 | + payload: string, |
| 43 | + attempt = 1, |
| 44 | + ): Promise<void> { |
| 45 | + const maxAttempts = 3; |
| 46 | + try { |
| 47 | + const res = await fetch(sub.url, { |
| 48 | + method: 'POST', |
| 49 | + headers: { |
| 50 | + 'Content-Type': 'application/json', |
| 51 | + 'X-Signature': this.sign(sub.secret, payload), |
| 52 | + }, |
| 53 | + body: payload, |
| 54 | + }); |
| 55 | + if (!res.ok) throw new Error(`HTTP ${res.status}`); |
| 56 | + } catch (err) { |
| 57 | + if (attempt < maxAttempts) { |
| 58 | + const delayMs = 1000 * 2 ** (attempt - 1); |
| 59 | + await new Promise((r) => setTimeout(r, delayMs)); |
| 60 | + return this.deliver(sub, payload, attempt + 1); |
| 61 | + } |
| 62 | + this.logger.error( |
| 63 | + `Webhook ${sub.id} failed after ${maxAttempts} attempts: ${(err as Error).message}`, |
| 64 | + ); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments