Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(webhook): extract the delivery core shared by both paths
Yudhi Armyndharis1cdaa5cc1a65
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 50eccac92..7c5ebbedc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- The direct and queued webhook delivery paths share one POST-and-classify core (`postWebhookPayload`) and one terminal-failure recorder, instead of two line-for-line copies that an outbox would have tripled.- Test and DB infrastructure: the 23 file-reading specs are excluded from the unit coverage denominators (spec files were counted as 0%-covered source, ~994 lines inflating every floor), an e2e boots the production SQLite schema from scratch through both full migration chains (the path the other suites' synchronize=true never touches), and a drift gate derives the chain-vs-entity diff so a missing index, column, or constraint fails while the known column-type rebuild is pinned as a visible baseline.- The ingress route's rate bound is the per-instance limit alone: the global per-IP medium tier (100/min, below the instance default of 120/min) used to 429 every tenant of a shared-egress-IP provider before the instance bound ever fired.- The in-flight body budget gives each client IP its own share (half the aggregate by default, keyed through TRUSTED_PROXIES): four trickle connections from one source now exhaust only that source's share instead of 503ing every body-bearing request for everyone.diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex ff4e333a9..766fe66d6 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -10,8 +10,9 @@ import { WebhookJobData, WebhookPayload } from '../../webhook/webhook.service';import { Webhook } from '../../webhook/entities/webhook.entity';import { WebhookDeliveryFailure } from '../../webhook/entities/webhook-delivery-failure.entity';import { recordWebhookDeliveryFailure, statusCodeFromError } from '../../webhook/utils/record-delivery-failure';+import { postWebhookPayload } from '../../webhook/utils/deliver-once';import { HookManager } from '../../../core/hooks';-import { withSafeFetch, isSsrfProtectionEnabled, redactSsrfError } from '../../../common/security/ssrf-guard';+import { redactSsrfError } from '../../../common/security/ssrf-guard';import { incrementWebhookDeliveryFailures } from '../../../common/metrics/webhook-delivery-metrics';export interface WebhookJobResult {@@ -107,25 +108,15 @@ export class WebhookProcessor extends WorkerHost {requestHeaders: Record<string, string>,): Promise<{ status: number; responseTime: number }> {const { url, payload, startTime } = ctx;- const { status, statusText, ok } = await withSafeFetch(+ const { status } = await postWebhookPayload(url,- {- method: 'POST',- headers: requestHeaders,- body: JSON.stringify(payload),- // Honor WEBHOOK_TIMEOUT on the primary (queued) path too — not just the deprecated direct one.- signal: AbortSignal.timeout(this.configService.get<number>('webhook.timeout', 10000)),- },- response => ({ status: response.status, statusText: response.statusText, ok: response.ok }),- { guard: isSsrfProtectionEnabled() },+ JSON.stringify(payload),+ requestHeaders,+ // Honor WEBHOOK_TIMEOUT on the primary (queued) path too — not just the deprecated direct one.+ this.configService.get<number>('webhook.timeout', 10000),);const responseTime = Date.now() - startTime;-- if (!ok) {- throw new Error(`HTTP ${status}: ${statusText}`);- }-return { status, responseTime };}diff --git a/src/modules/webhook/utils/deliver-once.spec.ts b/src/modules/webhook/utils/deliver-once.spec.tsnew file mode 100644index 000000000..fae9ce0fe--- /dev/null+++ b/src/modules/webhook/utils/deliver-once.spec.ts@@ -0,0 +1,49 @@+import { postWebhookPayload } from './deliver-once';++/**+ * Direct coverage for the shared delivery core both paths (direct and queued processor) now route+ * through. Previously each path carried its own line-for-line copy of the POST + classification,+ * which is the duplication an outbox would have tripled.+ */+describe('postWebhookPayload', () => {+ const makeFetch = (status = 200): { mock: jest.Mock } => ({+ mock: jest.fn().mockResolvedValue({ ok: status < 400, status, statusText: 'OK' }),+ });++ it('POSTs the exact body bytes with the given headers and timeout, through the SSRF guard', async () => {+ const { mock } = makeFetch();+ await postWebhookPayload('https://receiver.example/hook', '{"a":1}', { 'X-Test': '1' }, 5000, mock as never);++ const calls = mock.mock.calls as unknown as unknown[][];+ const [url, opts, classifier, guard] = calls[0] as [+ string,+ { method: string; body: string; headers: Record<string, string>; signal: AbortSignal },+ unknown,+ { guard: boolean },+ ];+ expect(url).toBe('https://receiver.example/hook');+ expect(opts.method).toBe('POST');+ expect(opts.body).toBe('{"a":1}');+ expect(opts.headers).toEqual({ 'X-Test': '1' });+ expect(opts.signal).toBeInstanceOf(AbortSignal);+ expect(classifier).toBeInstanceOf(Function);+ expect(guard).toBeDefined();+ expect(Object.keys(guard)).toContain('guard');+ });++ it('resolves with the status on a 2xx answer', async () => {+ const { mock } = makeFetch(204);+ await expect(postWebhookPayload('https://r/hook', '{}', {}, 5000, mock as never)).resolves.toEqual({+ status: 204,+ statusText: 'OK',+ });+ });++ it('throws HTTP <status>: <statusText> on a non-2xx answer (the error shape both paths classify on)', async () => {+ const { mock } = makeFetch(502);+ mock.mockResolvedValue({ ok: false, status: 502, statusText: 'Bad Gateway' });+ await expect(postWebhookPayload('https://r/hook', '{}', {}, 5000, mock as never)).rejects.toThrow(+ 'HTTP 502: Bad Gateway',+ );+ });+});diff --git a/src/modules/webhook/utils/deliver-once.ts b/src/modules/webhook/utils/deliver-once.tsnew file mode 100644index 000000000..b1ebe426f--- /dev/null+++ b/src/modules/webhook/utils/deliver-once.ts@@ -0,0 +1,51 @@+import { Repository } from 'typeorm';+import { withSafeFetch, redactSsrfError, isSsrfProtectionEnabled } from '../../../common/security/ssrf-guard';+import { type LoggerService } from '../../../common/services/logger.service';+import { WebhookDeliveryFailure } from '../entities/webhook-delivery-failure.entity';+import { recordWebhookDeliveryFailure, statusCodeFromError } from './record-delivery-failure';++/**+ * One SSRF-guarded POST + response classification: a non-ok status throws `HTTP <status>: <statusText>`,+ * ok returns the status. This is the byte-level delivery core BOTH paths previously duplicated line+ * for line; extracting it keeps the two sinks one contract: same fetch, same guard, same error+ * shape, same timeout knob.+ */+export async function postWebhookPayload(+ url: string,+ body: string,+ headers: Record<string, string>,+ timeoutMs: number,+ fetch: typeof withSafeFetch = withSafeFetch,+): Promise<{ status: number; statusText: string }> {+ const { ok, status, statusText } = await fetch(+ url,+ {+ method: 'POST',+ headers,+ body,+ signal: AbortSignal.timeout(timeoutMs),+ },+ response => ({ ok: response.ok, status: response.status, statusText: response.statusText }),+ { guard: isSsrfProtectionEnabled() },+ );+ if (!ok) throw new Error(`HTTP ${status}: ${statusText}`);+ return { status, statusText };+}++/**+ * Record a terminal webhook delivery failure (all retries exhausted) to the durable table. Shared+ * wrapper so both paths write the identical row shape. Best-effort: never throws back into the+ * delivery result (the caller's semantics depend on that).+ */+export async function recordTerminalFailure(+ failureRepository: Repository<WebhookDeliveryFailure>,+ logger: LoggerService,+ input: Omit<Parameters<typeof recordWebhookDeliveryFailure>[2], 'lastStatusCode' | 'lastError'> & { error: unknown },+): Promise<void> {+ const errMessage = redactSsrfError(input.error);+ await recordWebhookDeliveryFailure(failureRepository, logger, {+ ...input,+ lastStatusCode: statusCodeFromError(errMessage),+ lastError: errMessage,+ });+}diff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.tsindex 3f0c3e62a..96c359ca2 100644--- a/src/modules/webhook/webhook-delivery.service.ts+++ b/src/modules/webhook/webhook-delivery.service.ts@@ -8,7 +8,8 @@ import * as crypto from 'crypto';import { setTimeout } from 'node:timers/promises';import { Webhook } from './entities/webhook.entity';import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';-import { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';+import { recordWebhookDeliveryFailure } from './utils/record-delivery-failure';+import { postWebhookPayload, recordTerminalFailure } from './utils/deliver-once';import { createLogger } from '../../common/services/logger.service';import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';@@ -16,7 +17,7 @@ import { QUEUE_NAMES } from '../queue/queue-names';import { generateIdempotencyKey, generateDeliveryId } from './utils/idempotency.util';import { evaluateFilters } from './filters/filter-evaluator';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';-import { withSafeFetch, isSsrfProtectionEnabled, redactSsrfError } from '../../common/security/ssrf-guard';+import { redactSsrfError } from '../../common/security/ssrf-guard';import { HookManager } from '../../core/hooks';import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';@@ -643,21 +644,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {}try {- const { ok, status, statusText } = await withSafeFetch(- webhook.url,- {- method: 'POST',- headers,- body,- signal: AbortSignal.timeout(this.configService.get<number>('webhook.timeout', 10000)),- },- response => ({ ok: response.ok, status: response.status, statusText: response.statusText }),- { guard: isSsrfProtectionEnabled() },- );-- if (!ok) {- throw new Error(`HTTP ${status}: ${statusText}`);- }+ await postWebhookPayload(webhook.url, body, headers, this.configService.get<number>('webhook.timeout', 10000));// The receiver already answered 2xx — the delivery SUCCEEDED. A bookkeeping failure here (e.g.// the lastTriggeredAt update on a flaky DB) must not reach the catch below: it would retry an@@ -695,8 +682,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {}// All direct-path retries exhausted — persist a durable failure record before giving up, mirroring// the queued processor's final-attempt path so the queue-disabled path isn't a blind spot.- const errMessage = redactSsrfError(error);- await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {+ await recordTerminalFailure(this.failureRepository, this.logger, {webhookId: webhook.id,sessionId: payload.sessionId,event: payload.event,@@ -704,8 +690,7 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {idempotencyKey: payload.idempotencyKey,deliveryId: payload.deliveryId,attempts: attempt,- lastStatusCode: statusCodeFromError(errMessage),- lastError: errMessage,+ error,});incrementWebhookDeliveryFailures();throw error;