Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(webhook): keep delivery records honest across 2xx bookkeeping, stalls, and shutdown (#933)
Yudhi Armyndharisa63d62413d82
diff --git a/src/common/utils/concurrency-limiter.spec.ts b/src/common/utils/concurrency-limiter.spec.tsindex a6c338e41..09729703e 100644--- a/src/common/utils/concurrency-limiter.spec.ts+++ b/src/common/utils/concurrency-limiter.spec.ts@@ -105,4 +105,35 @@ describe('ConcurrencyLimiter', () => {release(); // drain: active finishes, then the 50 parked tasks run one at a timeawait expect(Promise.all([active, ...parked])).resolves.toHaveLength(51);});++ it('close() rejects parked waiters and future arrivals but lets in-flight tasks finish', async () => {+ const limiter = new ConcurrencyLimiter(1);+ let release!: () => void;+ const active = limiter.run(+ () =>+ new Promise<void>(resolve => {+ release = resolve;+ }),+ );+ const parked = limiter.run(() => Promise.resolve('never runs'));+ expect(limiter.activeCount).toBe(1);+ expect(limiter.queuedCount).toBe(1);++ limiter.close();++ await expect(parked).rejects.toThrow('ConcurrencyLimiter closed');+ await expect(limiter.run(() => Promise.resolve('late'))).rejects.toThrow('ConcurrencyLimiter closed');+ expect(limiter.queuedCount).toBe(0);++ release();+ await expect(active).resolves.toBeUndefined(); // the in-flight task was NOT interrupted+ expect(limiter.activeCount).toBe(0);+ });++ it('close() with no parked waiters is a no-op and exposes a zero drain state', () => {+ const limiter = new ConcurrencyLimiter(2);+ expect(() => limiter.close()).not.toThrow();+ expect(limiter.activeCount).toBe(0);+ expect(limiter.queuedCount).toBe(0);+ });});diff --git a/src/common/utils/concurrency-limiter.ts b/src/common/utils/concurrency-limiter.tsindex bf42c7bf3..2808e9b6f 100644--- a/src/common/utils/concurrency-limiter.ts+++ b/src/common/utils/concurrency-limiter.ts@@ -6,7 +6,8 @@*/export class ConcurrencyLimiter {private active = 0;- private readonly waiters: Array<() => void> = [];+ private readonly waiters: Array<(error?: Error) => void> = [];+ private closed = false;/*** `max` is clamped to at least 1 so a misconfigured 0/negative value never deadlocks the gate.@@ -23,17 +24,45 @@ export class ConcurrencyLimiter {this.maxQueued = Math.max(0, Math.floor(maxQueued));}+ /** Tasks currently holding a slot (running). */+ get activeCount(): number {+ return this.active;+ }++ /** Tasks parked waiting for a slot. */+ get queuedCount(): number {+ return this.waiters.length;+ }++ /**+ * Stop admitting work: every parked task is rejected (its run() promise throws 'ConcurrencyLimiter+ * closed') and every future run() rejects the same way, so a shutdown path can drain instead of+ * leaving parked closures to vanish silently. In-flight tasks are NOT interrupted — they finish+ * (or fail) normally; watch {@link activeCount} to await them.+ */+ close(): void {+ this.closed = true;+ const parked = this.waiters.splice(0);+ for (const wake of parked) {+ wake(new Error('ConcurrencyLimiter closed'));+ }+ }+async run<T>(task: () => Promise<T>): Promise<T> {+ if (this.closed) {+ throw new Error('ConcurrencyLimiter closed');+ }if (this.active < this.max) {this.active++;} else {if (this.waiters.length >= this.maxQueued) {throw new Error('ConcurrencyLimiter queue full');}- // Park until a finishing task HANDS us its slot. We must not increment on wake: the count was- // never released (it was transferred), so re-incrementing would over-admit when a fresh run()- // raced into the microtask gap and already took a (wrongly-freed) slot.- await new Promise<void>(resolve => this.waiters.push(resolve));+ // Park until a finishing task HANDS us its slot (or close() rejects us). We must not increment+ // on wake: the count was never released (it was transferred), so re-incrementing would+ // over-admit when a fresh run() raced into the microtask gap and already took a (wrongly-freed)+ // slot.+ await new Promise<void>((resolve, reject) => this.waiters.push(error => (error ? reject(error) : resolve())));}try {return await task();diff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 3cdb44e4f..afcd566a7 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -138,6 +138,11 @@ export default () => ({// Bound parked inline deliveries as well as active sockets. Queue-full dispatches are recorded in// webhook_delivery_failures instead of retaining payload closures without limit.dispatchMaxQueued: parseInt(process.env.WEBHOOK_DISPATCH_MAX_QUEUED || '1000', 10),+ // Upper bound on the serialized webhook body after webhook:before hooks ran; oversize payloads+ // are recorded as undelivered instead of being sent/persisted. Default 1 MiB.+ maxPayloadBytes: parseInt(process.env.WEBHOOK_MAX_PAYLOAD_BYTES || '1048576', 10),+ // How long shutdown waits for in-flight direct deliveries to finish before abandoning them.+ shutdownDrainMs: parseInt(process.env.WEBHOOK_SHUTDOWN_DRAIN_MS || '5000', 10),},// API configurationdiff --git a/src/modules/queue/processors/webhook.processor.spec.ts b/src/modules/queue/processors/webhook.processor.spec.tsindex 484740cff..9ff5b0b3d 100644--- a/src/modules/queue/processors/webhook.processor.spec.ts+++ b/src/modules/queue/processors/webhook.processor.spec.ts@@ -6,6 +6,7 @@ import { Webhook } from '../../webhook/entities/webhook.entity';import { WebhookDeliveryFailure } from '../../webhook/entities/webhook-delivery-failure.entity';import { HookManager } from '../../../core/hooks';import { WebhookJobData } from '../../webhook/webhook.service';+import { getWebhookDeliveryFailuresTotal } from '../../../common/metrics/webhook-delivery-metrics';import { fetch as undiciFetch } from 'undici';// Delivery goes through undici's fetch (via the SSRF-pinning helper), so mock that, not global fetch.@@ -178,4 +179,67 @@ describe('WebhookProcessor', () => {expect(inserted.lastError).toBe('Destination address is not allowed');expect(inserted.lastError).not.toMatch(/169\.254\.169\.254/);});++ it('keeps the success outcome when post-delivery bookkeeping fails after a 2xx (no retry, no DLQ row)', async () => {+ mockFetch.mockResolvedValue({ ok: true, status: 200 });+ repo.update.mockRejectedValue(new Error('db down'));+ const failuresBefore = getWebhookDeliveryFailuresTotal();++ // Final attempt (attemptsMade=2, maxRetries=3): a bookkeeping throw reaching the catch would+ // file a dead-letter row AND rethrow for a retry — over an already-delivered event.+ const result = await processor.process(makeJob({ maxRetries: 3 }, 2));++ expect(result.success).toBe(true);+ expect(result.statusCode).toBe(200);+ expect(failureRepo.insert).not.toHaveBeenCalled();+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore);+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:delivered', expect.anything(), expect.anything());+ expect(hookManager.execute).not.toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());+ });++ // BullMQ fails a job that stalls more than maxStalledCount (default 1) WITHOUT calling process():+ // the worker emits 'failed' with "job stalled more than allowable limit". Those failures must land+ // in the same dead-letter/metric/hook channels as an ordinary final-attempt failure.+ describe('stall exhaustion (worker failed event)', () => {+ it('records a dead-letter row, metric, and webhook:error for a job failed by a double stall', async () => {+ const failuresBefore = getWebhookDeliveryFailuresTotal();++ await processor.onWorkerFailed(+ makeJob({ webhookId: 'wh-stall', url: 'https://8.8.8.8/s' }, 1),+ new Error('job stalled more than allowable limit'),+ );++ expect(failureRepo.insert).toHaveBeenCalledTimes(1);+ expect(failureRepo.insert).toHaveBeenCalledWith(+ expect.objectContaining({+ webhookId: 'wh-stall',+ url: 'https://8.8.8.8/s',+ sessionId: 'sess-1',+ attempts: 1,+ lastStatusCode: null, // no HTTP exchange completed on the stalled attempts+ lastError: 'job stalled more than allowable limit',+ }),+ );+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'webhook:error',+ expect.objectContaining({ webhookId: 'wh-stall', error: 'job stalled more than allowable limit' }),+ expect.anything(),+ );+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore + 1);+ });++ it('ignores ordinary delivery failures — process() already records those on the final attempt', async () => {+ await processor.onWorkerFailed(makeJob(), new Error('HTTP 500: Server Error'));++ expect(failureRepo.insert).not.toHaveBeenCalled();+ expect(hookManager.execute).not.toHaveBeenCalled();+ });++ it('ignores an undefined job (BullMQ may pass none when removeOnFail deleted it first)', async () => {+ await processor.onWorkerFailed(undefined, new Error('job stalled more than allowable limit'));++ expect(failureRepo.insert).not.toHaveBeenCalled();+ expect(hookManager.execute).not.toHaveBeenCalled();+ });+ });});diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.tsindex ec6990834..7724f5052 100644--- a/src/modules/queue/processors/webhook.processor.ts+++ b/src/modules/queue/processors/webhook.processor.ts@@ -1,4 +1,4 @@-import { Processor, WorkerHost } from '@nestjs/bullmq';+import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';import { Job } from 'bullmq';import { InjectRepository } from '@nestjs/typeorm';import { ConfigService } from '@nestjs/config';@@ -21,6 +21,15 @@ export interface WebhookJobResult {responseTime: number;}+/**+ * The exact `failedReason` BullMQ 5.80.x sets when a job stalls more than `maxStalledCount` (worker+ * default 1, so the SECOND genuine stall): the stalled checker (moveStalledJobsToWait Lua script)+ * stores it as the job's deferred failure, and the worker then fails the job itself — emitting+ * 'failed' WITHOUT ever calling process(). Lock renewal means a slow-but-alive processor never+ * stalls, so reaching this sentinel implies the job genuinely died twice mid-processing.+ */+const STALL_EXHAUSTION_MESSAGE = 'job stalled more than allowable limit';+// Override the Worker's connection so it does NOT inherit the producer's `enableOfflineQueue: false`// from the shared BullModule connection — the Worker must tolerate a brief Redis reconnect. Set an// explicit concurrency: BullMQ defaults a Worker to 1, which serializes every session's webhook@@ -80,10 +89,21 @@ export class WebhookProcessor extends WorkerHost {throw new Error(`HTTP ${status}: ${statusText}`);}- // Update lastTriggeredAt on successful delivery- await this.webhookRepository.update(webhookId, {- lastTriggeredAt: new Date(),- });+ // The receiver already answered 2xx — the delivery SUCCEEDED. Everything up to the return is+ // bookkeeping and must never throw back into the failure path: a rethrow would make BullMQ+ // retry (a duplicate POST for an already-delivered event) and, on the final attempt, file a+ // false dead-letter row. Log a bookkeeping failure and keep the success outcome.+ try {+ await this.webhookRepository.update(webhookId, {+ lastTriggeredAt: new Date(),+ });+ } catch (bookkeepingError) {+ this.logger.error(+ 'Webhook delivered but lastTriggeredAt update failed',+ bookkeepingError instanceof Error ? bookkeepingError.message : String(bookkeepingError),+ { webhookId, deliveryId: payload.deliveryId, action: 'webhook_bookkeeping_failed' },+ );+ }// Execute hook after successful deliveryawait this.hookManager.execute(@@ -170,4 +190,57 @@ export class WebhookProcessor extends WorkerHost {throw error;}}++ /**+ * A job failed by stall exhaustion never enters process(): the worker fails it internally after+ * the second stall and only emits 'failed'. Without this handler such a job bypasses every product+ * failure channel — no dead-letter row, no metric, no webhook:error hook. Normal delivery failures+ * are already recorded by process() on the final attempt (and non-final ones are retried), so this+ * handler MUST ignore anything but the stall-exhaustion sentinel, or every failure is recorded+ * twice. `job` can be undefined if removeOnFail deleted it first (we never set removeOnFail).+ */+ @OnWorkerEvent('failed')+ async onWorkerFailed(job: Job<WebhookJobData> | undefined, error: Error): Promise<void> {+ if (!job || error.message !== STALL_EXHAUSTION_MESSAGE) {+ return;+ }++ const { webhookId, url, event, payload } = job.data;+ const sessionId = payload.sessionId;++ this.logger.error('Webhook job failed after stalling beyond the recovery limit', error.message, {+ webhookId,+ event,+ deliveryId: payload.deliveryId,+ idempotencyKey: payload.idempotencyKey,+ attemptsMade: job.attemptsMade,+ action: 'webhook_stall_exhausted',+ });++ await this.hookManager.execute(+ 'webhook:error',+ {+ sessionId,+ event,+ webhookId,+ deliveryId: payload.deliveryId,+ error: error.message,+ attempt: job.attemptsMade,+ },+ { sessionId, source: 'WebhookProcessor' },+ );++ await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {+ webhookId,+ sessionId,+ event,+ url,+ idempotencyKey: payload.idempotencyKey,+ deliveryId: payload.deliveryId,+ attempts: job.attemptsMade,+ lastStatusCode: null, // no HTTP exchange completed on the stalled attempts+ lastError: error.message,+ });+ incrementWebhookDeliveryFailures();+ }}diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 4f61253a3..d24d18891 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -306,6 +306,52 @@ describe('WebhookService', () => {});});+ // The drain bound at shutdown must cover the per-delivery timeout, or a delivery that takes nearly+ // the full timeout is abandoned at shutdown. The defaults already cross (drain 5s < timeout 10s),+ // so the warning is the only signal an operator gets that their config silently truncates deliveries.+ describe('onModuleInit drain-vs-timeout warning', () => {+ const drainSpy = () =>+ jest.spyOn((service as unknown as { logger: { warn: jest.Mock; error: jest.Mock } }).logger, 'warn');++ const withConfig = (drainMs: number, timeoutMs: number, fn: () => void): void => {+ const orig = configService.get as jest.Mock;+ const impl = orig.getMockImplementation() as ((key: string, def?: unknown) => unknown) | undefined;+ orig.mockImplementation((key: string, def?: unknown) => {+ if (key === 'webhook.shutdownDrainMs') return drainMs;+ if (key === 'webhook.timeout') return timeoutMs;+ // Preserve the other keys the service reads at startup (queue.enabled etc.) by delegating+ // to the original implementation for anything we did not override.+ if (impl) return impl(key, def);+ return def;+ });+ try {+ fn();+ } finally {+ if (impl) orig.mockImplementation(impl);+ }+ };++ it('warns when WEBHOOK_SHUTDOWN_DRAIN_MS < WEBHOOK_TIMEOUT (the default-derived cross)', () => {+ const warn = drainSpy();+ withConfig(5000, 10000, () => service.onModuleInit());+ expect(warn).toHaveBeenCalledTimes(1);+ expect(warn.mock.calls[0][0]).toContain('WEBHOOK_SHUTDOWN_DRAIN_MS');+ expect(warn.mock.calls[0][0]).toContain('WEBHOOK_TIMEOUT');+ });++ it('does not warn when WEBHOOK_SHUTDOWN_DRAIN_MS >= WEBHOOK_TIMEOUT (drain covers the delivery)', () => {+ const warn = drainSpy();+ withConfig(15000, 10000, () => service.onModuleInit());+ expect(warn).not.toHaveBeenCalled();+ });++ it('does not warn when either value is non-finite (let the per-call site handle a bad config)', () => {+ const warn = drainSpy();+ withConfig(Number.NaN, 10000, () => service.onModuleInit());+ expect(warn).not.toHaveBeenCalled();+ });+ });+describe('dispatch (direct mode)', () => {const mockFetch = undiciFetch as jest.Mock;@@ -543,6 +589,97 @@ describe('WebhookService', () => {expect(body.deliveryId).not.toBe('PLUGIN-FORGED');});+ it('re-asserts event/sessionId/timestamp on the signed body after a tampering webhook:before hook', async () => {+ const webhook = createMockWebhook({ events: ['message.received'], secret: 'sek' });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });++ // The plugin rewrites every remaining identity field; other hook events pass through. The+ // canonical timestamp is captured from the payload the hook was given.+ let canonicalTimestamp = '';+ (hookManager.execute as jest.Mock).mockImplementation((event: string, ctx: { payload?: WebhookPayload }) => {+ if (event === 'webhook:before' && ctx.payload) {+ canonicalTimestamp = ctx.payload.timestamp;+ return Promise.resolve({+ continue: true,+ data: {+ payload: {+ ...ctx.payload,+ event: 'forged.event',+ sessionId: 'other-session',+ timestamp: '1999-01-01T00:00:00.000Z',+ },+ },+ });+ }+ return Promise.resolve({ continue: true, data: {} });+ });++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ const call = mockFetch.mock.calls[0] as [unknown, { headers: Record<string, string>; body: string }];+ const headers = call[1].headers;+ const body = JSON.parse(call[1].body) as WebhookPayload;+ expect(body.event).toBe('message.received');+ expect(body.sessionId).toBe('sess-1');+ expect(body.timestamp).toBe(canonicalTimestamp);+ // Body and headers tell the same story, and the signature covers the exact bytes sent — a+ // forged identity field would have diverged body from header/signature.+ expect(headers['X-OpenWA-Event']).toBe(body.event);+ const expected = `sha256=${crypto.createHmac('sha256', 'sek').update(call[1].body).digest('hex')}`;+ expect(headers['X-OpenWA-Signature']).toBe(expected);+ });++ it('records (never sends) a hook-mutated payload that exceeds the payload size cap', async () => {+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'queue.enabled') return false;+ if (key === 'webhook.maxPayloadBytes') return 1024;+ return def as T;+ });+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (hookManager.execute as jest.Mock).mockImplementation((event: string, ctx: { payload?: WebhookPayload }) =>+ event === 'webhook:before' && ctx.payload+ ? Promise.resolve({+ continue: true,+ data: { payload: { ...ctx.payload, data: { big: 'x'.repeat(64 * 1024) } } },+ })+ : Promise.resolve({ continue: true, data: {} }),+ );++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ expect(mockFetch).not.toHaveBeenCalled();+ expect(failureRepository.insert).toHaveBeenCalledTimes(1);+ expect(failureRepository.insert).toHaveBeenCalledWith(+ expect.objectContaining({+ webhookId: webhook.id,+ attempts: 0,+ lastStatusCode: null,+ }),+ );+ const oversizeInsert = (failureRepository.insert as jest.Mock).mock.calls as Array<[{ lastError: string }]>;+ expect(oversizeInsert[0][0].lastError).toContain('exceeding the 1024-byte cap');+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());+ });++ it('does not retry or record a failure when lastTriggeredAt bookkeeping fails after a 2xx', async () => {+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (repository.update as jest.Mock).mockRejectedValue(new Error('db down'));+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });+ const failuresBefore = getWebhookDeliveryFailuresTotal();++ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ // The receiver answered 2xx: no redelivery, no dead-letter row, delivered-hooks still fire.+ expect(mockFetch).toHaveBeenCalledTimes(1);+ expect(failureRepository.insert).not.toHaveBeenCalled();+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore);+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:delivered', expect.anything(), expect.anything());+ expect(hookManager.execute).not.toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());+ });+it("isolates each webhook's data so an in-place before-hook mutation cannot bleed across webhooks", async () => {const a = createMockWebhook({ id: 'wh-a', events: ['message.received'] });const b = createMockWebhook({ id: 'wh-b', events: ['message.received'] });@@ -658,8 +795,9 @@ describe('WebhookService', () => {describe('dispatch (queued mode) — serialization safety', () => {it('catches an unserializable webhook:before payload instead of aborting the loop / rejecting', async () => {(service as unknown as { queueEnabled: boolean }).queueEnabled = true;- // A plugin's webhook:before returns a payload JSON.stringify cannot serialize (BigInt). With the- // secret set, the queued branch signs JSON.stringify(finalPayload) — which throws.+ // A plugin's webhook:before returns a payload JSON.stringify cannot serialize (BigInt). The+ // preflight size check serializes the hook result, so the throw lands in the preflight catch+ // and the payload is recorded as undelivered.(hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: { payload: { x: 1n } } });const webhook = createMockWebhook({ secret: 'sek', events: ['message.received'] });(repository.find as jest.Mock).mockResolvedValue([webhook]);@@ -672,6 +810,85 @@ describe('WebhookService', () => {});});+ // ── shutdown drain ────────────────────────────────────────────────++ describe('shutdown drain', () => {+ const mockFetch = undiciFetch as jest.Mock;++ afterEach(() => mockFetch.mockReset());++ it('records parked deliveries on close and abandons a hung in-flight delivery within the drain bound', async () => {+ const hooks = [+ createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] }),+ createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] }),+ createMockWebhook({ id: 'wh-c', url: 'https://c.example/hook', events: ['message.received'] }),+ ];+ (repository.find as jest.Mock).mockResolvedValue(hooks);+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (hookManager.execute as jest.Mock).mockImplementation((_event: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {+ if (key === 'queue.enabled') return false;+ if (key === 'webhook.shutdownDrainMs') return 150;+ return def as T;+ });+ // One active slot, generous parked bound: B and C park behind the hanging A.+ (service as unknown as { dispatchLimiter: ConcurrencyLimiter }).dispatchLimiter = new ConcurrencyLimiter(1, 1000);++ let releaseActive: (value: unknown) => void = () => undefined;+ mockFetch.mockImplementation(() => new Promise(resolve => (releaseActive = resolve)));+ const loggerSpy = jest.spyOn((service as unknown as { logger: { error: jest.Mock } }).logger, 'error');++ const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });+ for (let i = 0; i < 20 && mockFetch.mock.calls.length === 0; i++) await new Promise(r => setImmediate(r));++ const start = Date.now();+ await service.onModuleDestroy();+ const elapsed = Date.now() - start;++ // Bounded: the hanging in-flight delivery did not stall teardown past the drain window.+ expect(elapsed).toBeLessThan(2000);+ // The two parked deliveries were rejected by the closing limiter and recorded as undelivered —+ // they never reached the receiver, so a dead-letter row is the honest record.+ expect(failureRepository.insert).toHaveBeenCalledTimes(2);+ const shutdownInserts = (failureRepository.insert as jest.Mock).mock.calls as Array<+ [{ webhookId: string; lastError: string }]+ >;+ const recorded = shutdownInserts.map(c => c[0]);+ expect(recorded.map(r => r.webhookId)).toEqual(expect.arrayContaining(['wh-b', 'wh-c']));+ for (const r of recorded) expect(r.lastError).toBe('ConcurrencyLimiter closed');+ // The in-flight delivery was NOT falsely dead-lettered (the receiver may have it); it is+ // logged as abandoned so the loss is still operator-visible.+ expect(+ loggerSpy.mock.calls.some(c => {+ const meta = c[2] as { action?: string; webhookId?: string } | undefined;+ return meta?.action === 'webhook_delivery_abandoned_shutdown' && meta.webhookId === 'wh-a';+ }),+ ).toBe(true);++ releaseActive({ ok: true, status: 200 });+ await dispatchP;+ loggerSpy.mockRestore();+ });++ it('records a dispatch that arrives after the limiter closed (no fetch, dead-letter row)', async () => {+ const webhook = createMockWebhook({ events: ['message.received'] });+ (repository.find as jest.Mock).mockResolvedValue([webhook]);+ (hookManager.execute as jest.Mock).mockImplementation((_event: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );++ await service.onModuleDestroy(); // nothing in flight → returns immediately+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });++ expect(mockFetch).not.toHaveBeenCalled();+ expect(failureRepository.insert).toHaveBeenCalledWith(+ expect.objectContaining({ webhookId: webhook.id, attempts: 0, lastError: 'ConcurrencyLimiter closed' }),+ );+ });+ });+// ── dispatch (smart filters) ──────────────────────────────────────// The event still has to match `events[]`; filters then refine WHETHER it fires based// on the payload. A webhook with no filters behaves exactly as before (fires on match).diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 98f456376..4a50f6748 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -55,12 +55,37 @@ export interface WebhookJobData {maxRetries: number;}+/**+ * Upper bound on the serialized webhook body after webhook:before hooks ran. Hook results are+ * untrusted — an unbounded mutation (or a genuinely huge media event) would POST a giant body and,+ * on failure, bloat the durable failure path. Oversize payloads are recorded as undelivered instead.+ * Default 1 MiB; override with WEBHOOK_MAX_PAYLOAD_BYTES.+ */+const DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES = 1024 * 1024;++/**+ * How long shutdown waits for in-flight direct deliveries (and their dead-letter bookkeeping) to+ * finish before abandoning them. Default 5s; override with WEBHOOK_SHUTDOWN_DRAIN_MS.+ */+const DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS = 5000;+@Injectable()export class WebhookService implements OnModuleInit, OnModuleDestroy {private readonly logger = createLogger('WebhookService');private readonly queueEnabled: boolean;private readonly dispatchLimiter: ConcurrencyLimiter;private cleanupTimer?: ReturnType<typeof setInterval>;+ /**+ * Context of every delivery currently holding a dispatch-limiter slot (queued-path enqueue or a+ * direct delivery with its retry loop). Used at shutdown to log, per delivery, what the bounded+ * drain had to abandon — those deliveries were neither completed nor safely recorded.+ */+ private readonly inFlightDeliveries = new Map<+ string,+ { webhookId: string; sessionId: string; event: string; idempotencyKey: string; url: string }+ >();+ /** Late bookkeeping (dead-letter rows) written by tasks the limiter already released — awaited on shutdown. */+ private readonly pendingBookkeeping = new Set<Promise<void>>();constructor(@InjectRepository(Webhook, 'data')@@ -92,6 +117,22 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {* receiver outage. (Mirrors AuditService's audit-log retention.)*/onModuleInit(): void {+ // Warn on the default-derived misconfiguration that silently truncates in-flight deliveries at+ // shutdown: WEBHOOK_SHUTDOWN_DRAIN_MS (default 5s) bounds how long onModuleDestroy waits for a+ // delivery in flight, while WEBHOOK_TIMEOUT (default 10s) bounds the delivery itself. When the+ // drain is shorter than the timeout, a delivery that takes nearly the full timeout is abandoned+ // (logged, not dead-lettered — the receiver may already have it). The defaults already cross, so+ // surface the cross so an operator who raised the timeout without raising the drain notices.+ const drainMs = this.configService.get<number>('webhook.shutdownDrainMs', DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS);+ const deliveryTimeoutMs = this.configService.get<number>('webhook.timeout', 10_000);+ if (Number.isFinite(drainMs) && Number.isFinite(deliveryTimeoutMs) && drainMs < deliveryTimeoutMs) {+ this.logger.warn(+ `WEBHOOK_SHUTDOWN_DRAIN_MS (${drainMs}ms) is shorter than WEBHOOK_TIMEOUT (${deliveryTimeoutMs}ms) — ` ++ `an in-flight delivery that takes nearly the full timeout will be abandoned at shutdown. ` ++ `Raise WEBHOOK_SHUTDOWN_DRAIN_MS to at least WEBHOOK_TIMEOUT if you want shutdown to wait for deliveries to complete.`,+ );+ }+const parsed = Number.parseInt(process.env.WEBHOOK_FAILURE_RETENTION_DAYS ?? '', 10);const retentionDays = Number.isInteger(parsed) ? Math.max(0, parsed) : 90;if (retentionDays <= 0) {@@ -112,10 +153,38 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {this.cleanupTimer.unref?.();}- onModuleDestroy(): void {+ /**+ * Bounded drain of the direct-delivery path (queued BullMQ jobs are durable in Redis and need no+ * drain). Closing the limiter rejects every PARKED delivery; the dispatch catch records each one in+ * webhook_delivery_failures like any other undispatched delivery. In-flight deliveries (a direct+ * delivery can outlive WEBHOOK_TIMEOUT via its backoff sleeps) get up to WEBHOOK_SHUTDOWN_DRAIN_MS+ * to finish; anything still running after that is about to be dropped by process exit, so it is+ * logged per delivery — a dead-letter row would be wrong there, since the receiver may already+ * have gotten the event. Nest awaits this hook during app.close(), so the bound also keeps+ * app.close() itself bounded.+ */+ async onModuleDestroy(): Promise<void> {if (this.cleanupTimer) {clearInterval(this.cleanupTimer);}+ this.dispatchLimiter.close();+ const drainMs = Math.max(+ 0,+ this.configService.get<number>('webhook.shutdownDrainMs', DEFAULT_WEBHOOK_SHUTDOWN_DRAIN_MS),+ );+ const deadline = Date.now() + drainMs;+ while (this.dispatchLimiter.activeCount > 0 || this.pendingBookkeeping.size > 0) {+ const remaining = deadline - Date.now();+ if (remaining <= 0) break;+ await this.delay(Math.min(50, remaining));+ }+ for (const lost of this.inFlightDeliveries.values()) {+ this.logger.error('Webhook delivery abandoned during shutdown', undefined, {+ ...lost,+ action: 'webhook_delivery_abandoned_shutdown',+ });+ }+ this.inFlightDeliveries.clear();}/**@@ -376,6 +445,9 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// payload.data in place would otherwise bleed that change into sibling webhooks.data: structuredClone(data),};+ // Captured BEFORE the hook chain: a hook may return the same payload object mutated in+ // place, so reading the canonical timestamp off the hook result afterwards is not safe.+ const payloadTimestamp = payload.timestamp;const { continue: shouldContinue, data: hookResult } = await this.hookManager.execute('webhook:before',@@ -393,9 +465,37 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Null/undefined hook results mean "no override", matching an object without payload.finalPayload = (hookResult as { payload?: WebhookPayload } | null | undefined)?.payload ?? payload;+ // Re-assert EVERY identity field after the (untrusted) hook chain. A hook may rewrite data,+ // but event/sessionId/timestamp and the dedupe ids must remain the server's values: the+ // receiver verifies the signature over this body and compares it against the X-OpenWA-*+ // headers, and failure records are filed by these fields — a rewritten sessionId/event+ // misfiles them across sessions.+ finalPayload.event = event;+ finalPayload.sessionId = sessionId;+ finalPayload.timestamp = payloadTimestamp;finalPayload.idempotencyKey = idempotencyKey;finalPayload.deliveryId = deliveryId;+ // Bound what a hook mutation can make us send. Serializing here also catches a poisoned+ // (BigInt/circular) hook result as a preflight failure, on BOTH the queued and direct paths.+ const maxPayloadBytes = this.configService.get<number>(+ 'webhook.maxPayloadBytes',+ DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES,+ );+ const payloadBytes = Buffer.byteLength(JSON.stringify(finalPayload), 'utf8');+ if (payloadBytes > maxPayloadBytes) {+ await recordUndelivered(+ webhook,+ deliveryId,+ idempotencyKey,+ new Error(+ `Webhook payload is ${payloadBytes} bytes after webhook:before hooks, exceeding the ${maxPayloadBytes}-byte cap`,+ ),+ 'webhook_payload_oversize',+ );+ return;+ }+headers = {...this.sanitizeCustomHeaders(webhook.headers),'Content-Type': 'application/json',@@ -545,12 +645,38 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {// Salt per webhook so sibling subscriptions cannot collide at the receiver's dedup boundary.const idempotencyKey = `${baseIdempotencyKey}_${webhook.id}`;return this.dispatchLimiter- .run(() => deliverOne(webhook, deliveryId, idempotencyKey))+ .run(async () => {+ this.inFlightDeliveries.set(deliveryId, {+ webhookId: webhook.id,+ sessionId,+ event,+ idempotencyKey,+ url: webhook.url,+ });+ try {+ await deliverOne(webhook, deliveryId, idempotencyKey);+ } finally {+ this.inFlightDeliveries.delete(deliveryId);+ }+ }).catch(async error => {if (error instanceof Error && error.message === 'ConcurrencyLimiter queue full') {await recordUndelivered(webhook, deliveryId, idempotencyKey, error, 'webhook_dispatch_capacity_exceeded');return;}+ if (error instanceof Error && error.message === 'ConcurrencyLimiter closed') {+ // Rejected by the shutdown drain before dispatching — record it like any other+ // undelivered delivery, and track the write so onModuleDestroy can await it (the+ // limiter slot bookkeeping no longer covers this task).+ const record = recordUndelivered(webhook, deliveryId, idempotencyKey, error, 'webhook_dispatch_shutdown');+ this.pendingBookkeeping.add(record);+ try {+ await record;+ } finally {+ this.pendingBookkeeping.delete(record);+ }+ return;+ }throw error;});});@@ -593,10 +719,21 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {throw new Error(`HTTP ${status}: ${statusText}`);}- // Update last triggered timestamp- await this.webhookRepository.update(webhook.id, {- lastTriggeredAt: new Date(),- });+ // 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+ // already-delivered webhook (duplicate POST) and, on the last attempt, file a false dead-letter+ // row. Log it and keep the success outcome.+ try {+ await this.webhookRepository.update(webhook.id, {+ lastTriggeredAt: new Date(),+ });+ } catch (bookkeepingError) {+ this.logger.error(+ `Webhook delivered to ${webhook.id} but lastTriggeredAt update failed`,+ bookkeepingError instanceof Error ? bookkeepingError.message : String(bookkeepingError),+ { webhookId: webhook.id, deliveryId: payload.deliveryId, action: 'webhook_bookkeeping_failed' },+ );+ }this.logger.debug(`Webhook delivered to ${webhook.id}`, {webhookId: webhook.id,diff --git a/test/webhooks.e2e-spec.ts b/test/webhooks.e2e-spec.tsindex 1bbfabc4d..998b4f3cc 100644--- a/test/webhooks.e2e-spec.ts+++ b/test/webhooks.e2e-spec.ts@@ -16,6 +16,7 @@ import { AuthService } from './../src/modules/auth/auth.service';import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';import { Session } from './../src/modules/session/entities/session.entity';import { WebhookService } from './../src/modules/webhook/webhook.service';+import { HookManager } from './../src/core/hooks';/*** End-to-end coverage for the webhooks module across the seam the unit specs can't reach: the REST@@ -324,6 +325,46 @@ describe('Webhooks (e2e)', () => {expect(headers['content-type']).toBe('application/json');expect(headers['x-custom']).toBe('ok'); // legitimate custom header preserved});++ it('keeps server identity fields on the signed body when a webhook:before hook tampers with them', async () => {+ const session = await nextSession();+ const secret = 'sig-secret';+ await createWebhook(session, { secret });++ const hookManager = app.get(HookManager);+ const hookId = hookManager.register('e2e-tamper', 'webhook:before', ctx => {+ const data = ctx.data as { payload: Record<string, unknown> };+ return Promise.resolve({+ continue: true,+ data: {+ ...data,+ payload: {+ ...data.payload,+ event: 'forged.event',+ sessionId: 'other-session',+ timestamp: '1999-01-01T00:00:00.000Z',+ },+ },+ });+ });+ try {+ await webhookService.dispatch(session, 'message.received', { from: '[email protected]' });+ await waitFor(() => received.length === 1);++ const { headers, raw, body } = received[0];+ // The tampered identity fields were re-asserted to the server's values, so the body still+ // matches the headers and the signature still verifies over the exact bytes received.+ expect(body.event).toBe('message.received');+ expect(body.sessionId).toBe(session);+ expect(body.timestamp).not.toBe('1999-01-01T00:00:00.000Z');+ expect(headers['x-openwa-event']).toBe('message.received');+ const expected = `sha256=${crypto.createHmac('sha256', secret).update(raw).digest('hex')}`;+ expect(headers['x-openwa-signature']).toBe(expected);+ expect((body as { data: { from: string } }).data.from).toBe('[email protected]'); // data stays hook-controlled+ } finally {+ hookManager.unregister(hookId);+ }+ });});// ── the test endpoint ─────────────────────────────────────────────