Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(session): pin the validators of the chat action bodies
Yudhi Armyndharis88f608e20e34
diff --git a/src/modules/session/dto/chat-id-bound.dto.spec.ts b/src/modules/session/dto/chat-id-bound.dto.spec.tsindex b2ba01899..b1560f17b 100644--- a/src/modules/session/dto/chat-id-bound.dto.spec.ts+++ b/src/modules/session/dto/chat-id-bound.dto.spec.ts@@ -1,6 +1,7 @@import 'reflect-metadata';import { plainToInstance } from 'class-transformer';import { validate } from 'class-validator';+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';import { SendProductDto } from '../../catalog/dto/send-product.dto';import { ArchiveChatDto } from './archive-chat.dto';import { DeleteChatDto } from './delete-chat.dto';@@ -38,3 +39,42 @@ describe('chatId is bounded at 255 characters on the chat action bodies', () =>expect(await constraintsOf(exact)).not.toContain('maxLength');});});++// docs/06 states one structural rule for the chat id of a chat action: localpart@host with no whitespace.+// It is engine-neutral on purpose (@c.us, @s.whatsapp.net, @g.us and @lid all pass), so it only turns away+// ids that cannot name a chat on any engine. Dropping it from one body lets that garbage reach the engine.+describe('chatId must be localpart@host on the chat action bodies', () => {+ const accepted = ['[email protected]', '[email protected]', '[email protected]', '1234567890@lid'];+ const rejected = [+ ['no host separator', '628123456789'],+ ['no local part', '@c.us'],+ ['no host', '628123456789@'],+ ['two separators', '628123456789@@c.us'],+ ['whitespace in the local part', '6281 [email protected]'],+ ['whitespace in the host', '628123456789@c .us'],+ ['leading whitespace', ' [email protected]'],+ ['trailing newline', '[email protected]\n'],+ ];++ it.each([+ ['ArchiveChatDto', ArchiveChatDto, { archive: true }],+ ['DeleteChatDto', DeleteChatDto, {}],+ ['MarkChatReadDto', MarkChatReadDto, {}],+ ['MarkChatUnreadDto', MarkChatUnreadDto, {}],+ ['MuteChatDto', MuteChatDto, { muteUntil: 1_800_000_000_000 }],+ ['PinChatDto', PinChatDto, { pin: true }],+ ['SubscribePresenceDto', SubscribePresenceDto, {}],+ ] as const)('%s', async (_name, Dto, rest) => {+ const constraintsOf = async (chatId: string): Promise<string[]> => {+ const errors = await validate(+ plainToInstance(Dto as new () => object, { ...rest, chatId }, GLOBAL_VALIDATION_OPTIONS.transformOptions),+ GLOBAL_VALIDATION_OPTIONS,+ );+ return errors.filter(e => e.property === 'chatId').flatMap(e => Object.keys(e.constraints ?? {}));+ };+ for (const chatId of accepted)+ expect({ chatId, failing: await constraintsOf(chatId) }).toEqual({ chatId, failing: [] });+ for (const [why, chatId] of rejected)+ expect({ why, chatId, failing: await constraintsOf(chatId) }).toEqual({ why, chatId, failing: ['matches'] });+ });+});diff --git a/src/modules/session/dto/mute-chat.dto.spec.ts b/src/modules/session/dto/mute-chat.dto.spec.tsindex 154bc5f61..732c19855 100644--- a/src/modules/session/dto/mute-chat.dto.spec.ts+++ b/src/modules/session/dto/mute-chat.dto.spec.ts@@ -2,8 +2,49 @@ import 'reflect-metadata';import { DECORATORS } from '@nestjs/swagger';import { plainToInstance } from 'class-transformer';import { validate } from 'class-validator';+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';import { MuteChatDto } from './mute-chat.dto';+// A mute expiry that is not a positive integer is an instant in the past, so the mute would expire as it+// is set while the request still answered 200 (see the DTO). `null` is the unmute instruction and skips+// the numeric checks; a missing field is not null and must still be refused.+describe('MuteChatDto muteUntil validation', () => {+ const failing = async (body: object): Promise<string[]> =>+ (+ await validate(+ plainToInstance(+ MuteChatDto,+ { chatId: '[email protected]', ...body },+ GLOBAL_VALIDATION_OPTIONS.transformOptions,+ ),+ GLOBAL_VALIDATION_OPTIONS,+ )+ ).map(error => error.property);++ it.each([+ ['the smallest positive integer', 1],+ ['an epoch-millisecond expiry', 1_800_000_000_000],+ ['null, which unmutes', null],+ ])('accepts %s', async (_label, muteUntil) => {+ expect(await failing({ muteUntil })).toEqual([]);+ });++ it.each([+ ['zero', 0],+ ['a negative number', -1],+ ['a fraction', 1.5],+ ['a numeric string', '1'],+ ['an empty string', ''],+ ['a boolean', true],+ ])('rejects %s', async (_label, muteUntil) => {+ expect(await failing({ muteUntil })).toEqual(['muteUntil']);+ });++ it('rejects a missing muteUntil rather than guessing between unmute and mute forever', async () => {+ expect(await failing({})).toEqual(['muteUntil']);+ });+});+describe('MuteChatDto published schema', () => {// @nestjs/swagger derives nothing from @IsInt/@Min/@Max, so the decorator has to state all of them.it('publishes muteUntil as a nullable integer between 1 and the largest safe integer', () => {diff --git a/src/modules/session/dto/send-chat-state.dto.spec.ts b/src/modules/session/dto/send-chat-state.dto.spec.tsnew file mode 100644index 000000000..bd31c1c14--- /dev/null+++ b/src/modules/session/dto/send-chat-state.dto.spec.ts@@ -0,0 +1,47 @@+import { plainToInstance } from 'class-transformer';+import { validate } from 'class-validator';+import { GLOBAL_VALIDATION_OPTIONS } from '../../../config/app-validation';+import { SendChatStateDto } from './send-chat-state.dto';++// The indicator the typing route sends is one of the three ChatState words. Anything else, `composing`+// (the word a presence report uses) included, would reach the engines as a state they do not know.+describe('SendChatStateDto state', () => {+ const failing = async (body: object): Promise<string[]> =>+ (+ await validate(+ plainToInstance(+ SendChatStateDto,+ { chatId: '[email protected]', ...body },+ GLOBAL_VALIDATION_OPTIONS.transformOptions,+ ),+ GLOBAL_VALIDATION_OPTIONS,+ )+ ).map(error => error.property);++ it.each(['typing', 'recording', 'paused'])('accepts %s', async state => {+ expect(await failing({ state })).toEqual([]);+ });++ it.each([+ ['composing', 'composing'],+ ['available', 'available'],+ ['a different case', 'TYPING'],+ ['an empty string', ''],+ ['a number', 1],+ ['null', null],+ ])('rejects %s', async (_label, state) => {+ expect(await failing({ state })).toEqual(['state']);+ });++ it('rejects a missing state', async () => {+ expect(await failing({})).toEqual(['state']);+ });++ it('rejects a missing chatId', async () => {+ const errors = await validate(+ plainToInstance(SendChatStateDto, { state: 'typing' }, GLOBAL_VALIDATION_OPTIONS.transformOptions),+ GLOBAL_VALIDATION_OPTIONS,+ );+ expect(errors.map(error => error.property)).toEqual(['chatId']);+ });+});