Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(catalog): run the message:sending gate on product sends

Yudhi Armyndharis0d427ef79670
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index bdf4663e5..1120e38cb 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -3663,7 +3663,7 @@ Send a product message (catalog product card) to a chat. Note: this route lives
**Response** `201` (Baileys engine only) — the sent `MessageResult`
-**Errors:** `400` missing `chatId`/`productId`, wrong types, any field not on the DTO, or a product with no image (a product card needs one) · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected`, or the product is not in the session catalog · `409` session present but not READY (retryable) · `500` engine error · `501` whatsapp-web.js only (no Catalog API) · `503` the catalog query went unanswered by WhatsApp, or the session/dependency is not ready (retryable only in the not-ready case; a silently unanswered catalog query does not clear on retry)
+**Errors:** `400` missing `chatId`/`productId`, wrong types, any field not on the DTO, a product with no image (a product card needs one), or a `message:sending` plugin blocked the send or returned an invalid `productId`/`body` · `401` missing/invalid API key · `403` API-key role below OPERATOR · `404` `Session <sessionId> not found or not connected`, or the product is not in the session catalog · `409` session present but not READY (retryable) · `500` engine error · `501` whatsapp-web.js only (no Catalog API) · `503` the catalog query went unanswered by WhatsApp, or the session/dependency is not ready (retryable only in the not-ready case; a silently unanswered catalog query does not clear on retry)
On whatsapp-web.js the readiness guard runs before the refusal, so a session that exists but is not
`READY` gets `409` instead of `501`. Baileys resolves the product from the session catalog and sends
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index 92b533e4f..be7a162e3 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -429,6 +429,11 @@ reads `input.chatId` on a single send reads it here too. A handler may rewrite t
rewritten `chatId` is ignored: the item always goes to its own recipient. On a single send the rewritten
`input` is what gets sent, `chatId` included.
+A product send (`POST /api/sessions/:sessionId/messages/send-product`) runs `message:sending` with type
+`product`, source `CatalogService` and `input` `{ chatId, productId, body }`. A handler may rewrite
+`productId` or `body`; a value that is not a string (or an empty `productId`) is refused with `400`. As
+with a bulk item, a rewritten `chatId` is ignored: the product goes to the chat the request named.
+
> **`message:sending` does not see every attempted send.** With send pacing enabled
> (`SEND_PACING_ENABLED`), the pacing governor runs _before_ this hook, so a send it refuses never
> fires `message:sending` — plugins are not asked to moderate, and cannot rewrite, traffic that
diff --git a/openapi.json b/openapi.json
index bbd93bed9..ed8ee71d6 100644
--- a/openapi.json
+++ b/openapi.json
@@ -8440,7 +8440,7 @@
}
},
"400": {
- "description": "Product has no image — a product card requires one."
+ "description": "Product has no image (a product card requires one), a plugin blocked the send, or a plugin returned an invalid productId or body."
},
"404": {
"description": "Product id not found in the session catalog."
diff --git a/src/core/hooks/sending-gate.ts b/src/core/hooks/sending-gate.ts
index 4b7519316..b6b6639b7 100644
--- a/src/core/hooks/sending-gate.ts
+++ b/src/core/hooks/sending-gate.ts
@@ -11,7 +11,8 @@ const logger = createLogger('SendingGate');
* Lives here rather than on a service so callers in different modules share one implementation.
* A second copy of a moderation chokepoint is a chokepoint that will eventually disagree with itself.
*
- * Current callers: `MessageService` (all senders + edit) and `StatusService` (the three posts).
+ * Current callers: `MessageService` (all senders + edit), `StatusService` (the three posts) and
+ * `CatalogService` (`sendProduct`, which ignores a rewritten `chatId` as bulk does).
* `BulkMessageService` still runs its own inlined copy — it has to flag a plugin block separately
* from a delivery failure so the per-item `message:failed` hook is skipped, which this signature
* cannot express. If you change the gate's semantics here, change it there too
diff --git a/src/modules/catalog/catalog.controller.ts b/src/modules/catalog/catalog.controller.ts
index be9aa98d4..f4d0dbbdc 100644
--- a/src/modules/catalog/catalog.controller.ts
+++ b/src/modules/catalog/catalog.controller.ts
@@ -75,7 +75,11 @@ export class CatalogController {
@ApiOperation({ summary: 'Send a product message (Baileys engine only)' })
@ApiResponse({ status: 201, description: 'Product message accepted for sending', type: ProductMessageResponseDto })
@ApiResponse({ status: 404, description: 'Product id not found in the session catalog.' })
- @ApiResponse({ status: 400, description: 'Product has no image — a product card requires one.' })
+ @ApiResponse({
+ status: 400,
+ description:
+ 'Product has no image (a product card requires one), a plugin blocked the send, or a plugin returned an invalid productId or body.',
+ })
@ApiResponse({
status: 501,
description: 'Not supported by the active engine: whatsapp-web.js cannot send product messages.',
diff --git a/src/modules/catalog/catalog.service.spec.ts b/src/modules/catalog/catalog.service.spec.ts
index ef3b006c5..bdac61b97 100644
--- a/src/modules/catalog/catalog.service.spec.ts
+++ b/src/modules/catalog/catalog.service.spec.ts
@@ -1,9 +1,10 @@
-import { NotFoundException, NotImplementedException } from '@nestjs/common';
+import { BadRequestException, HttpException, NotFoundException, NotImplementedException } from '@nestjs/common';
import { CatalogService } from './catalog.service';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
import type { SendPacingService } from '../message/send-pacing.service';
+import type { HookManager } from '../../core/hooks';
import type {
IWhatsAppEngine,
Catalog,
@@ -25,8 +26,17 @@ const product: Product = {
const page: PaginatedProducts = { products: [product], pagination: { page: 1, limit: 20, total: 1, totalPages: 1 } };
const sent: MessageResult = { id: 'wamid.product', timestamp: 1_706_868_000 };
+/** No plugin registered: HookManager hands the envelope back unchanged. */
+const passThroughHooks = () => ({
+ execute: jest.fn((_event: string, data: unknown) => Promise.resolve({ continue: true, data })),
+});
+
describe('CatalogService', () => {
- const makeService = (engine: Partial<IWhatsAppEngine> | undefined, pacing?: { assertSendAllowed: jest.Mock }) => {
+ const makeService = (
+ engine: Partial<IWhatsAppEngine> | undefined,
+ pacing?: { assertSendAllowed: jest.Mock },
+ hookManager = passThroughHooks(),
+ ) => {
const engines = new EngineRegistry();
if (engine) engines.set('s1', engine as IWhatsAppEngine);
const sendPacing = {
@@ -35,7 +45,15 @@ describe('CatalogService', () => {
recordSendFailure: jest.fn(),
...pacing,
};
- return { svc: new CatalogService(engines, sendPacing as unknown as SendPacingService), pacing: sendPacing };
+ return {
+ svc: new CatalogService(
+ engines,
+ sendPacing as unknown as SendPacingService,
+ hookManager as unknown as HookManager,
+ ),
+ pacing: sendPacing,
+ hookManager,
+ };
};
describe('catalog reads', () => {
@@ -89,17 +107,10 @@ describe('CatalogService', () => {
});
describe('product-message sends', () => {
- it.each(['sendProduct', 'sendCatalog'] as const)(
- 'rejects with 404 for %s when the session is not started',
- async method => {
- const { svc } = makeService(undefined);
- const promise =
- method === 'sendProduct'
- ? svc.sendProduct('s1', '[email protected]', 'prod-1')
- : svc.sendCatalog('s1', '[email protected]');
- await expect(promise).rejects.toBeInstanceOf(NotFoundException);
- },
- );
+ it('rejects with 404 for sendProduct when the session is not started', async () => {
+ const { svc } = makeService(undefined);
+ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1')).rejects.toBeInstanceOf(NotFoundException);
+ });
it('paces a product send BEFORE it reaches the engine', async () => {
const order: string[] = [];
@@ -121,19 +132,64 @@ describe('CatalogService', () => {
expect(sendProduct).toHaveBeenCalledWith('[email protected]', 'prod-1', 'Back in stock!');
});
- // No engine can send a catalog link today — the route stays live (and paced) so the day one
- // gains support the send is not unpaced, but until then the adapter's 501 must reach the
- // caller unchanged. Pin the refusal; do not "fix" it into a success.
- it('sendCatalog surfaces the engine’s deliberate 501 unchanged', async () => {
- const pacing = { assertSendAllowed: jest.fn().mockResolvedValue(undefined) };
- const unsupported = new EngineNotSupportedError('sendCatalog');
- const sendCatalog = jest.fn().mockRejectedValue(unsupported);
- const { svc } = makeService({ sendCatalog }, pacing);
-
- await expect(svc.sendCatalog('s1', '[email protected]', 'Browse our catalog')).rejects.toBe(unsupported);
- expect(unsupported.getStatus()).toBe(501);
- expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1', '[email protected]');
- expect(sendCatalog).toHaveBeenCalledWith('[email protected]', 'Browse our catalog');
+ // A product card is a chat send like any other, so a moderation plugin that polices every chat
+ // send must be able to stop it too.
+ it('offers the product send to message:sending and sends nothing when a plugin vetoes it', async () => {
+ const hookManager = { execute: jest.fn().mockResolvedValue({ continue: false }) };
+ const sendProduct = jest.fn().mockResolvedValue(sent);
+ const { svc, pacing } = makeService({ sendProduct }, undefined, hookManager);
+
+ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1', 'Back in stock!')).rejects.toBeInstanceOf(
+ BadRequestException,
+ );
+ expect(hookManager.execute).toHaveBeenCalledWith(
+ 'message:sending',
+ {
+ sessionId: 's1',
+ type: 'product',
+ input: { chatId: '[email protected]', productId: 'prod-1', body: 'Back in stock!' },
+ },
+ { sessionId: 's1', source: 'CatalogService' },
+ );
+ expect(sendProduct).not.toHaveBeenCalled();
+ expect(pacing.recordSendFailure).not.toHaveBeenCalled();
+ });
+
+ it('sends the gated productId and body, but always to the requested chat', async () => {
+ const hookManager = {
+ execute: jest.fn().mockResolvedValue({
+ continue: true,
+ data: { input: { chatId: '[email protected]', productId: 'prod-2', body: 'Rewritten' } },
+ }),
+ };
+ const sendProduct = jest.fn().mockResolvedValue(sent);
+ const { svc } = makeService({ sendProduct }, undefined, hookManager);
+
+ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1', 'Back in stock!')).resolves.toBe(sent);
+ expect(sendProduct).toHaveBeenCalledWith('[email protected]', 'prod-2', 'Rewritten');
+ });
+
+ it.each([
+ ['a non-string productId', { productId: 42 }],
+ ['an empty productId', { productId: '' }],
+ ['a non-string body', { productId: 'prod-1', body: { text: 'x' } }],
+ ])('refuses with 400 when a plugin returns %s', async (_label, input) => {
+ const hookManager = { execute: jest.fn().mockResolvedValue({ continue: true, data: { input } }) };
+ const sendProduct = jest.fn().mockResolvedValue(sent);
+ const { svc } = makeService({ sendProduct }, undefined, hookManager);
+
+ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1')).rejects.toBeInstanceOf(BadRequestException);
+ expect(sendProduct).not.toHaveBeenCalled();
+ });
+
+ it('refuses on pacing before the plugin gate is consulted', async () => {
+ const pacing = { assertSendAllowed: jest.fn().mockRejectedValue(new HttpException('paced', 429)) };
+ const sendProduct = jest.fn();
+ const { svc, hookManager } = makeService({ sendProduct }, pacing);
+
+ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1')).rejects.toMatchObject({ status: 429 });
+ expect(hookManager.execute).not.toHaveBeenCalled();
+ expect(sendProduct).not.toHaveBeenCalled();
});
it('propagates an engine failure from sendProduct', async () => {
@@ -155,11 +211,13 @@ describe('CatalogService', () => {
});
it('does not feed a client-fault or unsupported refusal to the breaker', async () => {
- const sendProduct = jest.fn().mockRejectedValue(new NotFoundException('Product not found'));
- const sendCatalog = jest.fn().mockRejectedValue(new EngineNotSupportedError('sendCatalog'));
- const { svc, pacing } = makeService({ sendProduct, sendCatalog });
+ const sendProduct = jest
+ .fn()
+ .mockRejectedValueOnce(new NotFoundException('Product not found'))
+ .mockRejectedValueOnce(new EngineNotSupportedError('sendProduct'));
+ const { svc, pacing } = makeService({ sendProduct });
await expect(svc.sendProduct('s1', '[email protected]', 'prod-404')).rejects.toBeInstanceOf(NotFoundException);
- await expect(svc.sendCatalog('s1', '[email protected]')).rejects.toBeInstanceOf(EngineNotSupportedError);
+ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1')).rejects.toBeInstanceOf(EngineNotSupportedError);
expect(pacing.recordSendFailure).not.toHaveBeenCalled();
});
});
diff --git a/src/modules/catalog/catalog.service.ts b/src/modules/catalog/catalog.service.ts
index 2dac77296..27a5168cf 100644
--- a/src/modules/catalog/catalog.service.ts
+++ b/src/modules/catalog/catalog.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, NotFoundException } from '@nestjs/common';
+import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { EngineRegistry } from '../../engine/engine-registry.service';
import type {
Catalog,
@@ -7,12 +7,15 @@ import type {
MessageResult,
} from '../../engine/interfaces/whatsapp-engine.interface';
import { SendPacingService, countsTowardSendBreaker } from '../message/send-pacing.service';
+import { HookManager, applySendingGate } from '../../core/hooks';
@Injectable()
export class CatalogService {
+ // HookManager comes from the @Global() HooksModule, so no module import is needed.
constructor(
private readonly engines: EngineRegistry,
private readonly pacing: SendPacingService,
+ private readonly hookManager: HookManager,
) {}
async getCatalog(sessionId: string): Promise<Catalog | null> {
@@ -40,32 +43,37 @@ export class CatalogService {
}
/**
- * Sending a product is a real outbound chat message, not a catalog read, so it is paced like every
- * other send. It does NOT go through MessageService, which is why the pacing call has to be here:
- * this path persists no row and fires no message hooks either — deliberately out of scope for this
- * change, but worth knowing when reading the counts.
+ * Sending a product is a real outbound chat message, not a catalog read. It does NOT go through
+ * MessageService, so this method runs the two pre-send steps every chat send gets: pacing, then the
+ * `message:sending` plugin gate (input `{ chatId, productId, body }`, type `product`). A plugin may
+ * rewrite `productId` or `body`; a rewritten `chatId` is ignored, because `chatId` is the value the
+ * API key's chat scope was checked against. No PENDING row is written up front. On Baileys the
+ * own-send echo (MessageProjector.handleOwnSendEcho) persists the OUTGOING row afterwards and fires
+ * `message:sent` and `message:persisted`, so the send is counted into the pacing daily cap once
+ * that row lands.
*/
async sendProduct(sessionId: string, chatId: string, productId: string, body?: string): Promise<MessageResult> {
await this.pacing.assertSendAllowed(sessionId, chatId);
- const engine = this.engines.require(
+ const gated = await applySendingGate(
+ this.hookManager,
sessionId,
- () => new NotFoundException(`Session ${sessionId} not found or not connected`),
+ 'product',
+ { chatId, productId, body },
+ 'CatalogService',
);
- return this.recordedSend(sessionId, () => engine.sendProduct(chatId, productId, body));
- }
-
- /**
- * Paced for the same reason as sendProduct. Both engines answer 501 today, so the adapter refuses
- * before any traffic leaves — but the route is live, and pacing it now means the day an engine
- * gains support does not silently open an unpaced send path.
- */
- async sendCatalog(sessionId: string, chatId: string, body?: string): Promise<MessageResult> {
- await this.pacing.assertSendAllowed(sessionId, chatId);
+ const gatedProductId: unknown = gated.productId;
+ const gatedBody: unknown = gated.body;
+ if (typeof gatedProductId !== 'string' || gatedProductId === '') {
+ throw new BadRequestException('A message:sending handler returned an invalid productId');
+ }
+ if (gatedBody !== undefined && typeof gatedBody !== 'string') {
+ throw new BadRequestException('A message:sending handler returned an invalid body');
+ }
const engine = this.engines.require(
sessionId,
() => new NotFoundException(`Session ${sessionId} not found or not connected`),
);
- return this.recordedSend(sessionId, () => engine.sendCatalog(chatId, body));
+ return this.recordedSend(sessionId, () => engine.sendProduct(chatId, gatedProductId, gatedBody));
}
/**
diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.ts
index 4d2957307..a36ea2a82 100644
--- a/src/modules/message/send-pacing.service.spec.ts
+++ b/src/modules/message/send-pacing.service.spec.ts
@@ -345,16 +345,16 @@ describe('send paths consult the governor', () => {
// This path does NOT go through MessageService, which is exactly why it needs its own call —
// sending a product is a real outbound chat message, not a catalog read.
it('CatalogService.sendProduct refuses before the engine is asked', async () => {
- const engine = { sendProduct: jest.fn(), sendCatalog: jest.fn() };
+ const hookManager = { execute: jest.fn() };
+ const engine = { sendProduct: jest.fn() };
const pacing = refusing();
- const service = new CatalogService({ require: () => engine } as never, pacing as never);
+ const service = new CatalogService({ require: () => engine } as never, pacing as never, hookManager as never);
await expect(service.sendProduct('s1', '[email protected]', 'p1')).rejects.toBeInstanceOf(HttpException);
- await expect(service.sendCatalog('s1', '[email protected]')).rejects.toBeInstanceOf(HttpException);
- expect(pacing.assertSendAllowed).toHaveBeenCalledTimes(2);
+ expect(pacing.assertSendAllowed).toHaveBeenCalledWith('s1', '[email protected]');
+ expect(hookManager.execute).not.toHaveBeenCalled();
expect(engine.sendProduct).not.toHaveBeenCalled();
- expect(engine.sendCatalog).not.toHaveBeenCalled();
});
// Group participant adds reach WhatsApp with no moderation gate of any kind, so the governor is