Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(webhook): build the test probe headers with the delivery helper

Yudhi Armyndharis5513265d5448
diff --git a/src/modules/integration/ingress-signature.ts b/src/modules/integration/ingress-signature.ts
index 8fc6d9051..f62dd8acc 100644
--- a/src/modules/integration/ingress-signature.ts
+++ b/src/modules/integration/ingress-signature.ts
@@ -88,9 +88,9 @@ function verifyStandardWebhooks(spec: IngressSignatureSpec, input: VerifyInput):
}
/**
- * Inverts the outbound signer (webhook.service.ts:527-531) — but over the provider's declared
- * contentTemplate applied to the RAW request bytes, and with a constant-time compare. `now` is
- * injected so the replay-window check is deterministic in tests.
+ * Inverts the outbound signer (generateSignature in src/modules/webhook/utils/deliver-once.ts), but
+ * over the provider's declared contentTemplate applied to the RAW request bytes, and with a
+ * constant-time compare. `now` is injected so the replay-window check is deterministic in tests.
*/
export function verifyIngressSignature(
spec: IngressSignatureSpec,
diff --git a/src/modules/queue/processors/webhook.processor.ts b/src/modules/queue/processors/webhook.processor.ts
index bff444f94..e2ea06f5d 100644
--- a/src/modules/queue/processors/webhook.processor.ts
+++ b/src/modules/queue/processors/webhook.processor.ts
@@ -156,7 +156,7 @@ export class WebhookProcessor extends WorkerHost {
url,
body,
requestHeaders,
- // Honor WEBHOOK_TIMEOUT on the primary (queued) path too — not just the deprecated direct one.
+ // Honor WEBHOOK_TIMEOUT on the queued path too, as the direct path does.
this.configService.get<number>('webhook.timeout', 10000),
);
diff --git a/src/modules/webhook/webhook-delivery.service.ts b/src/modules/webhook/webhook-delivery.service.ts
index 7e025e5b7..27ba4f782 100644
--- a/src/modules/webhook/webhook-delivery.service.ts
+++ b/src/modules/webhook/webhook-delivery.service.ts
@@ -9,13 +9,7 @@ import { Webhook } from './entities/webhook.entity';
import { WebhookOutboxService } from './webhook-outbox.service';
import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';
import { clearDeliveryFailureRows, recordWebhookDeliveryFailure } from './utils/record-delivery-failure';
-import {
- buildDeliveryHeaders,
- generateSignature,
- postWebhookPayload,
- recordTerminalFailure,
- sanitizeCustomHeaders,
-} from './utils/deliver-once';
+import { buildDeliveryHeaders, postWebhookPayload, recordTerminalFailure } from './utils/deliver-once';
import { createLogger } from '../../common/services/logger.service';
import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';
import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';
@@ -736,7 +730,8 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
}
/**
- * @deprecated Use job queue dispatch instead. This is kept for fallback.
+ * Direct delivery with in-process retries, up to `webhook.retryCount` attempts: the path every
+ * delivery takes when the queue is disabled (the default), and the fallback when an enqueue fails.
* `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.
*/
@@ -750,11 +745,6 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
// 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 {
await postWebhookPayload(webhook.url, body, headers, this.configService.get<number>('webhook.timeout', 10000));
@@ -815,13 +805,4 @@ export class WebhookDeliveryService implements OnModuleInit, OnModuleDestroy {
throw error;
}
}
-
- /** 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> {
- return sanitizeCustomHeaders(custom);
- }
-
- generateSignature(payload: string, secret: string): string {
- return generateSignature(payload, secret);
- }
}
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 2d9758259..1373b0cec 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -10,6 +10,7 @@ jest.mock('undici', () => {
return { __esModule: true, ...actual, fetch: jest.fn() };
});
+import { createHmac } from 'crypto';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { getQueueToken } from '@nestjs/bullmq';
@@ -20,6 +21,7 @@ import { fetch as undiciFetch } from 'undici';
import { WebhookService } from './webhook.service';
import { WebhookOutboxService } from './webhook-outbox.service';
import { WebhookDeliveryService } from './webhook-delivery.service';
+import { buildDeliveryHeaders } from './utils/deliver-once';
import { Webhook } from './entities/webhook.entity';
import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
@@ -496,6 +498,41 @@ describe('WebhookService', () => {
for (const key of keys) expect(key.endsWith(`_${webhook.id}`)).toBe(true);
});
+ // The probe must carry exactly what a real delivery would, or a receiver that passes the test can
+ // still reject live traffic (a stripped header, a signature over different bytes).
+ it('test() sends the headers of a real delivery, signed over the exact body', async () => {
+ const webhook = createMockWebhook({
+ secret: 'probe-secret',
+ headers: { 'X-Custom': 'a', 'X-OpenWA-Event': 'forged', 'Content-Type': 'text/plain', Connection: 'close' },
+ });
+ (repository.findOne as jest.Mock).mockResolvedValue(webhook);
+ mockFetch.mockResolvedValue({ ok: true, status: 200 });
+
+ await expect(service.test('sess-1', webhook.id)).resolves.toEqual({ success: true, statusCode: 200 });
+
+ const [, init] = mockFetch.mock.calls[0] as [string, { headers: Record<string, string>; body: string }];
+ const sent = JSON.parse(init.body) as { idempotencyKey: string; deliveryId: string };
+ expect(init.headers).toEqual(
+ buildDeliveryHeaders(webhook, 'test', sent.idempotencyKey, sent.deliveryId, init.body),
+ );
+ expect(init.headers).toMatchObject({
+ 'X-Custom': 'a',
+ 'X-OpenWA-Event': 'test',
+ 'Content-Type': 'application/json',
+ 'X-OpenWA-Retry-Count': '0',
+ 'X-OpenWA-Signature': `sha256=${createHmac('sha256', 'probe-secret').update(init.body).digest('hex')}`,
+ });
+ expect(init.headers).not.toHaveProperty('Connection');
+ });
+
+ it('test() reports a non-2xx receiver answer as a status, without throwing', async () => {
+ const webhook = createMockWebhook();
+ (repository.findOne as jest.Mock).mockResolvedValue(webhook);
+ mockFetch.mockResolvedValue({ ok: false, status: 500 });
+
+ await expect(service.test('sess-1', webhook.id)).resolves.toEqual({ success: false, statusCode: 500 });
+ });
+
// A literal link-local IP is rejected synchronously by the SSRF guard before any fetch/DNS, so this
// is fully offline. The raw SsrfBlockedError message names the resolved internal IP — an SSRF
// disclosure oracle — so the test() response must surface the generic constant instead.
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index 3efd1517d..8e470f2c8 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -10,6 +10,7 @@ import { createLogger } from '../../common/services/logger.service';
import { resolveSessionScope } from '../../common/security/session-scope';
import { ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { generateDeliveryId } from './utils/idempotency.util';
+import { buildDeliveryHeaders } from './utils/deliver-once';
import {
assertSafeFetchUrl,
withSafeFetch,
@@ -261,20 +262,8 @@ 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.delivery.sanitizeCustomHeaders(webhook.headers),
- 'Content-Type': 'application/json',
- 'User-Agent': 'OpenWA-Webhook/1.0.0',
- 'X-OpenWA-Event': 'test',
- 'X-OpenWA-Idempotency-Key': testPayload.idempotencyKey,
- 'X-OpenWA-Delivery-Id': testPayload.deliveryId,
- 'X-OpenWA-Retry-Count': '0',
- };
-
- if (webhook.secret) {
- headers['X-OpenWA-Signature'] = this.delivery.generateSignature(body, webhook.secret);
- }
+ // The same header builder as a real delivery, so the probe tests what the receiver will get.
+ const headers = buildDeliveryHeaders(webhook, 'test', testPayload.idempotencyKey, deliveryId, body);
try {
return await withSafeFetch(