Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(webhook): split delivery engine into WebhookDeliveryService

Yudhi Armyndharis49f3d8a40a99
diff --git a/src/modules/webhook/delivery-failures-scope.spec.ts b/src/modules/webhook/delivery-failures-scope.spec.ts
index c3d0b2167..f7af86c8c 100644
--- a/src/modules/webhook/delivery-failures-scope.spec.ts
+++ b/src/modules/webhook/delivery-failures-scope.spec.ts
@@ -20,7 +20,9 @@ describe('WebhookService.listDeliveryFailures session scoping', () => {
await ds.initialize();
const failureRepo = ds.getRepository(WebhookDeliveryFailure);
const cfg = { get: () => false };
- service = new WebhookService({} as never, failureRepo, {} as never, cfg as never, {} as never, undefined);
+ // 2nd arg is the delivery-failure repo; the webhook/session repos and the delivery service
+ // (5th arg) are never touched by the scoping paths under test.
+ service = new WebhookService({} as never, failureRepo, {} as never, cfg as never, {} as never);
for (const sessionId of ['sessA', 'sessB']) {
await failureRepo.save(
failureRepo.create({
diff --git a/src/modules/webhook/webhook-delivery.service.spec.ts b/src/modules/webhook/webhook-delivery.service.spec.ts
new file mode 100644
index 000000000..68c6ad2f4
--- /dev/null
+++ b/src/modules/webhook/webhook-delivery.service.spec.ts
@@ -0,0 +1,1348 @@
+// SSRF protection is now ON by default; resolve any host to a public IP so existing
+// dispatch/create tests stay offline. Literal-IP tests (8.8.8.8 / 127.0.0.1) bypass lookup.
+jest.mock('dns/promises', () => ({
+ lookup: jest.fn().mockResolvedValue([{ address: '93.184.216.34', family: 4 }]),
+}));
+
+// Webhook delivery goes through undici's fetch (via the SSRF-pinning helper); mock it, not global fetch.
+jest.mock('undici', () => {
+ const actual = jest.requireActual<typeof import('undici')>('undici');
+ return { __esModule: true, ...actual, fetch: jest.fn() };
+});
+
+import { Test, TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+import { getQueueToken } from '@nestjs/bullmq';
+import { Repository } from 'typeorm';
+import { ConfigService } from '@nestjs/config';
+import * as crypto from 'crypto';
+import { fetch as undiciFetch } from 'undici';
+import { WebhookDeliveryService, WebhookPayload, WebhookJobData } from './webhook-delivery.service';
+import { Webhook } from './entities/webhook.entity';
+import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';
+import { Session } from '../session/entities/session.entity';
+import { WebhookFilters } from './filters/filter-types';
+import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { userPart } from '../../engine/identity/wa-id';
+import { HookManager } from '../../core/hooks';
+import { QUEUE_NAMES } from '../queue/queue-names';
+import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
+
+function createMockWebhook(overrides: Partial<Webhook> = {}): Webhook {
+ return {
+ id: 'wh-uuid-1',
+ sessionId: 'sess-1',
+ url: 'https://example.com/webhook',
+ events: ['message.received'],
+ secret: null,
+ headers: {},
+ filters: null,
+ active: true,
+ retryCount: 3,
+ lastTriggeredAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ session: undefined as unknown as Session,
+ ...overrides,
+ };
+}
+
+describe('WebhookDeliveryService', () => {
+ let service: WebhookDeliveryService;
+ let repository: jest.Mocked<Partial<Repository<Webhook>>>;
+ let failureRepository: jest.Mocked<Partial<Repository<WebhookDeliveryFailure>>>;
+ let configService: jest.Mocked<Partial<ConfigService>>;
+ let hookManager: jest.Mocked<Partial<HookManager>>;
+ let webhookQueue: jest.Mocked<Record<string, jest.Mock>>;
+ let lidStore: { getCached: jest.Mock; resolveLid: jest.Mock };
+
+ beforeEach(async () => {
+ repository = {
+ find: jest.fn(),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ };
+
+ failureRepository = {
+ insert: jest.fn().mockResolvedValue({}),
+ find: jest.fn().mockResolvedValue([]),
+ delete: jest.fn().mockResolvedValue({ affected: 0 }),
+ };
+
+ configService = {
+ get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
+ if (key === 'queue.enabled') return false;
+ if (key === 'webhook.retryDelay') return 100;
+ // Distinct from the hardcoded 10000 fallback so a regression to a literal timeout is caught.
+ if (key === 'webhook.timeout') return 25000;
+ // A small, non-default cap so the fan-out-bound test (5 webhooks) can assert the limiter holds.
+ if (key === 'webhook.dispatchConcurrency') return 2;
+ return def as T;
+ }),
+ };
+
+ hookManager = {
+ execute: jest.fn().mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload: {} },
+ }),
+ };
+
+ webhookQueue = {
+ add: jest.fn().mockResolvedValue(undefined),
+ };
+
+ lidStore = {
+ getCached: jest.fn().mockReturnValue(null),
+ // Mirrors the real implementation so tests keep driving resolution through getCached mocks.
+ resolveLid: jest.fn((jid: string) => (lidStore.getCached(userPart(jid)) as string | null | undefined) ?? null),
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ WebhookDeliveryService,
+ { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
+ { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },
+ { provide: ConfigService, useValue: configService },
+ { provide: HookManager, useValue: hookManager },
+ { provide: LidMappingStoreService, useValue: lidStore },
+ { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
+ ],
+ }).compile();
+
+ service = module.get<WebhookDeliveryService>(WebhookDeliveryService);
+ });
+
+ // 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;
+
+ beforeEach(() => {
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+ });
+
+ afterEach(() => {
+ mockFetch.mockReset();
+ });
+
+ it('resolves (never rejects) when the webhook lookup fails — callers fire-and-forget it', async () => {
+ (repository.find as jest.Mock).mockRejectedValue(new Error('db down'));
+ await expect(service.dispatch('sess-1', 'message.received', { x: 1 })).resolves.toBeUndefined();
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('should dispatch to webhooks matching the event', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ // Mock hook to return the payload properly
+ const mockPayload: WebhookPayload = {
+ event: 'message.received',
+ timestamp: new Date().toISOString(),
+ sessionId: 'sess-1',
+ idempotencyKey: 'test-key',
+ deliveryId: 'test-delivery',
+ data: { from: '[email protected]' },
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'message.received',
+ payload: mockPayload,
+ },
+ });
+
+ const timeoutSpy = jest.spyOn(AbortSignal, 'timeout');
+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://example.com/webhook',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ // Direct delivery path honors the configured WEBHOOK_TIMEOUT, not a literal 10s.
+ expect(timeoutSpy).toHaveBeenCalledWith(25000);
+ timeoutSpy.mockRestore();
+ });
+
+ it('dispatches to sibling webhooks concurrently — a slow receiver does not block the others', async () => {
+ const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
+ const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([wA, wB]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ let resolveSlow: (v: unknown) => void = () => undefined;
+ const slow = new Promise(r => (resolveSlow = r));
+ const calledUrls: string[] = [];
+ mockFetch.mockImplementation((url: string) => {
+ calledUrls.push(url);
+ return url.includes('a.example') ? slow : Promise.resolve({ ok: true, status: 200 });
+ });
+
+ const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+ // Flush until both fetches fire (or give up): with the old sequential loop, only A ever fires while
+ // it hangs, so this exhausts and the assertion below fails — exactly the regression we guard.
+ for (let i = 0; i < 20 && calledUrls.length < 2; i++) {
+ await new Promise(r => setImmediate(r));
+ }
+
+ // B is delivered even though A is still hanging — sequential code would not have reached B yet.
+ expect(calledUrls).toEqual(expect.arrayContaining(['https://a.example/hook', 'https://b.example/hook']));
+
+ resolveSlow({ ok: true, status: 200 });
+ await dispatchP;
+ });
+
+ it('bounds concurrent delivery to WEBHOOK_DISPATCH_CONCURRENCY (cap=2, 5 webhooks → peak ≤ 2)', async () => {
+ const hooks = Array.from({ length: 5 }, (_, i) =>
+ createMockWebhook({ id: `wh-${i}`, url: `https://h${i}.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).mockResolvedValue({ continue: true, data: {} });
+
+ let inFlight = 0;
+ let peak = 0;
+ let resolved = 0;
+ const releasers: Array<() => void> = [];
+ mockFetch.mockImplementation(
+ () =>
+ new Promise(resolve => {
+ inFlight += 1;
+ peak = Math.max(peak, inFlight);
+ releasers.push(() => {
+ inFlight -= 1;
+ resolved += 1;
+ resolve({ ok: true, status: 200 });
+ });
+ }),
+ );
+
+ const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+ // Let the limiter admit up to the cap (2) and each reach fetch. The other 3 stay parked.
+ for (let i = 0; i < 20 && releasers.length < 2; i++) {
+ await new Promise(r => setImmediate(r));
+ }
+ expect(inFlight).toBeLessThanOrEqual(2);
+ // Release in a macrotask loop: freeing a slot lets the limiter admit the next webhook, whose fetch
+ // pushes a fresh releaser on the NEXT tick — a single synchronous drain would miss it and hang.
+ for (let i = 0; i < 50 && resolved < 5; i++) {
+ while (releasers.length) (releasers.shift() as () => void)();
+ await new Promise(r => setImmediate(r));
+ }
+ await dispatchP;
+ // Peak across the whole run never exceeded the cap. (An unbounded fan-out would reach 5.)
+ expect(peak).toBeLessThanOrEqual(2);
+ expect(mockFetch).toHaveBeenCalledTimes(5);
+ });
+
+ it('records a durable failure when the bounded dispatch queue is full', async () => {
+ const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
+ const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([wA, wB]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockImplementation((_event: string, data: unknown) =>
+ Promise.resolve({ continue: true, data }),
+ );
+ (service as unknown as { dispatchLimiter: ConcurrencyLimiter }).dispatchLimiter = new ConcurrencyLimiter(1, 0);
+
+ let release: (value: unknown) => void = () => undefined;
+ mockFetch.mockImplementation(() => new Promise(resolve => (release = resolve)));
+
+ const pending = 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));
+ release({ ok: true, status: 200 });
+ await pending;
+
+ expect(failureRepository.insert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ webhookId: 'wh-b',
+ attempts: 0,
+ lastError: 'ConcurrencyLimiter queue full',
+ }),
+ );
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('salts each sibling webhook with a distinct idempotency key so one receiver cannot dedupe out another', async () => {
+ const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
+ const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([wA, wB]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+
+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+
+ const keyByUrl = new Map<string, string>();
+ for (const call of mockFetch.mock.calls as [string, { headers: Record<string, string> }][]) {
+ keyByUrl.set(call[0], call[1].headers['X-OpenWA-Idempotency-Key']);
+ }
+ const keyA = keyByUrl.get('https://a.example/hook');
+ const keyB = keyByUrl.get('https://b.example/hook');
+ // Same event + payload, but two distinct endpoints must not collide on the dedupe header.
+ expect(keyA).toBeTruthy();
+ expect(keyB).toBeTruthy();
+ expect(keyA).not.toBe(keyB);
+ });
+
+ it('falls back to the original payload when a before-hook omits payload (no undefined body)', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ // A misbehaving plugin returns continue:true but no `payload` key on the result.
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received' },
+ });
+
+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+
+ expect(mockFetch).toHaveBeenCalled();
+ const callArgs = mockFetch.mock.calls[0] as [unknown, { body: string }];
+ const body = JSON.parse(callArgs[1].body) as WebhookPayload;
+ expect(body).not.toBeUndefined();
+ expect(body.event).toBe('message.received');
+ expect(body.data).toEqual({ from: '[email protected]' });
+ });
+
+ it('falls back to the original payload when a before-hook returns null data', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: null });
+
+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+
+ const callArgs = mockFetch.mock.calls[0] as [unknown, { body: string }];
+ const body = JSON.parse(callArgs[1].body) as WebhookPayload;
+ expect(body.event).toBe('message.received');
+ expect(body.data).toEqual({ from: '[email protected]' });
+ });
+
+ it('keeps the server-canonical idempotency/delivery ids on the signed body, overriding a tampering plugin', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ // A webhook:before plugin returns a payload with forged identifiers (other hook events pass through).
+ (hookManager.execute as jest.Mock).mockImplementation((event: string, ctx: { payload?: WebhookPayload }) =>
+ event === 'webhook:before' && ctx.payload
+ ? Promise.resolve({
+ continue: true,
+ data: { payload: { ...ctx.payload, idempotencyKey: 'PLUGIN-FORGED', deliveryId: 'PLUGIN-FORGED' } },
+ })
+ : 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;
+ // Receivers dedupe on the header, so the signed body field must equal the header — and both must
+ // be the server's value, not the plugin's forgery.
+ expect(body.idempotencyKey).toBe(headers['X-OpenWA-Idempotency-Key']);
+ expect(body.deliveryId).toBe(headers['X-OpenWA-Delivery-Id']);
+ expect(body.idempotencyKey).not.toBe('PLUGIN-FORGED');
+ 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('replaces over-threshold inline media with the omitted marker before fan-out (input not mutated)', async () => {
+ (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
+ if (key === 'queue.enabled') return false;
+ if (key === 'webhook.mediaInlineMaxBytes') return 1024;
+ return def as T;
+ });
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ const base64 = Buffer.alloc(2048, 7).toString('base64'); // 2048 decoded bytes > 1024 cap
+ const data: Record<string, unknown> = {
+ media: { mimetype: 'image/jpeg', data: base64 },
+ };
+ await service.dispatch('sess-1', 'message.received', data);
+
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
+ data: { media: Record<string, unknown> };
+ };
+ // The documented marker shape — the blob itself never reaches the wire.
+ expect(body.data.media).toEqual({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 2048 });
+ // The caller's event data keeps its media — shedding works on a copy.
+ expect((data.media as { data?: string }).data).toBe(base64);
+ expect(failureRepository.insert).not.toHaveBeenCalled();
+ });
+
+ it('keeps under-threshold media inline, unchanged', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ const base64 = Buffer.alloc(512, 3).toString('base64'); // default inline cap is 1 MiB
+ await service.dispatch('sess-1', 'message.received', {
+ media: { mimetype: 'image/jpeg', data: base64 },
+ });
+
+ const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
+ data: { media: { data?: string; omitted?: boolean } };
+ };
+ expect(body.data.media.data).toBe(base64);
+ expect(body.data.media.omitted).toBeUndefined();
+ });
+
+ it('sheds inline media to fit the payload budget instead of recording the event undelivered', 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;
+ if (key === 'webhook.mediaInlineMaxBytes') return 50 * 1024 * 1024; // pre-fan-out shed stays out of the way
+ return def as T;
+ });
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ // 2048 decoded bytes → ~2.7 KB base64 → serialized payload over the 1024-byte budget.
+ const base64 = Buffer.alloc(2048, 9).toString('base64');
+ await service.dispatch('sess-1', 'message.received', {
+ media: { mimetype: 'image/jpeg', filename: 'photo.jpg', data: base64 },
+ });
+
+ // Delivered with the marker (filename preserved) — NOT dropped as undelivered.
+ expect(mockFetch).toHaveBeenCalledTimes(1);
+ const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
+ data: { media: Record<string, unknown> };
+ };
+ expect(body.data.media).toEqual({
+ mimetype: 'image/jpeg',
+ filename: 'photo.jpg',
+ omitted: true,
+ sizeBytes: 2048,
+ });
+ expect(failureRepository.insert).not.toHaveBeenCalled();
+ });
+
+ it('still records undelivered when an over-budget payload has no inline media to shed', 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).mockResolvedValue({ continue: true, data: {} });
+
+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]', body: 'y'.repeat(4096) });
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ expect(failureRepository.insert).toHaveBeenCalledTimes(1);
+ });
+
+ 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'] });
+ (repository.find as jest.Mock).mockResolvedValue([a, b]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ // The hook mutates payload.data in place every time it runs (returns no payload key → finalPayload
+ // is the mutated input). With a shared data object the second webhook would see the first's tag.
+ (hookManager.execute as jest.Mock).mockImplementation((event: string, ctx: { payload?: WebhookPayload }) => {
+ if (event === 'webhook:before' && ctx.payload) {
+ const d = ctx.payload.data as { tag?: number };
+ d.tag = (d.tag ?? 0) + 1;
+ return Promise.resolve({ continue: true, data: { payload: ctx.payload } });
+ }
+ return Promise.resolve({ continue: true, data: {} });
+ });
+
+ await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+
+ const bodyA = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
+ data: { tag: number };
+ };
+ const bodyB = JSON.parse((mockFetch.mock.calls[1] as [unknown, { body: string }])[1].body) as {
+ data: { tag: number };
+ };
+ // Each webhook starts from its own clone of the original data, so both see exactly one increment.
+ expect(bodyA.data.tag).toBe(1);
+ expect(bodyB.data.tag).toBe(1);
+ });
+
+ it('should NOT dispatch to webhooks that do not match the event', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+
+ await service.dispatch('sess-1', 'session.ready', { phone: '628123456789' });
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
+ it('should dispatch to webhooks with wildcard (*) event filter', async () => {
+ const webhook = createMockWebhook({ events: ['*'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ const wildcardPayload: WebhookPayload = {
+ event: 'anything.goes',
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: '',
+ deliveryId: '',
+ data: {},
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'anything.goes',
+ payload: wildcardPayload,
+ },
+ });
+
+ await service.dispatch('sess-1', 'anything.goes', {});
+
+ expect(mockFetch).toHaveBeenCalled();
+ });
+
+ it('should skip dispatch when plugin cancels via hook', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: false, data: {} });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+ });
+
+ 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). 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]);
+
+ // Must NOT reject (the loop/dispatch promise stays settled); the throw is caught + logged.
+ await expect(service.dispatch('sess-1', 'message.received', { ok: true })).resolves.toBeUndefined();
+
+ expect(webhookQueue.add).not.toHaveBeenCalled(); // never enqueued the un-signable job
+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
+ });
+ });
+
+ // ── 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('queued mode: parked enqueues drain to the queue on shutdown instead of dead-lettering', async () => {
+ (service as unknown as { queueEnabled: boolean }).queueEnabled = true;
+ 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);
+ (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 true;
+ if (key === 'webhook.shutdownDrainMs') return 1000;
+ return def as T;
+ });
+ // One active slot, generous parked bound: B and C park behind A, whose enqueue hangs.
+ (service as unknown as { dispatchLimiter: ConcurrencyLimiter }).dispatchLimiter = new ConcurrencyLimiter(1, 1000);
+
+ let releaseActive: (value: unknown) => void = () => undefined;
+ let firstAdd = true;
+ (webhookQueue.add as jest.Mock).mockImplementation(
+ () =>
+ new Promise(resolve => {
+ if (firstAdd) {
+ firstAdd = false;
+ releaseActive = resolve;
+ } else {
+ resolve(undefined);
+ }
+ }),
+ );
+
+ const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+ for (let i = 0; i < 20 && webhookQueue.add.mock.calls.length === 0; i++) await new Promise(r => setImmediate(r));
+
+ // Shutdown starts while A holds the slot and B/C are parked. Queued mode must not close the
+ // limiter: a parked task is just webhookQueue.add() — durable in Redis once it runs — and it
+ // holds an activeCount slot via handoff, so the drain loop waits for the whole chain.
+ const destroyP = service.onModuleDestroy();
+ releaseActive(undefined);
+ await destroyP;
+ await dispatchP;
+
+ // All three reached the queue; none was dead-lettered as webhook_dispatch_shutdown.
+ expect(webhookQueue.add).toHaveBeenCalledTimes(3);
+ expect(failureRepository.insert).not.toHaveBeenCalled();
+ });
+
+ 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).
+
+ describe('dispatch (smart filters)', () => {
+ const mockFetch = undiciFetch as jest.Mock;
+
+ beforeEach(() => {
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ });
+
+ afterEach(() => mockFetch.mockReset());
+
+ const conds = (...conditions: WebhookFilters['conditions']): WebhookFilters => ({ conditions });
+
+ // events:['*'] isolates the filter logic from event-name matching. Returns the number
+ // of outbound HTTP deliveries the dispatch performed (1 = fired, 0 = filtered out).
+ async function deliveries(
+ filters: WebhookFilters | null,
+ event: string,
+ data: Record<string, unknown>,
+ ): Promise<number> {
+ mockFetch.mockClear();
+ const webhook = createMockWebhook({ events: ['*'], filters });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ await service.dispatch('sess-1', event, data);
+ return mockFetch.mock.calls.length;
+ }
+
+ // A condition names a field the event's payload does not carry — `sender` resolves from
+ // author/from, and message.ack dispatches { id, messageId, status, ack }. The condition cannot
+ // match, so the delivery is dropped. That is the filter working as specified; what was missing
+ // was any way to find out it had happened.
+ it('logs when a filter suppresses a subscribed webhook', async () => {
+ const logger = (service as unknown as { logger: { debug: jest.Mock } }).logger;
+ const spy = jest.spyOn(logger, 'debug');
+
+ expect(
+ await deliveries(conds({ field: 'sender', operator: 'is', value: ['[email protected]'] }), 'message.ack', {
+ messageId: 'm1',
+ status: 'read',
+ }),
+ ).toBe(0);
+
+ const suppressed = spy.mock.calls.filter(c => String(c[0]).includes('suppressed a delivery'));
+ expect(suppressed).toHaveLength(1);
+ expect(suppressed[0][1]).toMatchObject({ event: 'message.ack', subscribed: 1, suppressed: 1 });
+ // The payload's own fields are recorded, because the usual cause is a condition on a field
+ // this event does not have — that list is the answer to "why did nothing fire?".
+ expect((suppressed[0][1] as { payloadFields: string }).payloadFields).toBe('messageId,status');
+ spy.mockRestore();
+ });
+
+ it('stays quiet when nothing is suppressed', async () => {
+ const logger = (service as unknown as { logger: { debug: jest.Mock } }).logger;
+ const spy = jest.spyOn(logger, 'debug');
+
+ expect(
+ await deliveries(conds({ field: 'sender', operator: 'is', value: ['[email protected]'] }), 'message.received', {
+ }),
+ ).toBe(1);
+
+ expect(spy.mock.calls.filter(c => String(c[0]).includes('suppressed a delivery'))).toHaveLength(0);
+ spy.mockRestore();
+ });
+
+ it('fires with no filters (additive: zero-config behaviour is unchanged)', async () => {
+ expect(await deliveries(null, 'message.received', { from: '[email protected]' })).toBe(1);
+ expect(await deliveries(conds(), 'message.received', { from: '[email protected]' })).toBe(1);
+ });
+
+ it('sender "is": fires on a match, filters out a mismatch', async () => {
+ const f = conds({ field: 'sender', operator: 'is', value: ['[email protected]'] });
+ expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(1);
+ expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(0);
+ });
+
+ it('sender "isNot": filters out the named sender, fires for everyone else', async () => {
+ const f = conds({ field: 'sender', operator: 'isNot', value: ['[email protected]'] });
+ expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(0);
+ expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(1);
+ });
+
+ it('resolves sender to the group participant (author), not the group JID', async () => {
+ const f = conds({ field: 'sender', operator: 'is', value: ['[email protected]'] });
+ const data = { from: '[email protected]', author: '[email protected]', isGroup: true };
+ expect(await deliveries(f, 'message.received', data)).toBe(1);
+ });
+
+ it('ANDs multiple conditions (all must match)', async () => {
+ const f = conds(
+ { field: 'sender', operator: 'is', value: ['[email protected]'] },
+ { field: 'body', operator: 'contains', value: 'invoice' },
+ );
+ expect(await deliveries(f, 'message.received', { from: '[email protected]', body: 'the invoice is ready' })).toBe(1);
+ expect(await deliveries(f, 'message.received', { from: '[email protected]', body: 'lunch?' })).toBe(0);
+ expect(await deliveries(f, 'message.received', { from: '[email protected]', body: 'invoice' })).toBe(0);
+ });
+
+ it('body "contains" is case-insensitive by default and respects caseSensitive', async () => {
+ const ci = conds({ field: 'body', operator: 'contains', value: 'ping' });
+ expect(await deliveries(ci, 'message.received', { body: 'PING me' })).toBe(1);
+ const cs = conds({ field: 'body', operator: 'contains', value: 'ping', caseSensitive: true });
+ expect(await deliveries(cs, 'message.received', { body: 'PING me' })).toBe(0);
+ });
+
+ it('body "equals" fires only on an exact match', async () => {
+ const f = conds({ field: 'body', operator: 'equals', value: 'order 42' });
+ expect(await deliveries(f, 'message.received', { body: 'order 42' })).toBe(1);
+ expect(await deliveries(f, 'message.received', { body: 'order 4242' })).toBe(0);
+ });
+
+ it('type "is" matches one of the listed message types', async () => {
+ const f = conds({ field: 'type', operator: 'is', value: ['image', 'video'] });
+ expect(await deliveries(f, 'message.received', { type: 'image' })).toBe(1);
+ expect(await deliveries(f, 'message.received', { type: 'text' })).toBe(0);
+ });
+
+ it('boolean fields: fromMe and hasMedia', async () => {
+ const fromMe = conds({ field: 'fromMe', operator: 'is', value: true });
+ expect(await deliveries(fromMe, 'message.received', { fromMe: true })).toBe(1);
+ expect(await deliveries(fromMe, 'message.received', { fromMe: false })).toBe(0);
+
+ const hasMedia = conds({ field: 'hasMedia', operator: 'is', value: true });
+ expect(await deliveries(hasMedia, 'message.received', { media: { mimetype: 'image/png' } })).toBe(1);
+ expect(await deliveries(hasMedia, 'message.received', { body: 'just text' })).toBe(0);
+ });
+
+ it('filters message.edited through a wildcard subscription using its normalized message fields', async () => {
+ const f = conds(
+ { field: 'sender', operator: 'is', value: ['[email protected]'] },
+ { field: 'body', operator: 'contains', value: 'invoice' },
+ { field: 'type', operator: 'is', value: ['image'] },
+ { field: 'hasMedia', operator: 'is', value: true },
+ );
+ const data = {
+ author: '[email protected]',
+ body: 'Updated invoice',
+ type: 'image',
+ hasMedia: true,
+ };
+
+ expect(await deliveries(f, 'message.edited', data)).toBe(1);
+ expect(await deliveries(f, 'message.edited', { ...data, body: 'lunch?', hasMedia: false })).toBe(0);
+ });
+
+ it('mentions: fires when the message mentions one of the listed JIDs', async () => {
+ const f = conds({ field: 'mentions', operator: 'is', value: ['[email protected]'] });
+ expect(await deliveries(f, 'message.received', { mentionedIds: ['[email protected]', '[email protected]'] })).toBe(1);
+ expect(await deliveries(f, 'message.received', { mentionedIds: ['[email protected]'] })).toBe(0);
+ });
+
+ it('skips message-only conditions on a non-message event (so it still fires)', async () => {
+ // A webhook subscribed to '*' with message filters must not suppress non-message events.
+ const f = conds({ field: 'sender', operator: 'is', value: ['[email protected]'] });
+ expect(await deliveries(f, 'session.status', { status: 'connected' })).toBe(1);
+ expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(0);
+ });
+
+ it('resolves a lid sender to its phone via the table, so a phone filter fires (else a silent miss)', async () => {
+ const f = conds({ field: 'sender', operator: 'is', value: ['628999'] });
+ const data = { from: '[email protected]', author: '111@lid', isGroup: true };
+
+ // No mapping yet -> the lid author never matches the phone filter.
+ lidStore.getCached.mockReturnValue(null);
+ expect(await deliveries(f, 'message.received', data)).toBe(0);
+
+ // Table maps lid 111 -> 628999 -> the same message now fires.
+ lidStore.getCached.mockImplementation((lid: string) => (lid === '111' ? '628999' : null));
+ expect(await deliveries(f, 'message.received', data)).toBe(1);
+ });
+ });
+
+ // ── custom-header sanitization ───────────────────────────────
+
+ describe('custom header merge', () => {
+ it('drops reserved custom headers so the system headers always win', async () => {
+ const webhook = createMockWebhook({
+ events: ['message.received'],
+ headers: { 'X-OpenWA-Event': 'forged', 'Content-Type': 'text/plain', 'X-Custom': 'ok' },
+ });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ const captured: Record<string, string> = {};
+ const mockFetch = undiciFetch as jest.Mock;
+ mockFetch.mockImplementation((_url: string, opts: RequestInit) => {
+ Object.assign(captured, opts.headers as Record<string, string>);
+ return Promise.resolve({ ok: true, status: 200 });
+ });
+
+ const payload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload },
+ });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ expect(captured['X-OpenWA-Event']).toBe('message.received'); // system value, not 'forged'
+ expect(captured['Content-Type']).toBe('application/json');
+ expect(captured['X-Custom']).toBe('ok'); // legitimate custom header preserved
+ mockFetch.mockReset();
+ });
+ });
+
+ // ── redirect refusal ─────────────────────────────────────────
+
+ describe('dispatch — redirect refusal', () => {
+ const mockFetch = undiciFetch as jest.Mock;
+ const origProtect = process.env.WEBHOOK_SSRF_PROTECT;
+
+ beforeEach(() => {
+ process.env.WEBHOOK_SSRF_PROTECT = 'true';
+ });
+
+ afterEach(() => {
+ mockFetch.mockReset();
+ if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;
+ else process.env.WEBHOOK_SSRF_PROTECT = origProtect;
+ });
+
+ it('does NOT follow a redirect and treats it as a delivery failure when protection is on', async () => {
+ // Public literal IP → assertSafeFetchUrl passes with no DNS lookup; retryCount:1 → no retry loop.
+ const webhook = createMockWebhook({
+ url: 'https://8.8.8.8/webhook',
+ events: ['message.received'],
+ retryCount: 1,
+ });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ // Simulate undici's redirect:'manual' result — an opaque redirect, never followed.
+ mockFetch.mockResolvedValue({ ok: false, status: 0, type: 'opaqueredirect' });
+
+ const payload: WebhookPayload = {
+ event: 'message.received',
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ data: {},
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload },
+ });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ // fetch was issued with redirect:'manual' and the redirect was NOT followed (no success path)
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://8.8.8.8/webhook',
+ expect.objectContaining({ redirect: 'manual' }),
+ );
+ expect(repository.update).not.toHaveBeenCalled(); // lastTriggeredAt never set → delivery failed
+ expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
+ });
+ });
+
+ // ── generateSignature (via dispatch) ──────────────────────────────
+
+ describe('generateSignature', () => {
+ it('should produce valid HMAC-SHA256 signature', async () => {
+ const webhook = createMockWebhook({
+ events: ['message.received'],
+ secret: 'test-secret-123',
+ });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ const capturedHeaders: Record<string, string> = {};
+ const mockFetch = undiciFetch as jest.Mock;
+ mockFetch.mockImplementation((_url: string, opts: RequestInit) => {
+ Object.assign(capturedHeaders, opts.headers as Record<string, string>);
+ return Promise.resolve({ ok: true, status: 200 });
+ });
+
+ const sigPayload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'message.received',
+ payload: sigPayload,
+ },
+ });
+
+ await service.dispatch('sess-1', 'message.received', {});
+
+ // Verify signature format
+ expect(capturedHeaders['X-OpenWA-Signature']).toMatch(/^sha256=[a-f0-9]{64}$/);
+
+ // Verify signature correctness against the ACTUAL delivered body. The body now carries the
+ // server-canonical idempotency/delivery ids (re-asserted over the plugin's 'k'/'d'), so the
+ // signature is checked against what the receiver actually gets — the real verification contract.
+ const sentBody = (mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body;
+ const expected = `sha256=${crypto.createHmac('sha256', 'test-secret-123').update(sentBody).digest('hex')}`;
+ expect(capturedHeaders['X-OpenWA-Signature']).toBe(expected);
+
+ mockFetch.mockReset();
+ });
+ });
+
+ // ── dispatch (queue mode) ─────────────────────────────────────────
+
+ describe('dispatch (queue mode)', () => {
+ afterEach(() => (undiciFetch as jest.Mock).mockReset());
+
+ const buildQueueService = async (
+ configGet: (key: string, def?: unknown) => unknown,
+ ): Promise<WebhookDeliveryService> => {
+ const queueModule: TestingModule = await Test.createTestingModule({
+ providers: [
+ WebhookDeliveryService,
+ { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
+ { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },
+ { provide: ConfigService, useValue: { get: jest.fn().mockImplementation(configGet) } },
+ { provide: HookManager, useValue: hookManager },
+ { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
+ ],
+ }).compile();
+ return queueModule.get<WebhookDeliveryService>(WebhookDeliveryService);
+ };
+
+ it('enqueues a small, media-shed job when the event carries over-threshold media', async () => {
+ const queueService = await buildQueueService((key: string, def?: unknown) => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ if (key === 'webhook.mediaInlineMaxBytes') return 1024;
+ return def;
+ });
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ const base64 = Buffer.alloc(2048, 5).toString('base64'); // 2048 decoded bytes > 1024 cap
+ await queueService.dispatch('sess-1', 'message.received', {
+ media: { mimetype: 'image/jpeg', data: base64 },
+ });
+
+ expect(webhookQueue.add).toHaveBeenCalledTimes(1);
+ const addCalls = (webhookQueue.add as jest.Mock).mock.calls as Array<[string, WebhookJobData]>;
+ const jobData = addCalls[0][1];
+ // The blob is shed BEFORE enqueue: a failed job retains only the marker in Redis, and the
+ // bounded removeOnFail window (WEBHOOK_QUEUE_JOB_OPTIONS) keeps count × bytes bounded.
+ expect((jobData.payload.data as { media: Record<string, unknown> }).media).toEqual({
+ mimetype: 'image/jpeg',
+ omitted: true,
+ sizeBytes: 2048,
+ });
+ expect(JSON.stringify(jobData).length).toBeLessThan(2048);
+ });
+
+ it('keys the queue job by the delivery id, so a retried enqueue cannot double-deliver', async () => {
+ const queueService = await buildQueueService((key: string, def?: unknown) => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ return def;
+ });
+ (repository.find as jest.Mock).mockResolvedValue([createMockWebhook({ events: ['message.received'] })]);
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ const [, jobData, opts] = (webhookQueue.add as jest.Mock).mock.calls[0] as [
+ string,
+ WebhookJobData,
+ { jobId?: string },
+ ];
+ // BullMQ's dedupe boundary and the receiver's must key off the SAME identifier, or a job
+ // that BullMQ accepts twice still looks like one delivery to the receiver (and vice versa).
+ expect(opts.jobId).toBe(jobData.headers['X-OpenWA-Delivery-Id']);
+ expect(opts.jobId).toBe(jobData.payload.deliveryId);
+ });
+
+ it('gives sibling webhooks distinct job ids, so one event fanning out is not collapsed into one job', async () => {
+ const queueService = await buildQueueService((key: string, def?: unknown) => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ return def;
+ });
+ (repository.find as jest.Mock).mockResolvedValue([
+ createMockWebhook({ id: 'wh-uuid-1', events: ['message.received'] }),
+ createMockWebhook({ id: 'wh-uuid-2', events: ['message.received'], url: 'https://example.com/other' }),
+ ]);
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ // Guards the invariant that makes jobId = deliveryId safe: deliveryId is minted per webhook
+ // per dispatch. Were it ever hoisted to per-event, BullMQ would silently drop every
+ // subscription after the first — a data-loss bug with no error anywhere.
+ expect(webhookQueue.add).toHaveBeenCalledTimes(2);
+ const jobIds = (webhookQueue.add as jest.Mock).mock.calls.map(
+ (call: [string, WebhookJobData, { jobId?: string }]) => call[2].jobId,
+ );
+ expect(new Set(jobIds).size).toBe(2);
+ });
+
+ it('should add job to queue when queue is enabled', async () => {
+ const queueService = await buildQueueService(<T>(key: string, def?: T): T | boolean | number => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ return def as T;
+ });
+
+ const webhook = createMockWebhook({ events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+
+ const queuePayload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ sessionId: 'sess-1',
+ event: 'message.received',
+ payload: queuePayload,
+ },
+ });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ expect(webhookQueue.add).toHaveBeenCalledWith(
+ expect.stringContaining('webhook-'),
+ expect.objectContaining({
+ webhookId: 'wh-uuid-1',
+ url: 'https://example.com/webhook',
+ event: 'message.received',
+ }),
+ expect.objectContaining({
+ attempts: 3,
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ backoff: expect.objectContaining({ type: 'exponential' }),
+ }),
+ );
+ });
+
+ it('falls back to direct delivery when queue add fails', async () => {
+ const queueService = await buildQueueService(<T>(key: string, def?: T): T | boolean | number => {
+ if (key === 'queue.enabled') return true;
+ if (key === 'webhook.retryDelay') return 5000;
+ if (key === 'webhook.timeout') return 25000;
+ return def as T;
+ });
+ const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });
+ const queuePayload: WebhookPayload = {
+ event: 'message.received',
+ data: {},
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ };
+ const mockFetch = undiciFetch as jest.Mock;
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: { sessionId: 'sess-1', event: 'message.received', payload: queuePayload },
+ });
+ webhookQueue.add.mockRejectedValueOnce(new Error('redis down'));
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+
+ await queueService.dispatch('sess-1', 'message.received', {});
+
+ expect(webhookQueue.add).toHaveBeenCalled();
+ expect(mockFetch).toHaveBeenCalledWith(
+ 'https://example.com/webhook',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'webhook:delivered',
+ expect.objectContaining({ webhookId: webhook.id, fallback: 'queue_failed' }),
+ expect.anything(),
+ );
+ });
+ });
+
+ describe('delivery-failure dead-letter', () => {
+ it('records a durable failure when a direct delivery exhausts its retries', async () => {
+ const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });
+ (repository.find as jest.Mock).mockResolvedValue([webhook]);
+ (hookManager.execute as jest.Mock).mockResolvedValue({
+ continue: true,
+ data: {
+ payload: {
+ event: 'message.received',
+ timestamp: '',
+ sessionId: 'sess-1',
+ idempotencyKey: 'k',
+ deliveryId: 'd',
+ data: {},
+ },
+ },
+ });
+ const mockFetch = undiciFetch as jest.Mock;
+ mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' });
+
+ const failuresBefore = getWebhookDeliveryFailuresTotal();
+ await service.dispatch('sess-1', 'message.received', {});
+
+ expect(failureRepository.insert).toHaveBeenCalledWith(
+ expect.objectContaining({
+ webhookId: webhook.id,
+ attempts: 1,
+ lastStatusCode: 500,
+ lastError: 'HTTP 500: Server Error',
+ }),
+ );
+ // The terminal failure also bumps the Prometheus counter exactly once.
+ expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore + 1);
+ mockFetch.mockReset();
+ });
+ });
+});
diff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.ts
new file mode 100644
index 000000000..5e5337f74
--- /dev/null
+++ b/src/modules/webhook/webhook-delivery.service.ts
@@ -0,0 +1,768 @@
+import { Injectable, Optional, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+import { ConfigService } from '@nestjs/config';
+import { InjectQueue } from '@nestjs/bullmq';
+import { Queue } from 'bullmq';
+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 { createLogger } from '../../common/services/logger.service';
+import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';
+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 { HookManager } from '../../core/hooks';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
+
+export interface WebhookPayload {
+ event: string;
+ timestamp: string;
+ sessionId: string;
+ idempotencyKey: string;
+ deliveryId: string;
+ data: Record<string, unknown>;
+}
+
+export interface WebhookJobData {
+ webhookId: string;
+ url: string;
+ event: string;
+ payload: WebhookPayload;
+ headers: Record<string, string>;
+ attempt: number;
+ 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;
+
+/**
+ * Decoded-byte cap for inline base64 media in webhook payloads. A larger blob is replaced with the
+ * engine's omitted-marker shape ({ mimetype, filename?, omitted: true, sizeBytes }) before the
+ * payload is cloned per webhook or queued, so fan-out and Redis retention never copy it. Default
+ * 1 MiB; override with WEBHOOK_MEDIA_INLINE_MAX_BYTES (0 = never inline media).
+ */
+const DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_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;
+
+/** Per-event-occurrence context threaded through the dispatch pipeline stages (was closure state). */
+interface DispatchEventContext {
+ sessionId: string;
+ event: string;
+ baseData: Record<string, unknown>;
+}
+
+/**
+ * The webhook delivery engine: given an event occurrence, fan it out to the session's matching
+ * webhooks — bounded by the dispatch limiter — through the BullMQ queue when enabled (with a
+ * direct-delivery fallback when enqueue fails) or through direct inline delivery when not.
+ * Records terminally failed deliveries in webhook_delivery_failures. Webhook registration/CRUD
+ * lives on WebhookService, which delegates dispatch here.
+ */
+@Injectable()
+export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
+ private readonly logger = createLogger('WebhookDelivery');
+ private readonly queueEnabled: boolean;
+ private readonly dispatchLimiter: ConcurrencyLimiter;
+ /**
+ * 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')
+ private readonly webhookRepository: Repository<Webhook>,
+ @InjectRepository(WebhookDeliveryFailure, 'data')
+ private readonly failureRepository: Repository<WebhookDeliveryFailure>,
+ private readonly configService: ConfigService,
+ private readonly hookManager: HookManager,
+ @Optional()
+ private readonly lidMappingStore?: LidMappingStoreService,
+ @Optional()
+ @InjectQueue(QUEUE_NAMES.WEBHOOK)
+ private readonly webhookQueue?: Queue<WebhookJobData>,
+ ) {
+ this.queueEnabled = configService.get<boolean>('queue.enabled', false);
+ // Bound fan-out: cap how many matching webhooks are delivered CONCURRENTLY for one event. Without
+ // it, an event matching N webhooks opens N outbound sockets at once. Default 16
+ // (WEBHOOK_DISPATCH_CONCURRENCY).
+ this.dispatchLimiter = new ConcurrencyLimiter(
+ this.configService.get<number>('webhook.dispatchConcurrency', 16),
+ this.configService.get<number>('webhook.dispatchMaxQueued', 1000),
+ );
+ }
+
+ 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.`,
+ );
+ }
+ }
+
+ /**
+ * Bounded drain of the direct-delivery path (queued BullMQ jobs are durable in Redis and need no
+ * drain). In direct mode, closing the limiter rejects every PARKED delivery; the dispatch catch
+ * records each one in webhook_delivery_failures like any other undispatched delivery. Queued mode
+ * skips the close: a parked dispatch's whole job is webhookQueue.add() — durable in Redis the
+ * moment it resolves — so rejecting it would dead-letter work Redis could have kept. A parked
+ * waiter holds an activeCount slot via handoff, so the drain loop below covers it either way.
+ * 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.queueEnabled) {
+ 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 setTimeout(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();
+ }
+
+ async dispatch(sessionId: string, event: string, data: Record<string, unknown>): Promise<void> {
+ const webhooks = await this.loadActiveWebhooks(sessionId, event);
+ const matchingWebhooks = this.filterMatchingWebhooks(webhooks, event, data);
+
+ // Base idempotency key for this event occurrence. occurredAt is captured once here and reused for
+ // every retry of this dispatch, so recurring lifecycle events get a distinct-per-occurrence key
+ // while retries of the same event stay stable. It is salted PER WEBHOOK below.
+ const occurredAt = new Date().toISOString();
+ const baseIdempotencyKey = generateIdempotencyKey(event, { ...data, sessionId }, occurredAt);
+
+ // Fan-out amplification bound: shed an over-cap inline media blob ONCE here, before the
+ // per-webhook structuredClone below, so N matching webhooks (and the queued jobs retained in
+ // Redis) never copy the blob. The per-webhook clone stays — a webhook:before hook may mutate
+ // payload.data in place and must not bleed into siblings — but after shedding it is small.
+ const baseData =
+ matchingWebhooks.length > 0
+ ? this.shedInlineMedia(
+ data,
+ this.configService.get<number>('webhook.mediaInlineMaxBytes', DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES),
+ )
+ : data;
+
+ const ctx: DispatchEventContext = { sessionId, event, baseData };
+ // allSettled preserves the per-webhook isolation: one failing delivery never rejects the others.
+ await Promise.allSettled(matchingWebhooks.map(webhook => this.dispatchWithLimit(webhook, baseIdempotencyKey, ctx)));
+ }
+
+ /**
+ * Callers fire-and-forget this (`void dispatch(...)`), so a failure looking up webhooks must be
+ * logged and swallowed here — otherwise it surfaces as an unhandled promise rejection.
+ */
+ private async loadActiveWebhooks(sessionId: string, event: string): Promise<Webhook[]> {
+ try {
+ return await this.webhookRepository.find({
+ where: { sessionId, active: true },
+ });
+ } catch (error) {
+ this.logger.error(`Webhook dispatch lookup failed for ${event}`, String(error), {
+ sessionId,
+ action: 'webhook_dispatch_lookup_failed',
+ });
+ return [];
+ }
+ }
+
+ private filterMatchingWebhooks(webhooks: Webhook[], event: string, data: Record<string, unknown>): Webhook[] {
+ // Resolve a lid actor to its phone through the persistent table so a phone filter matches a
+ // lid-addressed sender (e.g. an unresolved @lid group participant). Absent store -> no resolution.
+ const resolveLid = (jid: string): string | null => this.lidMappingStore?.resolveLid(jid) ?? null;
+ const subscribed = webhooks.filter(w => w.events.includes(event) || w.events.includes('*'));
+ const matching = subscribed.filter(w => evaluateFilters(w.filters, event, data, resolveLid));
+ // A subscribed webhook that a filter drops leaves no trace otherwise: dispatch() awaits an empty
+ // array and returns, and the delivery-failure table only records deliveries that were ATTEMPTED.
+ // That is fine when the filter is doing its job, and indistinguishable from it when it is not —
+ // a condition on a field the event's payload does not carry resolves to undefined and fails,
+ // which is how a `sender` filter silently swallows every message.ack. Debug rather than warn:
+ // suppression is the normal outcome of a working filter, so this is a trace to switch on while
+ // investigating, not an alarm.
+ if (matching.length < subscribed.length) {
+ this.logger.debug('Webhook filters suppressed a delivery', {
+ action: 'webhook_filter_suppressed',
+ event,
+ subscribed: subscribed.length,
+ suppressed: subscribed.length - matching.length,
+ payloadFields: Object.keys(data).sort().join(','),
+ });
+ }
+ return matching;
+ }
+
+ private async recordUndelivered(
+ webhook: Webhook,
+ deliveryId: string,
+ idempotencyKey: string,
+ error: unknown,
+ action: string,
+ ctx: DispatchEventContext,
+ ): Promise<void> {
+ const { sessionId, event } = ctx;
+ const lastError = redactSsrfError(error, this.logger, 'webhook dispatch');
+ await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
+ webhookId: webhook.id,
+ sessionId,
+ event,
+ url: webhook.url,
+ idempotencyKey,
+ deliveryId,
+ attempts: 0,
+ lastStatusCode: null,
+ lastError,
+ });
+ incrementWebhookDeliveryFailures();
+ try {
+ await this.hookManager.execute(
+ 'webhook:error',
+ { sessionId, event, webhookId: webhook.id, deliveryId, error: lastError },
+ { sessionId, source: 'WebhookService' },
+ );
+ } catch (hookError) {
+ this.logger.error('webhook:error hook failed while reporting an undelivered webhook', String(hookError), {
+ webhookId: webhook.id,
+ deliveryId,
+ action: 'webhook_error_hook_failed',
+ });
+ }
+ this.logger.error(`Webhook ${webhook.id} was not dispatched`, lastError, {
+ webhookId: webhook.id,
+ deliveryId,
+ action,
+ });
+ }
+
+ /**
+ * Build one webhook delivery: payload + webhook:before hooks + identity re-assertion + size gate +
+ * headers. Returns null when the delivery must not proceed — either cancelled by a plugin (a debug
+ * log, not a failure) or after a failure already recorded via recordUndelivered.
+ */
+ private async preflightDelivery(
+ webhook: Webhook,
+ deliveryId: string,
+ idempotencyKey: string,
+ ctx: DispatchEventContext,
+ ): Promise<{ finalPayload: WebhookPayload; body: string; headers: Record<string, string> } | null> {
+ const { sessionId, event, baseData } = ctx;
+ try {
+ const payload: WebhookPayload = {
+ event,
+ timestamp: new Date().toISOString(),
+ sessionId,
+ idempotencyKey,
+ deliveryId,
+ // Give each webhook its own copy of the event data: a webhook:before hook that mutates
+ // payload.data in place would otherwise bleed that change into sibling webhooks.
+ data: structuredClone(baseData),
+ };
+ // 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',
+ { sessionId, event, payload },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ if (!shouldContinue) {
+ this.logger.debug(`Webhook dispatch cancelled by plugin for ${event}`, {
+ webhookId: webhook.id,
+ action: 'webhook_cancelled_by_plugin',
+ });
+ return null;
+ }
+
+ // Null/undefined hook results mean "no override", matching an object without payload.
+ const 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.
+ // The bytes are serialized ONCE and reused for the size gate, the HMAC signature, and the
+ // direct-delivery body (BullMQ re-serializes jobData itself — unavoidable).
+ const maxPayloadBytes = this.configService.get<number>(
+ 'webhook.maxPayloadBytes',
+ DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES,
+ );
+ let body = JSON.stringify(finalPayload);
+ let payloadBytes = Buffer.byteLength(body, 'utf8');
+ if (payloadBytes > maxPayloadBytes) {
+ // Size-gated body shedding: over budget, strip ANY remaining inline media blob (threshold
+ // 0 — the marker form keeps the event deliverable) and re-check, instead of dropping the
+ // event or queueing a giant payload.
+ const shedData = this.shedInlineMedia(finalPayload.data, 0);
+ if (shedData !== finalPayload.data) {
+ finalPayload.data = shedData;
+ body = JSON.stringify(finalPayload);
+ payloadBytes = Buffer.byteLength(body, 'utf8');
+ }
+ }
+ if (payloadBytes > maxPayloadBytes) {
+ await this.recordUndelivered(
+ webhook,
+ deliveryId,
+ idempotencyKey,
+ new Error(
+ `Webhook payload is ${payloadBytes} bytes after webhook:before hooks, exceeding the ${maxPayloadBytes}-byte cap`,
+ ),
+ 'webhook_payload_oversize',
+ ctx,
+ );
+ return null;
+ }
+
+ const headers = {
+ ...this.sanitizeCustomHeaders(webhook.headers),
+ 'Content-Type': 'application/json',
+ 'User-Agent': 'OpenWA-Webhook/1.0.0',
+ 'X-OpenWA-Event': event,
+ 'X-OpenWA-Idempotency-Key': idempotencyKey,
+ 'X-OpenWA-Delivery-Id': deliveryId,
+ 'X-OpenWA-Retry-Count': '0',
+ };
+ return { finalPayload, body, headers };
+ } catch (error) {
+ await this.recordUndelivered(
+ webhook,
+ deliveryId,
+ idempotencyKey,
+ error,
+ 'webhook_dispatch_preflight_failed',
+ ctx,
+ );
+ return null;
+ }
+ }
+
+ private async deliverOne(
+ webhook: Webhook,
+ deliveryId: string,
+ idempotencyKey: string,
+ ctx: DispatchEventContext,
+ ): Promise<void> {
+ const preflight = await this.preflightDelivery(webhook, deliveryId, idempotencyKey, ctx);
+ if (!preflight) {
+ return;
+ }
+ const { finalPayload, body, headers } = preflight;
+ // Use queue if available, otherwise fallback to direct delivery
+ if (this.queueEnabled && this.webhookQueue) {
+ await this.enqueueWithFallback(webhook, finalPayload, body, headers, deliveryId, idempotencyKey, ctx);
+ } else {
+ await this.deliverDirect(webhook, finalPayload, body, headers, deliveryId, ctx);
+ }
+ }
+
+ private async enqueueWithFallback(
+ webhook: Webhook,
+ finalPayload: WebhookPayload,
+ body: string,
+ headers: Record<string, string>,
+ deliveryId: string,
+ idempotencyKey: string,
+ ctx: DispatchEventContext,
+ ): Promise<void> {
+ const { sessionId, event } = ctx;
+ try {
+ // Sign the exact pre-serialized body from preflight. The processor re-serializes the same
+ // payload object at delivery time (JSON key order survives the Redis round-trip), so the
+ // signature stays valid over the bytes the receiver sees.
+ const signature = webhook.secret ? this.generateSignature(body, webhook.secret) : '';
+
+ if (webhook.secret) {
+ headers['X-OpenWA-Signature'] = signature;
+ }
+
+ const jobData: WebhookJobData = {
+ webhookId: webhook.id,
+ url: webhook.url,
+ event,
+ payload: finalPayload,
+ headers,
+ attempt: 1,
+ maxRetries: webhook.retryCount,
+ };
+
+ await this.webhookQueue!.add(`webhook-${webhook.id}`, jobData, {
+ // jobId = deliveryId gives BullMQ exactly-once enqueue semantics (same precedent as the
+ // ingress producer), so a crash between add() and the bookkeeping below cannot re-enqueue
+ // the same delivery. Safe for fan-out: deliveryId is minted per webhook per dispatch in
+ // dispatchWithLimit, so sibling subscriptions to one event never share a job id.
+ jobId: deliveryId,
+ attempts: webhook.retryCount,
+ backoff: {
+ type: 'exponential',
+ delay: this.configService.get<number>('webhook.retryDelay', 5000),
+ },
+ });
+
+ // Execute hook after successful queue (NOT delivery - that happens in processor)
+ await this.hookManager.execute(
+ 'webhook:queued',
+ { sessionId, event, webhookId: webhook.id, deliveryId },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ this.logger.debug(`Webhook job queued for ${webhook.id}`, {
+ webhookId: webhook.id,
+ event,
+ idempotencyKey,
+ deliveryId,
+ action: 'webhook_queued',
+ });
+ } catch (error) {
+ // Execute hook on queue error (not delivery error - that happens in processor)
+ await this.hookManager.execute(
+ 'webhook:error',
+ { sessionId, event, webhookId: webhook.id, error: `Queue failed: ${String(error)}` },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ this.logger.error(`Failed to queue webhook ${webhook.id}`, String(error), {
+ webhookId: webhook.id,
+ action: 'webhook_queue_failed',
+ });
+
+ // Fallback: deliver directly when the queue add failed (e.g. Redis unreachable with the
+ // producer's enableOfflineQueue:false). This is at-least-once — if add() actually reached
+ // Redis before rejecting, the queued job AND this fallback may both POST. Both paths carry the
+ // same X-OpenWA-Idempotency-Key / X-OpenWA-Delivery-Id, so a conformant receiver dedupes.
+ try {
+ await this.deliverWebhook(webhook, finalPayload, headers, body);
+
+ await this.hookManager.execute(
+ 'webhook:delivered',
+ { sessionId, event, webhookId: webhook.id, deliveryId, fallback: 'queue_failed' },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ await this.hookManager.execute(
+ 'webhook:after',
+ { sessionId, event, webhookId: webhook.id, success: true, fallback: 'queue_failed' },
+ { sessionId, source: 'WebhookService' },
+ );
+ } catch (fallbackError) {
+ await this.hookManager.execute(
+ 'webhook:error',
+ {
+ sessionId,
+ event,
+ webhookId: webhook.id,
+ error: `Queue fallback delivery failed: ${redactSsrfError(fallbackError, this.logger, 'webhook fallback delivery')}`,
+ },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ this.logger.error(`Queue fallback delivery failed for webhook ${webhook.id}`, String(fallbackError), {
+ webhookId: webhook.id,
+ action: 'webhook_queue_fallback_failed',
+ });
+ }
+ }
+ }
+
+ /** Direct delivery when the queue is disabled. */
+ private async deliverDirect(
+ webhook: Webhook,
+ finalPayload: WebhookPayload,
+ body: string,
+ headers: Record<string, string>,
+ deliveryId: string,
+ ctx: DispatchEventContext,
+ ): Promise<void> {
+ const { sessionId, event } = ctx;
+ try {
+ await this.deliverWebhook(webhook, finalPayload, headers, body);
+
+ // Execute hook after successful delivery
+ await this.hookManager.execute(
+ 'webhook:delivered',
+ { sessionId, event, webhookId: webhook.id, deliveryId },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ // Legacy hook for backward compatibility
+ await this.hookManager.execute(
+ 'webhook:after',
+ { sessionId, event, webhookId: webhook.id, success: true },
+ { sessionId, source: 'WebhookService' },
+ );
+ } catch (error) {
+ // Execute hook on error
+ await this.hookManager.execute(
+ 'webhook:error',
+ { sessionId, event, webhookId: webhook.id, error: redactSsrfError(error, this.logger, 'webhook delivery') },
+ { sessionId, source: 'WebhookService' },
+ );
+
+ this.logger.error(`Failed to deliver webhook ${webhook.id}`, String(error), {
+ webhookId: webhook.id,
+ action: 'webhook_delivery_failed',
+ });
+ }
+ }
+
+ /**
+ * Bound fan-out: deliver to all matching webhooks concurrently, but cap in-flight deliveries at
+ * WEBHOOK_DISPATCH_CONCURRENCY so an event matching many webhooks (or slow receivers) can't open an
+ * unbounded number of outbound sockets at once.
+ */
+ private async dispatchWithLimit(
+ webhook: Webhook,
+ baseIdempotencyKey: string,
+ ctx: DispatchEventContext,
+ ): Promise<void> {
+ const { sessionId, event } = ctx;
+ const deliveryId = generateDeliveryId();
+ // Salt per webhook so sibling subscriptions cannot collide at the receiver's dedup boundary.
+ const idempotencyKey = `${baseIdempotencyKey}_${webhook.id}`;
+ await this.dispatchLimiter
+ .run(async () => {
+ this.inFlightDeliveries.set(deliveryId, {
+ webhookId: webhook.id,
+ sessionId,
+ event,
+ idempotencyKey,
+ url: webhook.url,
+ });
+ try {
+ await this.deliverOne(webhook, deliveryId, idempotencyKey, ctx);
+ } finally {
+ this.inFlightDeliveries.delete(deliveryId);
+ }
+ })
+ .catch(async error => {
+ if (error instanceof Error && error.message === 'ConcurrencyLimiter queue full') {
+ await this.recordUndelivered(
+ webhook,
+ deliveryId,
+ idempotencyKey,
+ error,
+ 'webhook_dispatch_capacity_exceeded',
+ ctx,
+ );
+ 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 = this.recordUndelivered(
+ webhook,
+ deliveryId,
+ idempotencyKey,
+ error,
+ 'webhook_dispatch_shutdown',
+ ctx,
+ );
+ this.pendingBookkeeping.add(record);
+ try {
+ await record;
+ } finally {
+ this.pendingBookkeeping.delete(record);
+ }
+ return;
+ }
+ throw error;
+ });
+ }
+
+ /**
+ * @deprecated Use job queue dispatch instead. This is kept for fallback.
+ * `body` is the pre-serialized payload from preflight — the exact bytes the size gate checked and
+ * (when a secret is set) the signature covers — so it is never re-serialized here.
+ */
+ private async deliverWebhook(
+ webhook: Webhook,
+ payload: WebhookPayload,
+ headers: Record<string, string>,
+ body: string,
+ attempt = 1,
+ ): Promise<void> {
+ // Update retry count header
+ headers['X-OpenWA-Retry-Count'] = String(attempt - 1);
+
+ // Add signature if secret is configured and not already present
+ if (webhook.secret && !headers['X-OpenWA-Signature']) {
+ headers['X-OpenWA-Signature'] = this.generateSignature(body, webhook.secret);
+ }
+
+ 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}`);
+ }
+
+ // 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,
+ deliveryId: payload.deliveryId,
+ action: 'webhook_delivered',
+ });
+ } catch (error) {
+ this.logger.error(`Webhook delivery failed for ${webhook.id}`, String(error), {
+ webhookId: webhook.id,
+ attempt,
+ deliveryId: payload.deliveryId,
+ action: 'webhook_delivery_failed',
+ });
+
+ if (attempt < webhook.retryCount) {
+ const delay = this.configService.get<number>('webhook.retryDelay', 5000);
+ await setTimeout(delay * attempt);
+ return this.deliverWebhook(webhook, payload, headers, body, attempt + 1);
+ }
+ // 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, {
+ webhookId: webhook.id,
+ sessionId: payload.sessionId,
+ event: payload.event,
+ url: webhook.url,
+ idempotencyKey: payload.idempotencyKey,
+ deliveryId: payload.deliveryId,
+ attempts: attempt,
+ lastStatusCode: statusCodeFromError(errMessage),
+ lastError: errMessage,
+ });
+ incrementWebhookDeliveryFailures();
+ throw error;
+ }
+ }
+
+ /**
+ * Replace an over-size inline base64 blob on `data.media` with the engine's omitted-marker shape
+ * ({ mimetype, filename?, omitted: true, sizeBytes }) — the same contract the inbound media cap
+ * and the status store already emit — so the multi-MB blob is never cloned per webhook, queued
+ * into Redis, or POSTed. Returns the ORIGINAL object when nothing was shed (zero-copy fast path);
+ * otherwise a shallow copy with only `media` replaced, so the caller's event data is never
+ * mutated. `maxBytes` compares against the DECODED size; 0 sheds any inline blob.
+ */
+ private shedInlineMedia(data: Record<string, unknown>, maxBytes: number): Record<string, unknown> {
+ if (!data || typeof data !== 'object') return data;
+ const media = data.media as
+ { mimetype?: unknown; filename?: unknown; data?: unknown; omitted?: unknown } | undefined;
+ if (!media || typeof media !== 'object' || typeof media.data !== 'string' || media.data.length === 0) {
+ return data;
+ }
+ const sizeBytes = Buffer.byteLength(media.data, 'base64');
+ if (sizeBytes <= maxBytes) return data;
+ return {
+ ...data,
+ media: {
+ mimetype: media.mimetype,
+ ...(typeof media.filename === 'string' ? { filename: media.filename } : {}),
+ omitted: true,
+ sizeBytes,
+ },
+ };
+ }
+
+ /**
+ * Drop operator-supplied custom headers that target reserved names (Content-Type or any
+ * X-OpenWA-* header) so a webhook config cannot forge the signature/event/idempotency
+ * headers. Spread the result BEFORE the system headers so system always wins. Shared with
+ * WebhookService.test(), which must probe with headers identical to a real delivery's.
+ */
+ sanitizeCustomHeaders(custom: Record<string, string> | null | undefined): Record<string, string> {
+ const safe: Record<string, string> = {};
+ for (const [key, value] of Object.entries(custom ?? {})) {
+ if (!/^(content-type|x-openwa-)/i.test(key)) {
+ safe[key] = value;
+ }
+ }
+ return safe;
+ }
+
+ /** HMAC-SHA256 over the exact pre-serialized body, prefixed for receiver-side verification. */
+ generateSignature(payload: string, secret: string): string {
+ const hmac = crypto.createHmac('sha256', secret);
+ hmac.update(payload);
+ return `sha256=${hmac.digest('hex')}`;
+ }
+}
diff --git a/src/modules/webhook/webhook-session-scope.spec.ts b/src/modules/webhook/webhook-session-scope.spec.ts
index 495129be7..0ef23482b 100644
--- a/src/modules/webhook/webhook-session-scope.spec.ts
+++ b/src/modules/webhook/webhook-session-scope.spec.ts
@@ -25,9 +25,10 @@ describe('WebhookService session-scoped access', () => {
await ds.initialize();
const repo = ds.getRepository(Webhook);
const cfg = { get: () => false }; // queue.enabled = false
- // 2nd arg is the delivery-failure repo and 3rd the session repo — the scoped read/update/delete
- // paths under test never touch them (only create() checks session existence).
- service = new WebhookService(repo, {} as never, {} as never, cfg as never, {} as never, undefined);
+ // 2nd arg is the delivery-failure repo, 3rd the session repo, and 5th the delivery service —
+ // the scoped read/update/delete paths under test never touch them (only create() checks
+ // session existence; test() would probe via the delivery service's header/signature helpers).
+ service = new WebhookService(repo, {} as never, {} as never, cfg as never, {} as never);
const sessions = ds.getRepository(Session);
for (const id of ['sessA', 'sessB']) {
diff --git a/src/modules/webhook/webhook.module.ts b/src/modules/webhook/webhook.module.ts
index 5d916621e..a0c0e3899 100644
--- a/src/modules/webhook/webhook.module.ts
+++ b/src/modules/webhook/webhook.module.ts
@@ -4,6 +4,7 @@ import { Webhook } from './entities/webhook.entity';
import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';
import { Session } from '../session/entities/session.entity';
import { WebhookService } from './webhook.service';
+import { WebhookDeliveryService } from './webhook-delivery.service';
import { WebhookController } from './webhook.controller';
import { WebhooksListController } from './webhooks-list.controller';
import { EngineModule } from '../../engine/engine.module';
@@ -25,7 +26,7 @@ if (process.env.QUEUE_ENABLED === 'true') {
...queueModules,
],
controllers: [WebhookController, WebhooksListController],
- providers: [WebhookService],
+ providers: [WebhookService, WebhookDeliveryService],
exports: [WebhookService],
})
export class WebhookModule {}
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index c5b6cc24e..5efafe61d 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -16,19 +16,16 @@ import { getQueueToken } from '@nestjs/bullmq';
import { In, Repository } from 'typeorm';
import { NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
-import * as crypto from 'crypto';
import { fetch as undiciFetch } from 'undici';
-import { WebhookService, WebhookPayload, WebhookJobData } from './webhook.service';
+import { WebhookService } from './webhook.service';
+import { WebhookDeliveryService } from './webhook-delivery.service';
import { Webhook } from './entities/webhook.entity';
import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';
-import { WebhookFilters } from './filters/filter-types';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { userPart } from '../../engine/identity/wa-id';
import { HookManager } from '../../core/hooks';
import { QUEUE_NAMES } from '../queue/queue-names';
import { Session } from '../session/entities/session.entity';
-import { getWebhookDeliveryFailuresTotal } from '../../common/metrics/webhook-delivery-metrics';
-import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
function createMockWebhook(overrides: Partial<Webhook> = {}): Webhook {
return {
@@ -51,6 +48,7 @@ function createMockWebhook(overrides: Partial<Webhook> = {}): Webhook {
describe('WebhookService', () => {
let service: WebhookService;
+ let testingModule: TestingModule;
let repository: jest.Mocked<Partial<Repository<Webhook>>>;
let failureRepository: jest.Mocked<Partial<Repository<WebhookDeliveryFailure>>>;
let sessionRepository: jest.Mocked<Partial<Repository<Session>>>;
@@ -110,9 +108,10 @@ describe('WebhookService', () => {
resolveLid: jest.fn((jid: string) => (lidStore.getCached(userPart(jid)) as string | null | undefined) ?? null),
};
- const module: TestingModule = await Test.createTestingModule({
+ testingModule = await Test.createTestingModule({
providers: [
WebhookService,
+ WebhookDeliveryService,
{ provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
{ provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },
{ provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },
@@ -123,7 +122,7 @@ describe('WebhookService', () => {
],
}).compile();
- service = module.get<WebhookService>(WebhookService);
+ service = testingModule.get<WebhookService>(WebhookService);
});
// ── create ────────────────────────────────────────────────────────
@@ -441,506 +440,27 @@ 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);
- }
- };
+ // ── dispatch facade ───────────────────────────────────────────────
- 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');
- });
+ describe('dispatch (facade)', () => {
+ it("delegates dispatch to the delivery engine with the caller's arguments", async () => {
+ const delivery = testingModule.get<WebhookDeliveryService>(WebhookDeliveryService);
+ const dispatchSpy = jest.spyOn(delivery, 'dispatch').mockResolvedValue(undefined);
- 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();
- });
+ await service.dispatch('sess-1', 'message.received', { x: 1 });
- 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();
+ expect(dispatchSpy).toHaveBeenCalledTimes(1);
+ expect(dispatchSpy).toHaveBeenCalledWith('sess-1', 'message.received', { x: 1 });
+ expect(repository.find).not.toHaveBeenCalled(); // the engine, not the facade, loads webhooks
});
});
- describe('dispatch (direct mode)', () => {
- const mockFetch = undiciFetch as jest.Mock;
-
- beforeEach(() => {
- mockFetch.mockResolvedValue({ ok: true, status: 200 });
- });
-
- afterEach(() => {
- mockFetch.mockReset();
- });
-
- it('resolves (never rejects) when the webhook lookup fails — callers fire-and-forget it', async () => {
- (repository.find as jest.Mock).mockRejectedValue(new Error('db down'));
- await expect(service.dispatch('sess-1', 'message.received', { x: 1 })).resolves.toBeUndefined();
- expect(mockFetch).not.toHaveBeenCalled();
- });
-
- it('should dispatch to webhooks matching the event', async () => {
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
- // Mock hook to return the payload properly
- const mockPayload: WebhookPayload = {
- event: 'message.received',
- timestamp: new Date().toISOString(),
- sessionId: 'sess-1',
- idempotencyKey: 'test-key',
- deliveryId: 'test-delivery',
- data: { from: '[email protected]' },
- };
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: {
- sessionId: 'sess-1',
- event: 'message.received',
- payload: mockPayload,
- },
- });
-
- const timeoutSpy = jest.spyOn(AbortSignal, 'timeout');
- await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+ // ── test probe ────────────────────────────────────────────────────
- expect(mockFetch).toHaveBeenCalledWith(
- 'https://example.com/webhook',
- expect.objectContaining({ method: 'POST' }),
- );
- // Direct delivery path honors the configured WEBHOOK_TIMEOUT, not a literal 10s.
- expect(timeoutSpy).toHaveBeenCalledWith(25000);
- timeoutSpy.mockRestore();
- });
-
- it('dispatches to sibling webhooks concurrently — a slow receiver does not block the others', async () => {
- const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
- const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([wA, wB]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
-
- let resolveSlow: (v: unknown) => void = () => undefined;
- const slow = new Promise(r => (resolveSlow = r));
- const calledUrls: string[] = [];
- mockFetch.mockImplementation((url: string) => {
- calledUrls.push(url);
- return url.includes('a.example') ? slow : Promise.resolve({ ok: true, status: 200 });
- });
-
- const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
- // Flush until both fetches fire (or give up): with the old sequential loop, only A ever fires while
- // it hangs, so this exhausts and the assertion below fails — exactly the regression we guard.
- for (let i = 0; i < 20 && calledUrls.length < 2; i++) {
- await new Promise(r => setImmediate(r));
- }
-
- // B is delivered even though A is still hanging — sequential code would not have reached B yet.
- expect(calledUrls).toEqual(expect.arrayContaining(['https://a.example/hook', 'https://b.example/hook']));
-
- resolveSlow({ ok: true, status: 200 });
- await dispatchP;
- });
-
- it('bounds concurrent delivery to WEBHOOK_DISPATCH_CONCURRENCY (cap=2, 5 webhooks → peak ≤ 2)', async () => {
- const hooks = Array.from({ length: 5 }, (_, i) =>
- createMockWebhook({ id: `wh-${i}`, url: `https://h${i}.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).mockResolvedValue({ continue: true, data: {} });
-
- let inFlight = 0;
- let peak = 0;
- let resolved = 0;
- const releasers: Array<() => void> = [];
- mockFetch.mockImplementation(
- () =>
- new Promise(resolve => {
- inFlight += 1;
- peak = Math.max(peak, inFlight);
- releasers.push(() => {
- inFlight -= 1;
- resolved += 1;
- resolve({ ok: true, status: 200 });
- });
- }),
- );
-
- const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
- // Let the limiter admit up to the cap (2) and each reach fetch. The other 3 stay parked.
- for (let i = 0; i < 20 && releasers.length < 2; i++) {
- await new Promise(r => setImmediate(r));
- }
- expect(inFlight).toBeLessThanOrEqual(2);
- // Release in a macrotask loop: freeing a slot lets the limiter admit the next webhook, whose fetch
- // pushes a fresh releaser on the NEXT tick — a single synchronous drain would miss it and hang.
- for (let i = 0; i < 50 && resolved < 5; i++) {
- while (releasers.length) (releasers.shift() as () => void)();
- await new Promise(r => setImmediate(r));
- }
- await dispatchP;
- // Peak across the whole run never exceeded the cap. (An unbounded fan-out would reach 5.)
- expect(peak).toBeLessThanOrEqual(2);
- expect(mockFetch).toHaveBeenCalledTimes(5);
- });
-
- it('records a durable failure when the bounded dispatch queue is full', async () => {
- const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
- const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([wA, wB]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockImplementation((_event: string, data: unknown) =>
- Promise.resolve({ continue: true, data }),
- );
- (service as unknown as { dispatchLimiter: ConcurrencyLimiter }).dispatchLimiter = new ConcurrencyLimiter(1, 0);
-
- let release: (value: unknown) => void = () => undefined;
- mockFetch.mockImplementation(() => new Promise(resolve => (release = resolve)));
-
- const pending = 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));
- release({ ok: true, status: 200 });
- await pending;
-
- expect(failureRepository.insert).toHaveBeenCalledWith(
- expect.objectContaining({
- webhookId: 'wh-b',
- attempts: 0,
- lastError: 'ConcurrencyLimiter queue full',
- }),
- );
- expect(mockFetch).toHaveBeenCalledTimes(1);
- });
-
- it('salts each sibling webhook with a distinct idempotency key so one receiver cannot dedupe out another', async () => {
- const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
- const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([wA, wB]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
- mockFetch.mockResolvedValue({ ok: true, status: 200 });
-
- await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
-
- const keyByUrl = new Map<string, string>();
- for (const call of mockFetch.mock.calls as [string, { headers: Record<string, string> }][]) {
- keyByUrl.set(call[0], call[1].headers['X-OpenWA-Idempotency-Key']);
- }
- const keyA = keyByUrl.get('https://a.example/hook');
- const keyB = keyByUrl.get('https://b.example/hook');
- // Same event + payload, but two distinct endpoints must not collide on the dedupe header.
- expect(keyA).toBeTruthy();
- expect(keyB).toBeTruthy();
- expect(keyA).not.toBe(keyB);
- });
-
- it('falls back to the original payload when a before-hook omits payload (no undefined body)', async () => {
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
- // A misbehaving plugin returns continue:true but no `payload` key on the result.
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: { sessionId: 'sess-1', event: 'message.received' },
- });
-
- await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
-
- expect(mockFetch).toHaveBeenCalled();
- const callArgs = mockFetch.mock.calls[0] as [unknown, { body: string }];
- const body = JSON.parse(callArgs[1].body) as WebhookPayload;
- expect(body).not.toBeUndefined();
- expect(body.event).toBe('message.received');
- expect(body.data).toEqual({ from: '[email protected]' });
- });
-
- it('falls back to the original payload when a before-hook returns null data', async () => {
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: null });
-
- await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
-
- const callArgs = mockFetch.mock.calls[0] as [unknown, { body: string }];
- const body = JSON.parse(callArgs[1].body) as WebhookPayload;
- expect(body.event).toBe('message.received');
- expect(body.data).toEqual({ from: '[email protected]' });
- });
-
- it('keeps the server-canonical idempotency/delivery ids on the signed body, overriding a tampering plugin', async () => {
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
- // A webhook:before plugin returns a payload with forged identifiers (other hook events pass through).
- (hookManager.execute as jest.Mock).mockImplementation((event: string, ctx: { payload?: WebhookPayload }) =>
- event === 'webhook:before' && ctx.payload
- ? Promise.resolve({
- continue: true,
- data: { payload: { ...ctx.payload, idempotencyKey: 'PLUGIN-FORGED', deliveryId: 'PLUGIN-FORGED' } },
- })
- : 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;
- // Receivers dedupe on the header, so the signed body field must equal the header — and both must
- // be the server's value, not the plugin's forgery.
- expect(body.idempotencyKey).toBe(headers['X-OpenWA-Idempotency-Key']);
- expect(body.deliveryId).toBe(headers['X-OpenWA-Delivery-Id']);
- expect(body.idempotencyKey).not.toBe('PLUGIN-FORGED');
- 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('replaces over-threshold inline media with the omitted marker before fan-out (input not mutated)', async () => {
- (configService.get as jest.Mock).mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
- if (key === 'queue.enabled') return false;
- if (key === 'webhook.mediaInlineMaxBytes') return 1024;
- return def as T;
- });
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
-
- const base64 = Buffer.alloc(2048, 7).toString('base64'); // 2048 decoded bytes > 1024 cap
- const data: Record<string, unknown> = {
- media: { mimetype: 'image/jpeg', data: base64 },
- };
- await service.dispatch('sess-1', 'message.received', data);
-
- expect(mockFetch).toHaveBeenCalledTimes(1);
- const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
- data: { media: Record<string, unknown> };
- };
- // The documented marker shape — the blob itself never reaches the wire.
- expect(body.data.media).toEqual({ mimetype: 'image/jpeg', omitted: true, sizeBytes: 2048 });
- // The caller's event data keeps its media — shedding works on a copy.
- expect((data.media as { data?: string }).data).toBe(base64);
- expect(failureRepository.insert).not.toHaveBeenCalled();
- });
-
- it('keeps under-threshold media inline, unchanged', async () => {
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
-
- const base64 = Buffer.alloc(512, 3).toString('base64'); // default inline cap is 1 MiB
- await service.dispatch('sess-1', 'message.received', {
- media: { mimetype: 'image/jpeg', data: base64 },
- });
-
- const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
- data: { media: { data?: string; omitted?: boolean } };
- };
- expect(body.data.media.data).toBe(base64);
- expect(body.data.media.omitted).toBeUndefined();
- });
-
- it('sheds inline media to fit the payload budget instead of recording the event undelivered', 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;
- if (key === 'webhook.mediaInlineMaxBytes') return 50 * 1024 * 1024; // pre-fan-out shed stays out of the way
- return def as T;
- });
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
-
- // 2048 decoded bytes → ~2.7 KB base64 → serialized payload over the 1024-byte budget.
- const base64 = Buffer.alloc(2048, 9).toString('base64');
- await service.dispatch('sess-1', 'message.received', {
- media: { mimetype: 'image/jpeg', filename: 'photo.jpg', data: base64 },
- });
-
- // Delivered with the marker (filename preserved) — NOT dropped as undelivered.
- expect(mockFetch).toHaveBeenCalledTimes(1);
- const body = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
- data: { media: Record<string, unknown> };
- };
- expect(body.data.media).toEqual({
- mimetype: 'image/jpeg',
- filename: 'photo.jpg',
- omitted: true,
- sizeBytes: 2048,
- });
- expect(failureRepository.insert).not.toHaveBeenCalled();
- });
-
- it('still records undelivered when an over-budget payload has no inline media to shed', 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).mockResolvedValue({ continue: true, data: {} });
-
- await service.dispatch('sess-1', 'message.received', { from: '[email protected]', body: 'y'.repeat(4096) });
-
- expect(mockFetch).not.toHaveBeenCalled();
- expect(failureRepository.insert).toHaveBeenCalledTimes(1);
- });
-
- 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'] });
- (repository.find as jest.Mock).mockResolvedValue([a, b]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
- // The hook mutates payload.data in place every time it runs (returns no payload key → finalPayload
- // is the mutated input). With a shared data object the second webhook would see the first's tag.
- (hookManager.execute as jest.Mock).mockImplementation((event: string, ctx: { payload?: WebhookPayload }) => {
- if (event === 'webhook:before' && ctx.payload) {
- const d = ctx.payload.data as { tag?: number };
- d.tag = (d.tag ?? 0) + 1;
- return Promise.resolve({ continue: true, data: { payload: ctx.payload } });
- }
- return Promise.resolve({ continue: true, data: {} });
- });
+ describe('test', () => {
+ const mockFetch = undiciFetch as jest.Mock;
- await service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
-
- const bodyA = JSON.parse((mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body) as {
- data: { tag: number };
- };
- const bodyB = JSON.parse((mockFetch.mock.calls[1] as [unknown, { body: string }])[1].body) as {
- data: { tag: number };
- };
- // Each webhook starts from its own clone of the original data, so both see exactly one increment.
- expect(bodyA.data.tag).toBe(1);
- expect(bodyB.data.tag).toBe(1);
- });
+ afterEach(() => mockFetch.mockReset());
it('test() probes the receiver using the configured WEBHOOK_TIMEOUT', async () => {
const webhook = createMockWebhook({ events: ['message.received'] });
@@ -975,773 +495,10 @@ describe('WebhookService', () => {
else process.env.WEBHOOK_SSRF_PROTECT = origProtect;
}
});
-
- it('should NOT dispatch to webhooks that do not match the event', async () => {
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
-
- await service.dispatch('sess-1', 'session.ready', { phone: '628123456789' });
-
- expect(mockFetch).not.toHaveBeenCalled();
- });
-
- it('should dispatch to webhooks with wildcard (*) event filter', async () => {
- const webhook = createMockWebhook({ events: ['*'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
- const wildcardPayload: WebhookPayload = {
- event: 'anything.goes',
- timestamp: '',
- sessionId: 'sess-1',
- idempotencyKey: '',
- deliveryId: '',
- data: {},
- };
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: {
- sessionId: 'sess-1',
- event: 'anything.goes',
- payload: wildcardPayload,
- },
- });
-
- await service.dispatch('sess-1', 'anything.goes', {});
-
- expect(mockFetch).toHaveBeenCalled();
- });
-
- it('should skip dispatch when plugin cancels via hook', async () => {
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
-
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: false, data: {} });
-
- await service.dispatch('sess-1', 'message.received', {});
-
- expect(mockFetch).not.toHaveBeenCalled();
- });
- });
-
- 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). 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]);
-
- // Must NOT reject (the loop/dispatch promise stays settled); the throw is caught + logged.
- await expect(service.dispatch('sess-1', 'message.received', { ok: true })).resolves.toBeUndefined();
-
- expect(webhookQueue.add).not.toHaveBeenCalled(); // never enqueued the un-signable job
- expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
- });
- });
-
- // ── 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('queued mode: parked enqueues drain to the queue on shutdown instead of dead-lettering', async () => {
- (service as unknown as { queueEnabled: boolean }).queueEnabled = true;
- 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);
- (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 true;
- if (key === 'webhook.shutdownDrainMs') return 1000;
- return def as T;
- });
- // One active slot, generous parked bound: B and C park behind A, whose enqueue hangs.
- (service as unknown as { dispatchLimiter: ConcurrencyLimiter }).dispatchLimiter = new ConcurrencyLimiter(1, 1000);
-
- let releaseActive: (value: unknown) => void = () => undefined;
- let firstAdd = true;
- (webhookQueue.add as jest.Mock).mockImplementation(
- () =>
- new Promise(resolve => {
- if (firstAdd) {
- firstAdd = false;
- releaseActive = resolve;
- } else {
- resolve(undefined);
- }
- }),
- );
-
- const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
- for (let i = 0; i < 20 && webhookQueue.add.mock.calls.length === 0; i++) await new Promise(r => setImmediate(r));
-
- // Shutdown starts while A holds the slot and B/C are parked. Queued mode must not close the
- // limiter: a parked task is just webhookQueue.add() — durable in Redis once it runs — and it
- // holds an activeCount slot via handoff, so the drain loop waits for the whole chain.
- const destroyP = service.onModuleDestroy();
- releaseActive(undefined);
- await destroyP;
- await dispatchP;
-
- // All three reached the queue; none was dead-lettered as webhook_dispatch_shutdown.
- expect(webhookQueue.add).toHaveBeenCalledTimes(3);
- expect(failureRepository.insert).not.toHaveBeenCalled();
- });
-
- 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).
-
- describe('dispatch (smart filters)', () => {
- const mockFetch = undiciFetch as jest.Mock;
-
- beforeEach(() => {
- mockFetch.mockResolvedValue({ ok: true, status: 200 });
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- });
-
- afterEach(() => mockFetch.mockReset());
-
- const conds = (...conditions: WebhookFilters['conditions']): WebhookFilters => ({ conditions });
-
- // events:['*'] isolates the filter logic from event-name matching. Returns the number
- // of outbound HTTP deliveries the dispatch performed (1 = fired, 0 = filtered out).
- async function deliveries(
- filters: WebhookFilters | null,
- event: string,
- data: Record<string, unknown>,
- ): Promise<number> {
- mockFetch.mockClear();
- const webhook = createMockWebhook({ events: ['*'], filters });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- await service.dispatch('sess-1', event, data);
- return mockFetch.mock.calls.length;
- }
-
- // A condition names a field the event's payload does not carry — `sender` resolves from
- // author/from, and message.ack dispatches { id, messageId, status, ack }. The condition cannot
- // match, so the delivery is dropped. That is the filter working as specified; what was missing
- // was any way to find out it had happened.
- it('logs when a filter suppresses a subscribed webhook', async () => {
- const logger = (service as unknown as { logger: { debug: jest.Mock } }).logger;
- const spy = jest.spyOn(logger, 'debug');
-
- expect(
- await deliveries(conds({ field: 'sender', operator: 'is', value: ['[email protected]'] }), 'message.ack', {
- messageId: 'm1',
- status: 'read',
- }),
- ).toBe(0);
-
- const suppressed = spy.mock.calls.filter(c => String(c[0]).includes('suppressed a delivery'));
- expect(suppressed).toHaveLength(1);
- expect(suppressed[0][1]).toMatchObject({ event: 'message.ack', subscribed: 1, suppressed: 1 });
- // The payload's own fields are recorded, because the usual cause is a condition on a field
- // this event does not have — that list is the answer to "why did nothing fire?".
- expect((suppressed[0][1] as { payloadFields: string }).payloadFields).toBe('messageId,status');
- spy.mockRestore();
- });
-
- it('stays quiet when nothing is suppressed', async () => {
- const logger = (service as unknown as { logger: { debug: jest.Mock } }).logger;
- const spy = jest.spyOn(logger, 'debug');
-
- expect(
- await deliveries(conds({ field: 'sender', operator: 'is', value: ['[email protected]'] }), 'message.received', {
- }),
- ).toBe(1);
-
- expect(spy.mock.calls.filter(c => String(c[0]).includes('suppressed a delivery'))).toHaveLength(0);
- spy.mockRestore();
- });
-
- it('fires with no filters (additive: zero-config behaviour is unchanged)', async () => {
- expect(await deliveries(null, 'message.received', { from: '[email protected]' })).toBe(1);
- expect(await deliveries(conds(), 'message.received', { from: '[email protected]' })).toBe(1);
- });
-
- it('sender "is": fires on a match, filters out a mismatch', async () => {
- const f = conds({ field: 'sender', operator: 'is', value: ['[email protected]'] });
- expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(1);
- expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(0);
- });
-
- it('sender "isNot": filters out the named sender, fires for everyone else', async () => {
- const f = conds({ field: 'sender', operator: 'isNot', value: ['[email protected]'] });
- expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(0);
- expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(1);
- });
-
- it('resolves sender to the group participant (author), not the group JID', async () => {
- const f = conds({ field: 'sender', operator: 'is', value: ['[email protected]'] });
- const data = { from: '[email protected]', author: '[email protected]', isGroup: true };
- expect(await deliveries(f, 'message.received', data)).toBe(1);
- });
-
- it('ANDs multiple conditions (all must match)', async () => {
- const f = conds(
- { field: 'sender', operator: 'is', value: ['[email protected]'] },
- { field: 'body', operator: 'contains', value: 'invoice' },
- );
- expect(await deliveries(f, 'message.received', { from: '[email protected]', body: 'the invoice is ready' })).toBe(1);
- expect(await deliveries(f, 'message.received', { from: '[email protected]', body: 'lunch?' })).toBe(0);
- expect(await deliveries(f, 'message.received', { from: '[email protected]', body: 'invoice' })).toBe(0);
- });
-
- it('body "contains" is case-insensitive by default and respects caseSensitive', async () => {
- const ci = conds({ field: 'body', operator: 'contains', value: 'ping' });
- expect(await deliveries(ci, 'message.received', { body: 'PING me' })).toBe(1);
- const cs = conds({ field: 'body', operator: 'contains', value: 'ping', caseSensitive: true });
- expect(await deliveries(cs, 'message.received', { body: 'PING me' })).toBe(0);
- });
-
- it('body "equals" fires only on an exact match', async () => {
- const f = conds({ field: 'body', operator: 'equals', value: 'order 42' });
- expect(await deliveries(f, 'message.received', { body: 'order 42' })).toBe(1);
- expect(await deliveries(f, 'message.received', { body: 'order 4242' })).toBe(0);
- });
-
- it('type "is" matches one of the listed message types', async () => {
- const f = conds({ field: 'type', operator: 'is', value: ['image', 'video'] });
- expect(await deliveries(f, 'message.received', { type: 'image' })).toBe(1);
- expect(await deliveries(f, 'message.received', { type: 'text' })).toBe(0);
- });
-
- it('boolean fields: fromMe and hasMedia', async () => {
- const fromMe = conds({ field: 'fromMe', operator: 'is', value: true });
- expect(await deliveries(fromMe, 'message.received', { fromMe: true })).toBe(1);
- expect(await deliveries(fromMe, 'message.received', { fromMe: false })).toBe(0);
-
- const hasMedia = conds({ field: 'hasMedia', operator: 'is', value: true });
- expect(await deliveries(hasMedia, 'message.received', { media: { mimetype: 'image/png' } })).toBe(1);
- expect(await deliveries(hasMedia, 'message.received', { body: 'just text' })).toBe(0);
- });
-
- it('filters message.edited through a wildcard subscription using its normalized message fields', async () => {
- const f = conds(
- { field: 'sender', operator: 'is', value: ['[email protected]'] },
- { field: 'body', operator: 'contains', value: 'invoice' },
- { field: 'type', operator: 'is', value: ['image'] },
- { field: 'hasMedia', operator: 'is', value: true },
- );
- const data = {
- author: '[email protected]',
- body: 'Updated invoice',
- type: 'image',
- hasMedia: true,
- };
-
- expect(await deliveries(f, 'message.edited', data)).toBe(1);
- expect(await deliveries(f, 'message.edited', { ...data, body: 'lunch?', hasMedia: false })).toBe(0);
- });
-
- it('mentions: fires when the message mentions one of the listed JIDs', async () => {
- const f = conds({ field: 'mentions', operator: 'is', value: ['[email protected]'] });
- expect(await deliveries(f, 'message.received', { mentionedIds: ['[email protected]', '[email protected]'] })).toBe(1);
- expect(await deliveries(f, 'message.received', { mentionedIds: ['[email protected]'] })).toBe(0);
- });
-
- it('skips message-only conditions on a non-message event (so it still fires)', async () => {
- // A webhook subscribed to '*' with message filters must not suppress non-message events.
- const f = conds({ field: 'sender', operator: 'is', value: ['[email protected]'] });
- expect(await deliveries(f, 'session.status', { status: 'connected' })).toBe(1);
- expect(await deliveries(f, 'message.received', { from: '[email protected]' })).toBe(0);
- });
-
- it('resolves a lid sender to its phone via the table, so a phone filter fires (else a silent miss)', async () => {
- const f = conds({ field: 'sender', operator: 'is', value: ['628999'] });
- const data = { from: '[email protected]', author: '111@lid', isGroup: true };
-
- // No mapping yet -> the lid author never matches the phone filter.
- lidStore.getCached.mockReturnValue(null);
- expect(await deliveries(f, 'message.received', data)).toBe(0);
-
- // Table maps lid 111 -> 628999 -> the same message now fires.
- lidStore.getCached.mockImplementation((lid: string) => (lid === '111' ? '628999' : null));
- expect(await deliveries(f, 'message.received', data)).toBe(1);
- });
- });
-
- // ── custom-header sanitization ───────────────────────────────
-
- describe('custom header merge', () => {
- it('drops reserved custom headers so the system headers always win', async () => {
- const webhook = createMockWebhook({
- events: ['message.received'],
- headers: { 'X-OpenWA-Event': 'forged', 'Content-Type': 'text/plain', 'X-Custom': 'ok' },
- });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
- const captured: Record<string, string> = {};
- const mockFetch = undiciFetch as jest.Mock;
- mockFetch.mockImplementation((_url: string, opts: RequestInit) => {
- Object.assign(captured, opts.headers as Record<string, string>);
- return Promise.resolve({ ok: true, status: 200 });
- });
-
- const payload: WebhookPayload = {
- event: 'message.received',
- data: {},
- timestamp: '',
- sessionId: 'sess-1',
- idempotencyKey: 'k',
- deliveryId: 'd',
- };
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: { sessionId: 'sess-1', event: 'message.received', payload },
- });
-
- await service.dispatch('sess-1', 'message.received', {});
-
- expect(captured['X-OpenWA-Event']).toBe('message.received'); // system value, not 'forged'
- expect(captured['Content-Type']).toBe('application/json');
- expect(captured['X-Custom']).toBe('ok'); // legitimate custom header preserved
- mockFetch.mockReset();
- });
- });
-
- // ── redirect refusal ─────────────────────────────────────────
-
- describe('dispatch — redirect refusal', () => {
- const mockFetch = undiciFetch as jest.Mock;
- const origProtect = process.env.WEBHOOK_SSRF_PROTECT;
-
- beforeEach(() => {
- process.env.WEBHOOK_SSRF_PROTECT = 'true';
- });
-
- afterEach(() => {
- mockFetch.mockReset();
- if (origProtect === undefined) delete process.env.WEBHOOK_SSRF_PROTECT;
- else process.env.WEBHOOK_SSRF_PROTECT = origProtect;
- });
-
- it('does NOT follow a redirect and treats it as a delivery failure when protection is on', async () => {
- // Public literal IP → assertSafeFetchUrl passes with no DNS lookup; retryCount:1 → no retry loop.
- const webhook = createMockWebhook({
- url: 'https://8.8.8.8/webhook',
- events: ['message.received'],
- retryCount: 1,
- });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- // Simulate undici's redirect:'manual' result — an opaque redirect, never followed.
- mockFetch.mockResolvedValue({ ok: false, status: 0, type: 'opaqueredirect' });
-
- const payload: WebhookPayload = {
- event: 'message.received',
- timestamp: '',
- sessionId: 'sess-1',
- idempotencyKey: 'k',
- deliveryId: 'd',
- data: {},
- };
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: { sessionId: 'sess-1', event: 'message.received', payload },
- });
-
- await service.dispatch('sess-1', 'message.received', {});
-
- // fetch was issued with redirect:'manual' and the redirect was NOT followed (no success path)
- expect(mockFetch).toHaveBeenCalledWith(
- 'https://8.8.8.8/webhook',
- expect.objectContaining({ redirect: 'manual' }),
- );
- expect(repository.update).not.toHaveBeenCalled(); // lastTriggeredAt never set → delivery failed
- expect(hookManager.execute).toHaveBeenCalledWith('webhook:error', expect.anything(), expect.anything());
- });
- });
-
- // ── generateSignature (via dispatch) ──────────────────────────────
-
- describe('generateSignature', () => {
- it('should produce valid HMAC-SHA256 signature', async () => {
- const webhook = createMockWebhook({
- events: ['message.received'],
- secret: 'test-secret-123',
- });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
-
- const capturedHeaders: Record<string, string> = {};
- const mockFetch = undiciFetch as jest.Mock;
- mockFetch.mockImplementation((_url: string, opts: RequestInit) => {
- Object.assign(capturedHeaders, opts.headers as Record<string, string>);
- return Promise.resolve({ ok: true, status: 200 });
- });
-
- const sigPayload: WebhookPayload = {
- event: 'message.received',
- data: {},
- timestamp: '',
- sessionId: 'sess-1',
- idempotencyKey: 'k',
- deliveryId: 'd',
- };
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: {
- sessionId: 'sess-1',
- event: 'message.received',
- payload: sigPayload,
- },
- });
-
- await service.dispatch('sess-1', 'message.received', {});
-
- // Verify signature format
- expect(capturedHeaders['X-OpenWA-Signature']).toMatch(/^sha256=[a-f0-9]{64}$/);
-
- // Verify signature correctness against the ACTUAL delivered body. The body now carries the
- // server-canonical idempotency/delivery ids (re-asserted over the plugin's 'k'/'d'), so the
- // signature is checked against what the receiver actually gets — the real verification contract.
- const sentBody = (mockFetch.mock.calls[0] as [unknown, { body: string }])[1].body;
- const expected = `sha256=${crypto.createHmac('sha256', 'test-secret-123').update(sentBody).digest('hex')}`;
- expect(capturedHeaders['X-OpenWA-Signature']).toBe(expected);
-
- mockFetch.mockReset();
- });
- });
-
- // ── dispatch (queue mode) ─────────────────────────────────────────
-
- describe('dispatch (queue mode)', () => {
- afterEach(() => (undiciFetch as jest.Mock).mockReset());
-
- const buildQueueService = async (configGet: (key: string, def?: unknown) => unknown): Promise<WebhookService> => {
- const queueModule: TestingModule = await Test.createTestingModule({
- providers: [
- WebhookService,
- { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
- { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },
- { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },
- { provide: ConfigService, useValue: { get: jest.fn().mockImplementation(configGet) } },
- { provide: HookManager, useValue: hookManager },
- { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
- ],
- }).compile();
- return queueModule.get<WebhookService>(WebhookService);
- };
-
- it('enqueues a small, media-shed job when the event carries over-threshold media', async () => {
- const queueService = await buildQueueService((key: string, def?: unknown) => {
- if (key === 'queue.enabled') return true;
- if (key === 'webhook.retryDelay') return 5000;
- if (key === 'webhook.mediaInlineMaxBytes') return 1024;
- return def;
- });
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
-
- const base64 = Buffer.alloc(2048, 5).toString('base64'); // 2048 decoded bytes > 1024 cap
- await queueService.dispatch('sess-1', 'message.received', {
- media: { mimetype: 'image/jpeg', data: base64 },
- });
-
- expect(webhookQueue.add).toHaveBeenCalledTimes(1);
- const addCalls = (webhookQueue.add as jest.Mock).mock.calls as Array<[string, WebhookJobData]>;
- const jobData = addCalls[0][1];
- // The blob is shed BEFORE enqueue: a failed job retains only the marker in Redis, and the
- // bounded removeOnFail window (WEBHOOK_QUEUE_JOB_OPTIONS) keeps count × bytes bounded.
- expect((jobData.payload.data as { media: Record<string, unknown> }).media).toEqual({
- mimetype: 'image/jpeg',
- omitted: true,
- sizeBytes: 2048,
- });
- expect(JSON.stringify(jobData).length).toBeLessThan(2048);
- });
-
- it('keys the queue job by the delivery id, so a retried enqueue cannot double-deliver', async () => {
- const queueService = await buildQueueService((key: string, def?: unknown) => {
- if (key === 'queue.enabled') return true;
- if (key === 'webhook.retryDelay') return 5000;
- return def;
- });
- (repository.find as jest.Mock).mockResolvedValue([createMockWebhook({ events: ['message.received'] })]);
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
-
- await queueService.dispatch('sess-1', 'message.received', {});
-
- const [, jobData, opts] = (webhookQueue.add as jest.Mock).mock.calls[0] as [
- string,
- WebhookJobData,
- { jobId?: string },
- ];
- // BullMQ's dedupe boundary and the receiver's must key off the SAME identifier, or a job
- // that BullMQ accepts twice still looks like one delivery to the receiver (and vice versa).
- expect(opts.jobId).toBe(jobData.headers['X-OpenWA-Delivery-Id']);
- expect(opts.jobId).toBe(jobData.payload.deliveryId);
- });
-
- it('gives sibling webhooks distinct job ids, so one event fanning out is not collapsed into one job', async () => {
- const queueService = await buildQueueService((key: string, def?: unknown) => {
- if (key === 'queue.enabled') return true;
- if (key === 'webhook.retryDelay') return 5000;
- return def;
- });
- (repository.find as jest.Mock).mockResolvedValue([
- createMockWebhook({ id: 'wh-uuid-1', events: ['message.received'] }),
- createMockWebhook({ id: 'wh-uuid-2', events: ['message.received'], url: 'https://example.com/other' }),
- ]);
- (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
-
- await queueService.dispatch('sess-1', 'message.received', {});
-
- // Guards the invariant that makes jobId = deliveryId safe: deliveryId is minted per webhook
- // per dispatch. Were it ever hoisted to per-event, BullMQ would silently drop every
- // subscription after the first — a data-loss bug with no error anywhere.
- expect(webhookQueue.add).toHaveBeenCalledTimes(2);
- const jobIds = (webhookQueue.add as jest.Mock).mock.calls.map(
- (call: [string, WebhookJobData, { jobId?: string }]) => call[2].jobId,
- );
- expect(new Set(jobIds).size).toBe(2);
- });
-
- it('should add job to queue when queue is enabled', async () => {
- // Create a new service with queue enabled
- const queueModule: TestingModule = await Test.createTestingModule({
- providers: [
- WebhookService,
- { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
- { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },
- { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },
- {
- provide: ConfigService,
- useValue: {
- get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
- if (key === 'queue.enabled') return true;
- if (key === 'webhook.retryDelay') return 5000;
- return def as T;
- }),
- },
- },
- { provide: HookManager, useValue: hookManager },
- { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
- ],
- }).compile();
-
- const queueService = queueModule.get<WebhookService>(WebhookService);
-
- const webhook = createMockWebhook({ events: ['message.received'] });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
-
- const queuePayload: WebhookPayload = {
- event: 'message.received',
- data: {},
- timestamp: '',
- sessionId: 'sess-1',
- idempotencyKey: 'k',
- deliveryId: 'd',
- };
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: {
- sessionId: 'sess-1',
- event: 'message.received',
- payload: queuePayload,
- },
- });
-
- await queueService.dispatch('sess-1', 'message.received', {});
-
- expect(webhookQueue.add).toHaveBeenCalledWith(
- expect.stringContaining('webhook-'),
- expect.objectContaining({
- webhookId: 'wh-uuid-1',
- url: 'https://example.com/webhook',
- event: 'message.received',
- }),
- expect.objectContaining({
- attempts: 3,
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- backoff: expect.objectContaining({ type: 'exponential' }),
- }),
- );
- });
-
- it('falls back to direct delivery when queue add fails', async () => {
- const queueModule: TestingModule = await Test.createTestingModule({
- providers: [
- WebhookService,
- { provide: getRepositoryToken(Webhook, 'data'), useValue: repository },
- { provide: getRepositoryToken(WebhookDeliveryFailure, 'data'), useValue: failureRepository },
- { provide: getRepositoryToken(Session, 'data'), useValue: sessionRepository },
- {
- provide: ConfigService,
- useValue: {
- get: jest.fn().mockImplementation(<T>(key: string, def?: T): T | boolean | number => {
- if (key === 'queue.enabled') return true;
- if (key === 'webhook.retryDelay') return 5000;
- if (key === 'webhook.timeout') return 25000;
- return def as T;
- }),
- },
- },
- { provide: HookManager, useValue: hookManager },
- { provide: getQueueToken(QUEUE_NAMES.WEBHOOK), useValue: webhookQueue },
- ],
- }).compile();
-
- const queueService = queueModule.get<WebhookService>(WebhookService);
- const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });
- const queuePayload: WebhookPayload = {
- event: 'message.received',
- data: {},
- timestamp: '',
- sessionId: 'sess-1',
- idempotencyKey: 'k',
- deliveryId: 'd',
- };
- const mockFetch = undiciFetch as jest.Mock;
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: { sessionId: 'sess-1', event: 'message.received', payload: queuePayload },
- });
- webhookQueue.add.mockRejectedValueOnce(new Error('redis down'));
- mockFetch.mockResolvedValue({ ok: true, status: 200 });
-
- await queueService.dispatch('sess-1', 'message.received', {});
-
- expect(webhookQueue.add).toHaveBeenCalled();
- expect(mockFetch).toHaveBeenCalledWith(
- 'https://example.com/webhook',
- expect.objectContaining({ method: 'POST' }),
- );
- expect(hookManager.execute).toHaveBeenCalledWith(
- 'webhook:delivered',
- expect.objectContaining({ webhookId: webhook.id, fallback: 'queue_failed' }),
- expect.anything(),
- );
- });
- });
-
- describe('delivery-failure dead-letter', () => {
- it('records a durable failure when a direct delivery exhausts its retries', async () => {
- const webhook = createMockWebhook({ events: ['message.received'], retryCount: 1 });
- (repository.find as jest.Mock).mockResolvedValue([webhook]);
- (hookManager.execute as jest.Mock).mockResolvedValue({
- continue: true,
- data: {
- payload: {
- event: 'message.received',
- timestamp: '',
- sessionId: 'sess-1',
- idempotencyKey: 'k',
- deliveryId: 'd',
- data: {},
- },
- },
- });
- const mockFetch = undiciFetch as jest.Mock;
- mockFetch.mockResolvedValue({ ok: false, status: 500, statusText: 'Server Error' });
-
- const failuresBefore = getWebhookDeliveryFailuresTotal();
- await service.dispatch('sess-1', 'message.received', {});
-
- expect(failureRepository.insert).toHaveBeenCalledWith(
- expect.objectContaining({
- webhookId: webhook.id,
- attempts: 1,
- lastStatusCode: 500,
- lastError: 'HTTP 500: Server Error',
- }),
- );
- // The terminal failure also bumps the Prometheus counter exactly once.
- expect(getWebhookDeliveryFailuresTotal()).toBe(failuresBefore + 1);
- mockFetch.mockReset();
- });
-
- it('listDeliveryFailures queries most-recent-first, optionally scoped to a session', async () => {
+ describe('listDeliveryFailures', () => {
+ it('queries most-recent-first, optionally scoped to a session', async () => {
(failureRepository.find as jest.Mock).mockResolvedValue([{ id: 'f1' }]);
const out = await service.listDeliveryFailures({ sessionId: 's1', limit: 10 });
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index b099c3ff5..320be5174 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -1,31 +1,15 @@
-import {
- Injectable,
- NotFoundException,
- Optional,
- BadRequestException,
- OnModuleInit,
- OnModuleDestroy,
-} from '@nestjs/common';
+import { Injectable, NotFoundException, BadRequestException, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FindManyOptions, In, LessThan, Repository } from 'typeorm';
import { ConfigService } from '@nestjs/config';
-import { InjectQueue } from '@nestjs/bullmq';
-import { Queue } from 'bullmq';
-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 { Session } from '../session/entities/session.entity';
-import { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';
import { CreateWebhookDto, UpdateWebhookDto } from './dto';
import { createLogger } from '../../common/services/logger.service';
import { resolveSessionScope } from '../../common/security/session-scope';
-import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';
import { ListOptions, resolveListWindow } from '../../common/utils/paginate';
-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 {
assertSafeFetchUrl,
withSafeFetch,
@@ -34,35 +18,11 @@ import {
SSRF_BLOCKED_CLIENT_MESSAGE,
redactSsrfError,
} from '../../common/security/ssrf-guard';
-import { HookManager } from '../../core/hooks';
-import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
-
-export interface WebhookPayload {
- event: string;
- timestamp: string;
- sessionId: string;
- idempotencyKey: string;
- deliveryId: string;
- data: Record<string, unknown>;
-}
+import { WebhookDeliveryService, WebhookPayload } from './webhook-delivery.service';
-export interface WebhookJobData {
- webhookId: string;
- url: string;
- event: string;
- payload: WebhookPayload;
- headers: Record<string, string>;
- attempt: number;
- 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;
+// Delivery-engine types (payload and queue job shapes) live on WebhookDeliveryService; re-exported
+// here so existing importers (the queue processor) keep a single stable path.
+export type { WebhookPayload, WebhookJobData } from './webhook-delivery.service';
/**
* Upper bound on how many webhooks one session can register. One inbound event fans out to EVERY
@@ -73,43 +33,14 @@ const DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES = 1024 * 1024;
const DEFAULT_WEBHOOK_MAX_PER_SESSION = 16;
/**
- * Decoded-byte cap for inline base64 media in webhook payloads. A larger blob is replaced with the
- * engine's omitted-marker shape ({ mimetype, filename?, omitted: true, sizeBytes }) before the
- * payload is cloned per webhook or queued, so fan-out and Redis retention never copy it. Default
- * 1 MiB; override with WEBHOOK_MEDIA_INLINE_MAX_BYTES (0 = never inline media).
+ * Webhook registration and operational queries: CRUD, the test probe, and the delivery-failure
+ * listing/retention. Event delivery itself (fan-out, queueing, retries, dead-lettering) lives on
+ * WebhookDeliveryService; dispatch() here is the stable facade every event producer calls.
*/
-const DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_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;
-
-/** Per-event-occurrence context threaded through the dispatch pipeline stages (was closure state). */
-interface DispatchEventContext {
- sessionId: string;
- event: string;
- baseData: Record<string, unknown>;
-}
-
@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')
@@ -119,22 +50,8 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
@InjectRepository(Session, 'data')
private readonly sessionRepository: Repository<Session>,
private readonly configService: ConfigService,
- private readonly hookManager: HookManager,
- @Optional()
- private readonly lidMappingStore?: LidMappingStoreService,
- @Optional()
- @InjectQueue(QUEUE_NAMES.WEBHOOK)
- private readonly webhookQueue?: Queue<WebhookJobData>,
- ) {
- this.queueEnabled = configService.get<boolean>('queue.enabled', false);
- // Bound fan-out: cap how many matching webhooks are delivered CONCURRENTLY for one event. Without
- // it, an event matching N webhooks opens N outbound sockets at once. Default 16
- // (WEBHOOK_DISPATCH_CONCURRENCY).
- this.dispatchLimiter = new ConcurrencyLimiter(
- this.configService.get<number>('webhook.dispatchConcurrency', 16),
- this.configService.get<number>('webhook.dispatchMaxQueued', 1000),
- );
- }
+ private readonly delivery: WebhookDeliveryService,
+ ) {}
/**
* Periodically prune webhook_delivery_failures older than WEBHOOK_FAILURE_RETENTION_DAYS
@@ -143,22 +60,6 @@ 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) {
@@ -179,43 +80,10 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
this.cleanupTimer.unref?.();
}
- /**
- * Bounded drain of the direct-delivery path (queued BullMQ jobs are durable in Redis and need no
- * drain). In direct mode, closing the limiter rejects every PARKED delivery; the dispatch catch
- * records each one in webhook_delivery_failures like any other undispatched delivery. Queued mode
- * skips the close: a parked dispatch's whole job is webhookQueue.add() — durable in Redis the
- * moment it resolves — so rejecting it would dead-letter work Redis could have kept. A parked
- * waiter holds an activeCount slot via handoff, so the drain loop below covers it either way.
- * 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> {
+ onModuleDestroy(): void {
if (this.cleanupTimer) {
clearInterval(this.cleanupTimer);
}
- if (!this.queueEnabled) {
- 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 setTimeout(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();
}
/**
@@ -386,7 +254,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
const body = JSON.stringify(testPayload);
const headers: Record<string, string> = {
// Custom headers FIRST so the system headers below always win.
- ...this.sanitizeCustomHeaders(webhook.headers),
+ ...this.delivery.sanitizeCustomHeaders(webhook.headers),
'Content-Type': 'application/json',
'User-Agent': 'OpenWA-Webhook/1.0.0',
'X-OpenWA-Event': 'test',
@@ -396,7 +264,7 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
};
if (webhook.secret) {
- headers['X-OpenWA-Signature'] = this.generateSignature(body, webhook.secret);
+ headers['X-OpenWA-Signature'] = this.delivery.generateSignature(body, webhook.secret);
}
try {
@@ -420,599 +288,8 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {
}
}
+ /** Delivery facade: same entry point event producers have always called; the engine lives on WebhookDeliveryService. */
async dispatch(sessionId: string, event: string, data: Record<string, unknown>): Promise<void> {
- const webhooks = await this.loadActiveWebhooks(sessionId, event);
- const matchingWebhooks = this.filterMatchingWebhooks(webhooks, event, data);
-
- // Base idempotency key for this event occurrence. occurredAt is captured once here and reused for
- // every retry of this dispatch, so recurring lifecycle events get a distinct-per-occurrence key
- // while retries of the same event stay stable. It is salted PER WEBHOOK below.
- const occurredAt = new Date().toISOString();
- const baseIdempotencyKey = generateIdempotencyKey(event, { ...data, sessionId }, occurredAt);
-
- // Fan-out amplification bound: shed an over-cap inline media blob ONCE here, before the
- // per-webhook structuredClone below, so N matching webhooks (and the queued jobs retained in
- // Redis) never copy the blob. The per-webhook clone stays — a webhook:before hook may mutate
- // payload.data in place and must not bleed into siblings — but after shedding it is small.
- const baseData =
- matchingWebhooks.length > 0
- ? this.shedInlineMedia(
- data,
- this.configService.get<number>('webhook.mediaInlineMaxBytes', DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES),
- )
- : data;
-
- const ctx: DispatchEventContext = { sessionId, event, baseData };
- // allSettled preserves the per-webhook isolation: one failing delivery never rejects the others.
- await Promise.allSettled(matchingWebhooks.map(webhook => this.dispatchWithLimit(webhook, baseIdempotencyKey, ctx)));
- }
-
- /**
- * Callers fire-and-forget this (`void dispatch(...)`), so a failure looking up webhooks must be
- * logged and swallowed here — otherwise it surfaces as an unhandled promise rejection.
- */
- private async loadActiveWebhooks(sessionId: string, event: string): Promise<Webhook[]> {
- try {
- return await this.webhookRepository.find({
- where: { sessionId, active: true },
- });
- } catch (error) {
- this.logger.error(`Webhook dispatch lookup failed for ${event}`, String(error), {
- sessionId,
- action: 'webhook_dispatch_lookup_failed',
- });
- return [];
- }
- }
-
- private filterMatchingWebhooks(webhooks: Webhook[], event: string, data: Record<string, unknown>): Webhook[] {
- // Resolve a lid actor to its phone through the persistent table so a phone filter matches a
- // lid-addressed sender (e.g. an unresolved @lid group participant). Absent store -> no resolution.
- const resolveLid = (jid: string): string | null => this.lidMappingStore?.resolveLid(jid) ?? null;
- const subscribed = webhooks.filter(w => w.events.includes(event) || w.events.includes('*'));
- const matching = subscribed.filter(w => evaluateFilters(w.filters, event, data, resolveLid));
- // A subscribed webhook that a filter drops leaves no trace otherwise: dispatch() awaits an empty
- // array and returns, and the delivery-failure table only records deliveries that were ATTEMPTED.
- // That is fine when the filter is doing its job, and indistinguishable from it when it is not —
- // a condition on a field the event's payload does not carry resolves to undefined and fails,
- // which is how a `sender` filter silently swallows every message.ack. Debug rather than warn:
- // suppression is the normal outcome of a working filter, so this is a trace to switch on while
- // investigating, not an alarm.
- if (matching.length < subscribed.length) {
- this.logger.debug('Webhook filters suppressed a delivery', {
- action: 'webhook_filter_suppressed',
- event,
- subscribed: subscribed.length,
- suppressed: subscribed.length - matching.length,
- payloadFields: Object.keys(data).sort().join(','),
- });
- }
- return matching;
- }
-
- private async recordUndelivered(
- webhook: Webhook,
- deliveryId: string,
- idempotencyKey: string,
- error: unknown,
- action: string,
- ctx: DispatchEventContext,
- ): Promise<void> {
- const { sessionId, event } = ctx;
- const lastError = redactSsrfError(error, this.logger, 'webhook dispatch');
- await recordWebhookDeliveryFailure(this.failureRepository, this.logger, {
- webhookId: webhook.id,
- sessionId,
- event,
- url: webhook.url,
- idempotencyKey,
- deliveryId,
- attempts: 0,
- lastStatusCode: null,
- lastError,
- });
- incrementWebhookDeliveryFailures();
- try {
- await this.hookManager.execute(
- 'webhook:error',
- { sessionId, event, webhookId: webhook.id, deliveryId, error: lastError },
- { sessionId, source: 'WebhookService' },
- );
- } catch (hookError) {
- this.logger.error('webhook:error hook failed while reporting an undelivered webhook', String(hookError), {
- webhookId: webhook.id,
- deliveryId,
- action: 'webhook_error_hook_failed',
- });
- }
- this.logger.error(`Webhook ${webhook.id} was not dispatched`, lastError, {
- webhookId: webhook.id,
- deliveryId,
- action,
- });
- }
-
- /**
- * Build one webhook delivery: payload + webhook:before hooks + identity re-assertion + size gate +
- * headers. Returns null when the delivery must not proceed — either cancelled by a plugin (a debug
- * log, not a failure) or after a failure already recorded via recordUndelivered.
- */
- private async preflightDelivery(
- webhook: Webhook,
- deliveryId: string,
- idempotencyKey: string,
- ctx: DispatchEventContext,
- ): Promise<{ finalPayload: WebhookPayload; body: string; headers: Record<string, string> } | null> {
- const { sessionId, event, baseData } = ctx;
- try {
- const payload: WebhookPayload = {
- event,
- timestamp: new Date().toISOString(),
- sessionId,
- idempotencyKey,
- deliveryId,
- // Give each webhook its own copy of the event data: a webhook:before hook that mutates
- // payload.data in place would otherwise bleed that change into sibling webhooks.
- data: structuredClone(baseData),
- };
- // 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',
- { sessionId, event, payload },
- { sessionId, source: 'WebhookService' },
- );
-
- if (!shouldContinue) {
- this.logger.debug(`Webhook dispatch cancelled by plugin for ${event}`, {
- webhookId: webhook.id,
- action: 'webhook_cancelled_by_plugin',
- });
- return null;
- }
-
- // Null/undefined hook results mean "no override", matching an object without payload.
- const 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.
- // The bytes are serialized ONCE and reused for the size gate, the HMAC signature, and the
- // direct-delivery body (BullMQ re-serializes jobData itself — unavoidable).
- const maxPayloadBytes = this.configService.get<number>(
- 'webhook.maxPayloadBytes',
- DEFAULT_WEBHOOK_MAX_PAYLOAD_BYTES,
- );
- let body = JSON.stringify(finalPayload);
- let payloadBytes = Buffer.byteLength(body, 'utf8');
- if (payloadBytes > maxPayloadBytes) {
- // Size-gated body shedding: over budget, strip ANY remaining inline media blob (threshold
- // 0 — the marker form keeps the event deliverable) and re-check, instead of dropping the
- // event or queueing a giant payload.
- const shedData = this.shedInlineMedia(finalPayload.data, 0);
- if (shedData !== finalPayload.data) {
- finalPayload.data = shedData;
- body = JSON.stringify(finalPayload);
- payloadBytes = Buffer.byteLength(body, 'utf8');
- }
- }
- if (payloadBytes > maxPayloadBytes) {
- await this.recordUndelivered(
- webhook,
- deliveryId,
- idempotencyKey,
- new Error(
- `Webhook payload is ${payloadBytes} bytes after webhook:before hooks, exceeding the ${maxPayloadBytes}-byte cap`,
- ),
- 'webhook_payload_oversize',
- ctx,
- );
- return null;
- }
-
- const headers = {
- ...this.sanitizeCustomHeaders(webhook.headers),
- 'Content-Type': 'application/json',
- 'User-Agent': 'OpenWA-Webhook/1.0.0',
- 'X-OpenWA-Event': event,
- 'X-OpenWA-Idempotency-Key': idempotencyKey,
- 'X-OpenWA-Delivery-Id': deliveryId,
- 'X-OpenWA-Retry-Count': '0',
- };
- return { finalPayload, body, headers };
- } catch (error) {
- await this.recordUndelivered(
- webhook,
- deliveryId,
- idempotencyKey,
- error,
- 'webhook_dispatch_preflight_failed',
- ctx,
- );
- return null;
- }
- }
-
- private async deliverOne(
- webhook: Webhook,
- deliveryId: string,
- idempotencyKey: string,
- ctx: DispatchEventContext,
- ): Promise<void> {
- const preflight = await this.preflightDelivery(webhook, deliveryId, idempotencyKey, ctx);
- if (!preflight) {
- return;
- }
- const { finalPayload, body, headers } = preflight;
- // Use queue if available, otherwise fallback to direct delivery
- if (this.queueEnabled && this.webhookQueue) {
- await this.enqueueWithFallback(webhook, finalPayload, body, headers, deliveryId, idempotencyKey, ctx);
- } else {
- await this.deliverDirect(webhook, finalPayload, body, headers, deliveryId, ctx);
- }
- }
-
- private async enqueueWithFallback(
- webhook: Webhook,
- finalPayload: WebhookPayload,
- body: string,
- headers: Record<string, string>,
- deliveryId: string,
- idempotencyKey: string,
- ctx: DispatchEventContext,
- ): Promise<void> {
- const { sessionId, event } = ctx;
- try {
- // Sign the exact pre-serialized body from preflight. The processor re-serializes the same
- // payload object at delivery time (JSON key order survives the Redis round-trip), so the
- // signature stays valid over the bytes the receiver sees.
- const signature = webhook.secret ? this.generateSignature(body, webhook.secret) : '';
-
- if (webhook.secret) {
- headers['X-OpenWA-Signature'] = signature;
- }
-
- const jobData: WebhookJobData = {
- webhookId: webhook.id,
- url: webhook.url,
- event,
- payload: finalPayload,
- headers,
- attempt: 1,
- maxRetries: webhook.retryCount,
- };
-
- await this.webhookQueue!.add(`webhook-${webhook.id}`, jobData, {
- // jobId = deliveryId gives BullMQ exactly-once enqueue semantics (same precedent as the
- // ingress producer), so a crash between add() and the bookkeeping below cannot re-enqueue
- // the same delivery. Safe for fan-out: deliveryId is minted per webhook per dispatch in
- // dispatchWithLimit, so sibling subscriptions to one event never share a job id.
- jobId: deliveryId,
- attempts: webhook.retryCount,
- backoff: {
- type: 'exponential',
- delay: this.configService.get<number>('webhook.retryDelay', 5000),
- },
- });
-
- // Execute hook after successful queue (NOT delivery - that happens in processor)
- await this.hookManager.execute(
- 'webhook:queued',
- { sessionId, event, webhookId: webhook.id, deliveryId },
- { sessionId, source: 'WebhookService' },
- );
-
- this.logger.debug(`Webhook job queued for ${webhook.id}`, {
- webhookId: webhook.id,
- event,
- idempotencyKey,
- deliveryId,
- action: 'webhook_queued',
- });
- } catch (error) {
- // Execute hook on queue error (not delivery error - that happens in processor)
- await this.hookManager.execute(
- 'webhook:error',
- { sessionId, event, webhookId: webhook.id, error: `Queue failed: ${String(error)}` },
- { sessionId, source: 'WebhookService' },
- );
-
- this.logger.error(`Failed to queue webhook ${webhook.id}`, String(error), {
- webhookId: webhook.id,
- action: 'webhook_queue_failed',
- });
-
- // Fallback: deliver directly when the queue add failed (e.g. Redis unreachable with the
- // producer's enableOfflineQueue:false). This is at-least-once — if add() actually reached
- // Redis before rejecting, the queued job AND this fallback may both POST. Both paths carry the
- // same X-OpenWA-Idempotency-Key / X-OpenWA-Delivery-Id, so a conformant receiver dedupes.
- try {
- await this.deliverWebhook(webhook, finalPayload, headers, body);
-
- await this.hookManager.execute(
- 'webhook:delivered',
- { sessionId, event, webhookId: webhook.id, deliveryId, fallback: 'queue_failed' },
- { sessionId, source: 'WebhookService' },
- );
-
- await this.hookManager.execute(
- 'webhook:after',
- { sessionId, event, webhookId: webhook.id, success: true, fallback: 'queue_failed' },
- { sessionId, source: 'WebhookService' },
- );
- } catch (fallbackError) {
- await this.hookManager.execute(
- 'webhook:error',
- {
- sessionId,
- event,
- webhookId: webhook.id,
- error: `Queue fallback delivery failed: ${redactSsrfError(fallbackError, this.logger, 'webhook fallback delivery')}`,
- },
- { sessionId, source: 'WebhookService' },
- );
-
- this.logger.error(`Queue fallback delivery failed for webhook ${webhook.id}`, String(fallbackError), {
- webhookId: webhook.id,
- action: 'webhook_queue_fallback_failed',
- });
- }
- }
- }
-
- /** Direct delivery when the queue is disabled. */
- private async deliverDirect(
- webhook: Webhook,
- finalPayload: WebhookPayload,
- body: string,
- headers: Record<string, string>,
- deliveryId: string,
- ctx: DispatchEventContext,
- ): Promise<void> {
- const { sessionId, event } = ctx;
- try {
- await this.deliverWebhook(webhook, finalPayload, headers, body);
-
- // Execute hook after successful delivery
- await this.hookManager.execute(
- 'webhook:delivered',
- { sessionId, event, webhookId: webhook.id, deliveryId },
- { sessionId, source: 'WebhookService' },
- );
-
- // Legacy hook for backward compatibility
- await this.hookManager.execute(
- 'webhook:after',
- { sessionId, event, webhookId: webhook.id, success: true },
- { sessionId, source: 'WebhookService' },
- );
- } catch (error) {
- // Execute hook on error
- await this.hookManager.execute(
- 'webhook:error',
- { sessionId, event, webhookId: webhook.id, error: redactSsrfError(error, this.logger, 'webhook delivery') },
- { sessionId, source: 'WebhookService' },
- );
-
- this.logger.error(`Failed to deliver webhook ${webhook.id}`, String(error), {
- webhookId: webhook.id,
- action: 'webhook_delivery_failed',
- });
- }
- }
-
- /**
- * Bound fan-out: deliver to all matching webhooks concurrently, but cap in-flight deliveries at
- * WEBHOOK_DISPATCH_CONCURRENCY so an event matching many webhooks (or slow receivers) can't open an
- * unbounded number of outbound sockets at once.
- */
- private async dispatchWithLimit(
- webhook: Webhook,
- baseIdempotencyKey: string,
- ctx: DispatchEventContext,
- ): Promise<void> {
- const { sessionId, event } = ctx;
- const deliveryId = generateDeliveryId();
- // Salt per webhook so sibling subscriptions cannot collide at the receiver's dedup boundary.
- const idempotencyKey = `${baseIdempotencyKey}_${webhook.id}`;
- await this.dispatchLimiter
- .run(async () => {
- this.inFlightDeliveries.set(deliveryId, {
- webhookId: webhook.id,
- sessionId,
- event,
- idempotencyKey,
- url: webhook.url,
- });
- try {
- await this.deliverOne(webhook, deliveryId, idempotencyKey, ctx);
- } finally {
- this.inFlightDeliveries.delete(deliveryId);
- }
- })
- .catch(async error => {
- if (error instanceof Error && error.message === 'ConcurrencyLimiter queue full') {
- await this.recordUndelivered(
- webhook,
- deliveryId,
- idempotencyKey,
- error,
- 'webhook_dispatch_capacity_exceeded',
- ctx,
- );
- 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 = this.recordUndelivered(
- webhook,
- deliveryId,
- idempotencyKey,
- error,
- 'webhook_dispatch_shutdown',
- ctx,
- );
- this.pendingBookkeeping.add(record);
- try {
- await record;
- } finally {
- this.pendingBookkeeping.delete(record);
- }
- return;
- }
- throw error;
- });
- }
-
- /**
- * @deprecated Use job queue dispatch instead. This is kept for fallback.
- * `body` is the pre-serialized payload from preflight — the exact bytes the size gate checked and
- * (when a secret is set) the signature covers — so it is never re-serialized here.
- */
- private async deliverWebhook(
- webhook: Webhook,
- payload: WebhookPayload,
- headers: Record<string, string>,
- body: string,
- attempt = 1,
- ): Promise<void> {
- // Update retry count header
- headers['X-OpenWA-Retry-Count'] = String(attempt - 1);
-
- // Add signature if secret is configured and not already present
- if (webhook.secret && !headers['X-OpenWA-Signature']) {
- headers['X-OpenWA-Signature'] = this.generateSignature(body, webhook.secret);
- }
-
- 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}`);
- }
-
- // 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,
- deliveryId: payload.deliveryId,
- action: 'webhook_delivered',
- });
- } catch (error) {
- this.logger.error(`Webhook delivery failed for ${webhook.id}`, String(error), {
- webhookId: webhook.id,
- attempt,
- deliveryId: payload.deliveryId,
- action: 'webhook_delivery_failed',
- });
-
- if (attempt < webhook.retryCount) {
- const delay = this.configService.get<number>('webhook.retryDelay', 5000);
- await setTimeout(delay * attempt);
- return this.deliverWebhook(webhook, payload, headers, body, attempt + 1);
- }
- // 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, {
- webhookId: webhook.id,
- sessionId: payload.sessionId,
- event: payload.event,
- url: webhook.url,
- idempotencyKey: payload.idempotencyKey,
- deliveryId: payload.deliveryId,
- attempts: attempt,
- lastStatusCode: statusCodeFromError(errMessage),
- lastError: errMessage,
- });
- incrementWebhookDeliveryFailures();
- throw error;
- }
- }
-
- /**
- * Replace an over-size inline base64 blob on `data.media` with the engine's omitted-marker shape
- * ({ mimetype, filename?, omitted: true, sizeBytes }) — the same contract the inbound media cap
- * and the status store already emit — so the multi-MB blob is never cloned per webhook, queued
- * into Redis, or POSTed. Returns the ORIGINAL object when nothing was shed (zero-copy fast path);
- * otherwise a shallow copy with only `media` replaced, so the caller's event data is never
- * mutated. `maxBytes` compares against the DECODED size; 0 sheds any inline blob.
- */
- private shedInlineMedia(data: Record<string, unknown>, maxBytes: number): Record<string, unknown> {
- if (!data || typeof data !== 'object') return data;
- const media = data.media as
- { mimetype?: unknown; filename?: unknown; data?: unknown; omitted?: unknown } | undefined;
- if (!media || typeof media !== 'object' || typeof media.data !== 'string' || media.data.length === 0) {
- return data;
- }
- const sizeBytes = Buffer.byteLength(media.data, 'base64');
- if (sizeBytes <= maxBytes) return data;
- return {
- ...data,
- media: {
- mimetype: media.mimetype,
- ...(typeof media.filename === 'string' ? { filename: media.filename } : {}),
- omitted: true,
- sizeBytes,
- },
- };
- }
-
- /**
- * Drop operator-supplied custom headers that target reserved names (Content-Type or any
- * X-OpenWA-* header) so a webhook config cannot forge the signature/event/idempotency
- * headers. Spread the result BEFORE the system headers so system always wins.
- */
- private sanitizeCustomHeaders(custom: Record<string, string> | null | undefined): Record<string, string> {
- const safe: Record<string, string> = {};
- for (const [key, value] of Object.entries(custom ?? {})) {
- if (!/^(content-type|x-openwa-)/i.test(key)) {
- safe[key] = value;
- }
- }
- return safe;
- }
-
- private generateSignature(payload: string, secret: string): string {
- const hmac = crypto.createHmac('sha256', secret);
- hmac.update(payload);
- return `sha256=${hmac.digest('hex')}`;
+ await this.delivery.dispatch(sessionId, event, data);
}
}