Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(catalog): accept a null product body and bound its fields

Yudhi Armyndharis49e09469a2c5
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index b2749e456..3c0a1e552 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -3666,11 +3666,11 @@ Send a product message (catalog product card) to a chat. Note: this route lives
**Request body** — `SendProductDto`
-| Field | Type | Required | Constraints | Description |
-| ----------- | ------ | -------- | ----------- | ----------------------------------------------------- |
-| `chatId` | string | Yes | `@IsString` | Target chat/recipient id (e.g. `[email protected]`). |
-| `productId` | string | Yes | `@IsString` | Catalog product id to send. |
-| `body` | string | No | `@IsString` | Optional message body/caption. |
+| Field | Type | Required | Constraints | Description |
+| ----------- | ------ | -------- | --------------------------------------- | ----------------------------------------------------------------- |
+| `chatId` | string | Yes | `@IsString @IsNotEmpty` | Target chat/recipient id (e.g. `[email protected]`). |
+| `productId` | string | Yes | `@IsString @IsNotEmpty @MaxLength(255)` | Catalog product id to send. |
+| `body` | string | No | `@IsString @MaxLength(4096)` | Optional message body/caption; `null` is the same as omitting it. |
```json
{
@@ -3682,7 +3682,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, 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)
+**Errors:** `400` missing or empty `chatId`/`productId`, a `productId` over 255 or a `body` over 4096 characters, 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/src/modules/catalog/catalog.service.spec.ts b/src/modules/catalog/catalog.service.spec.ts
index bdac61b97..81c52d865 100644
--- a/src/modules/catalog/catalog.service.spec.ts
+++ b/src/modules/catalog/catalog.service.spec.ts
@@ -4,7 +4,7 @@ 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 { HookManager } from '../../core/hooks';
import type {
IWhatsAppEngine,
Catalog,
@@ -220,5 +220,16 @@ describe('CatalogService', () => {
await expect(svc.sendProduct('s1', '[email protected]', 'prod-1')).rejects.toBeInstanceOf(EngineNotSupportedError);
expect(pacing.recordSendFailure).not.toHaveBeenCalled();
});
+
+ // A JSON null body passes the DTO (IsOptional) and, with no plugin installed, the gate hands the
+ // caller's own envelope back. It must send like an absent body, not fail as a plugin's bad output.
+ it('sends a null body as no body when no plugin is installed', async () => {
+ const sendProduct = jest.fn().mockResolvedValue(sent);
+ const { svc } = makeService({ sendProduct }, undefined, new HookManager() as never);
+
+ await expect(svc.sendProduct('s1', '[email protected]', 'prod-1', null as unknown as string)).resolves.toBe(sent);
+
+ expect(sendProduct).toHaveBeenCalledWith('[email protected]', 'prod-1', undefined);
+ });
});
});
diff --git a/src/modules/catalog/catalog.service.ts b/src/modules/catalog/catalog.service.ts
index 27a5168cf..9929b0f13 100644
--- a/src/modules/catalog/catalog.service.ts
+++ b/src/modules/catalog/catalog.service.ts
@@ -58,7 +58,9 @@ export class CatalogService {
this.hookManager,
sessionId,
'product',
- { chatId, productId, body },
+ // The DTO lets a JSON null through as "no body". Normalised here, so the checks below only ever
+ // judge what a plugin handed back, never the caller's own input.
+ { chatId, productId, body: body ?? undefined },
'CatalogService',
);
const gatedProductId: unknown = gated.productId;
diff --git a/src/modules/catalog/dto/send-product.dto.spec.ts b/src/modules/catalog/dto/send-product.dto.spec.ts
new file mode 100644
index 000000000..e7281e3e7
--- /dev/null
+++ b/src/modules/catalog/dto/send-product.dto.spec.ts
@@ -0,0 +1,39 @@
+import { plainToInstance } from 'class-transformer';
+import { validate } from 'class-validator';
+import { PRODUCT_ID_MAX_LENGTH, SendProductDto } from './send-product.dto';
+import { MESSAGE_TEXT_MAX_LENGTH } from '../../message/dto/send-message.dto';
+
+/** The constraints that failed, keyed by property; empty when the payload is valid. */
+const failures = async (body: object): Promise<Record<string, string[]>> => {
+ const errors = await validate(plainToInstance(SendProductDto, body, { enableImplicitConversion: true }));
+ return Object.fromEntries(errors.map(e => [e.property, Object.keys(e.constraints ?? {})]));
+};
+
+describe('SendProductDto', () => {
+ const valid = { chatId: '[email protected]', productId: 'prod-1', body: 'Back in stock!' };
+
+ it('accepts a product send with or without a body', async () => {
+ expect(await failures(valid)).toEqual({});
+ expect(await failures({ chatId: valid.chatId, productId: valid.productId })).toEqual({});
+ expect(await failures({ ...valid, body: '' })).toEqual({});
+ });
+
+ it('rejects an empty chatId or productId', async () => {
+ expect(await failures({ ...valid, chatId: '' })).toEqual({ chatId: ['isNotEmpty'] });
+ expect(await failures({ ...valid, productId: '' })).toEqual({ productId: ['isNotEmpty'] });
+ });
+
+ it('caps the productId length', async () => {
+ expect(await failures({ ...valid, productId: 'p'.repeat(PRODUCT_ID_MAX_LENGTH) })).toEqual({});
+ expect(await failures({ ...valid, productId: 'p'.repeat(PRODUCT_ID_MAX_LENGTH + 1) })).toEqual({
+ productId: ['maxLength'],
+ });
+ });
+
+ it('caps the body at the text-message limit', async () => {
+ expect(await failures({ ...valid, body: 'b'.repeat(MESSAGE_TEXT_MAX_LENGTH) })).toEqual({});
+ expect(await failures({ ...valid, body: 'b'.repeat(MESSAGE_TEXT_MAX_LENGTH + 1) })).toEqual({
+ body: ['maxLength'],
+ });
+ });
+});
diff --git a/src/modules/catalog/dto/send-product.dto.ts b/src/modules/catalog/dto/send-product.dto.ts
index 8e6505676..75d9f4037 100644
--- a/src/modules/catalog/dto/send-product.dto.ts
+++ b/src/modules/catalog/dto/send-product.dto.ts
@@ -1,19 +1,31 @@
-import { IsString, IsOptional, IsInt, Min } from 'class-validator';
+import { IsString, IsOptional, IsInt, Min, IsNotEmpty, MaxLength } from 'class-validator';
import { Type } from 'class-transformer';
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { MESSAGE_TEXT_MAX_LENGTH } from '../../message/dto/send-message.dto';
+
+/** WhatsApp catalog product ids are numeric strings of about 16-20 digits; this leaves wide headroom. */
+export const PRODUCT_ID_MAX_LENGTH = 255;
export class SendProductDto {
@ApiProperty({ description: 'Chat to send the product card to (@c.us or @g.us).', example: '[email protected]' })
@IsString()
+ @IsNotEmpty()
chatId!: string;
- @ApiProperty({ description: 'Catalog product id to send.', example: 'product-42' })
+ @ApiProperty({ description: 'Catalog product id to send.', example: 'product-42', maxLength: PRODUCT_ID_MAX_LENGTH })
@IsString()
+ @IsNotEmpty()
+ @MaxLength(PRODUCT_ID_MAX_LENGTH)
productId!: string;
- @ApiPropertyOptional({ description: 'Optional body text accompanying the product card.', example: 'Back in stock!' })
+ @ApiPropertyOptional({
+ description: 'Optional body text accompanying the product card.',
+ example: 'Back in stock!',
+ maxLength: MESSAGE_TEXT_MAX_LENGTH,
+ })
@IsOptional()
@IsString()
+ @MaxLength(MESSAGE_TEXT_MAX_LENGTH)
body?: string;
}