Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(api): keep reading a number in a string field as text
Yudhi Armyndharis239e45b9b4fb
diff --git a/src/common/utils/dto-strict-coercion.spec.ts b/src/common/utils/dto-strict-coercion.spec.tsindex 2b34fa717..1cd8b77ad 100644--- a/src/common/utils/dto-strict-coercion.spec.ts+++ b/src/common/utils/dto-strict-coercion.spec.ts@@ -17,8 +17,9 @@ import { join } from 'path';* `true` and `@IsBoolean()` can never reject them.* Number — `Number('')` and `Number(' ')` are `0`, so a blank field arrives as a real zero* and `@IsInt()`/`@IsNumber()` accept it.- * String - a number, boolean or object becomes its string form (`5`, `true`, `[object Object]`), so- * `@IsString()` accepts it and the route sends text the caller never wrote.+ * String - a boolean or object becomes its string form (`true`, `[object Object]`), so `@IsString()`+ * accepts it and the route sends text the caller never wrote. A number keeps the conversion,+ * because clients that hold a phone number as a number rely on it.** The first two fail toward the more permissive value, which is how a `forEveryone=false` delete became* a delete-for-everyone. `ToStrictBoolean`/`ToStrictNumber`/`ToStrictString` (`./strict-boolean`)@@ -37,11 +38,12 @@ const PIPE_VALIDATOR_OPTS = { whitelist: true, forbidNonWhitelisted: true };const PROBES: Record<string, { values: unknown[]; reason: string }> = {Boolean: { values: ['yes'], reason: 'implicit conversion turns any non-empty string into true' },Number: { values: [''], reason: 'Number("") is 0, so a blank field becomes a real zero' },- // Three probes, because their string forms differ: "628123456789" and "true" pass a digit pattern or a- // name rule that "[object Object]" fails, so one probe alone would let such a field skip the decorator.+ // Two string forms, because they differ: "true" passes a name rule that "[object Object]" fails, so one+ // probe alone would let such a field skip the decorator. An array is never converted, so it pins that it+ // stays refused. A number is not here: it is converted on purpose, and asserted separately below.String: {- values: [628123456789, true, { order: 42 }],- reason: 'implicit conversion rewrites a number, boolean or object into its string form, which @IsString accepts',+ values: [true, { order: 42 }, ['a']],+ reason: 'implicit conversion rewrites a boolean or an object into its string form, which @IsString accepts',},};@@ -126,6 +128,17 @@ describe('DTO input-coercion drift gate', () => {).toBe(true);},);++ // Clients that hold a phone number or a chat id as a number post it as one, and every release has read it+ // as its decimal string. The value reaching the validators is checked, not the verdict: a pattern such as+ // a chat id's legitimately refuses the digits, which is not the conversion going missing.+ it.each(targets.filter(t => t.type === 'String').map(t => [`${t.cls.name}.${t.prop}`, t] as const))(+ '%s still reads a number as its decimal string',+ (_label, target) => {+ const instance = plainToInstance(target.cls, { [target.prop]: 628123456789 }, PIPE_TRANSFORM_OPTS);+ expect((instance as Record<string, unknown>)[target.prop]).toBe('628123456789');+ },+ );});/**diff --git a/src/common/utils/strict-boolean.spec.ts b/src/common/utils/strict-boolean.spec.tsindex 37ca1886c..a312c32b5 100644--- a/src/common/utils/strict-boolean.spec.ts+++ b/src/common/utils/strict-boolean.spec.ts@@ -144,14 +144,32 @@ describe('ToStrictString', () => {}});- it.each([[628123456789], [true], [false], [0], [{ order: 42 }], [['a']]])(- 'rejects %j instead of reading it as text',- async value => {- const { instance, errors } = await run(StringSubject, { text: value });- expect(instance.text).toEqual(value);- expect(errors.map(e => e.property)).toEqual(['text']);- },- );+ // A number keeps the conversion every release has had: no-code clients post a phone number held as a number.+ it.each([+ [628123456789, '628123456789'],+ [0, '0'],+ [-5, '-5'],+ [1.5, '1.5'],+ [1e21, '1e+21'],+ ])('reads the number %j as the string %j, as the pipe always did', async (value, expected) => {+ const { instance, errors } = await run(StringSubject, { text: value });+ expect(instance.text).toBe(expected);+ expect(errors).toHaveLength(0);+ });++ it('converts a number exactly as the unguarded pipe does', async () => {+ for (const value of [628123456789, 0, -0, -5, 1.5, 1e21, Number.MAX_SAFE_INTEGER]) {+ const guarded = await run(StringSubject, { text: value });+ const unguarded = await run(UnguardedString, { text: value });+ expect(guarded.instance.text).toBe(unguarded.instance.text);+ }+ });++ it.each([[true], [false], [{ order: 42 }], [['a']]])('rejects %j instead of reading it as text', async value => {+ const { instance, errors } = await run(StringSubject, { text: value });+ expect(instance.text).toEqual(value);+ expect(errors.map(e => e.property)).toEqual(['text']);+ });it('leaves an absent property absent and a null one null', async () => {const absent = await run(StringSubject, {});@@ -163,9 +181,8 @@ describe('ToStrictString', () => {});// The behaviour the decorator exists to prevent: the customer receiving the literal "[object Object]".- it('documents the unguarded behaviour it replaces: a number, boolean or object becomes a string', async () => {+ it('documents the unguarded behaviour it replaces: a boolean or object becomes a string', async () => {for (const [value, expected] of [- [628123456789, '628123456789'],[true, 'true'],[{ order: 42 }, '[object Object]'],] as const) {diff --git a/src/common/utils/strict-boolean.ts b/src/common/utils/strict-boolean.tsindex 1b0b66790..5035d8192 100644--- a/src/common/utils/strict-boolean.ts+++ b/src/common/utils/strict-boolean.ts@@ -58,17 +58,19 @@ export const ToStrictNumber = (): PropertyDecorator => Transform(coerceStrictNum/*** The string counterpart, for the same reason and with the same `obj[key]` trick.*- * Implicit conversion applies `String(value)` to a `string`-typed property, so a number, a boolean or- * an object is rewritten into its string form (`5`, `true`, `[object Object]`) before `@IsString()` runs,- * and the route accepts it. An integration whose expression yields an object then sent the customer- * the literal text `[object Object]`. An array is the one value left alone, so the same field already- * answered 400 for it.+ * Implicit conversion applies `String(value)` to a `string`-typed property, so a boolean or an object is+ * rewritten into its string form (`true`, `[object Object]`) before `@IsString()` runs, and the route+ * accepts it. An integration whose expression yields an object then sent the customer the literal text+ * `[object Object]`. An array is the one value left alone, so the same field already answered 400 for it.*- * The caller's value is kept as it is, so `@IsString()` and the other string validators refuse anything- * that is not already a string. A string is never altered, so a form-encoded body is unaffected.+ * A number keeps the conversion: clients that hold a phone number or a chat id as a number post it as one,+ * and every release has read it as its decimal string. Every other value is kept as the caller sent it,+ * so `@IsString()` and the other string validators refuse it. A string is never altered, so a+ * form-encoded body is unaffected.*/export function coerceStrictString({ obj, key }: Pick<TransformFnParams, 'obj' | 'key'>): unknown {- return (obj as Record<string, unknown> | undefined)?.[key];+ const raw = (obj as Record<string, unknown> | undefined)?.[key];+ return typeof raw === 'number' ? String(raw) : raw;}/** Property decorator form of {@link coerceStrictString}. Pair it with `@IsString()`. */diff --git a/src/modules/message/dto/bulk-message.dto.spec.ts b/src/modules/message/dto/bulk-message.dto.spec.tsindex 0b0173f73..4c0c19605 100644--- a/src/modules/message/dto/bulk-message.dto.spec.ts+++ b/src/modules/message/dto/bulk-message.dto.spec.ts@@ -28,10 +28,17 @@ describe('SendBulkMessageDto nested media validation', () => {await rejects(imageItem({ base64: 'AAAA', evil: 'x' }));});- // A number is not text: implicit conversion used to rewrite it into its string form before @IsString- // ran, so the service decoded '12345' as base64 instead of the request being refused.- it('refuses a numeric base64 inside a media object', async () => {- await rejects(imageItem({ base64: 12345 }));+ // Implicit conversion turns a number into its string form before @IsString runs, so the service+ // receives a string either way.+ it('converts a numeric base64 inside a media object to a string', async () => {+ const dto = await validateBulk(imageItem({ base64: 12345 }));+ expect(dto.messages[0].content.image?.base64).toBe('12345');+ });++ it.each([[true], [{ a: 1 }]])('refuses %j where a media string belongs', async value => {+ await rejects(imageItem({ base64: value }));+ await rejects(imageItem({ url: value }));+ await rejects(imageItem({ base64: 'AAAA', mimetype: value }));});});@@ -67,9 +74,15 @@ describe('SendBulkMessageDto media url', () => {await accepts(imageItem({ url: 'https://{{host}}/a.jpg' }));});- // Refused like any other non-string field, even next to base64 (which wins when the item is sent).- it('refuses a numeric url next to base64', async () => {- await rejects(imageItem({ base64: 'AAAA', url: 123 }));+ // Converted like any string field; the per-item check then refuses '123' as not an http(s) URL.+ it('converts a numeric url next to base64 to a string', async () => {+ const dto = await validateBulk(imageItem({ base64: 'AAAA', url: 123 }));+ expect(dto.messages[0].content.image?.url).toBe('123');+ });++ // A boolean or an object is refused even next to base64, which wins when the item is sent.+ it.each([[true], [{ a: 1 }]])('refuses %j as the url next to base64', async value => {+ await rejects(imageItem({ base64: 'AAAA', url: value }));});});diff --git a/src/modules/message/dto/send-message.dto.spec.ts b/src/modules/message/dto/send-message.dto.spec.tsindex 02176aaf5..ad51460bd 100644--- a/src/modules/message/dto/send-message.dto.spec.ts+++ b/src/modules/message/dto/send-message.dto.spec.ts@@ -315,11 +315,12 @@ describe('SendTextMessageDto customLinkPreview', () => {});});-// Implicit conversion rewrote a number, a boolean or an object into its string form before @IsString ran, so-// {"text":{"order":42}} was sent as the literal text "[object Object]". Every field below is documented as a-// string, in docs/06 and in the request types of all five SDKs.-describe('string fields refuse a value that is not a string', () => {- const invalid: Array<[unknown]> = [[{ order: 42 }], [628123456789], [true]];+// Implicit conversion rewrote a boolean or an object into its string form before @IsString ran, so+// {"text":{"order":42}} was sent as the literal text "[object Object]". A number keeps the conversion: no-code+// clients post a phone number or a chat id held as a number, and every release has read it as its decimal+// string. Every field below is documented as a string, in docs/06 and in the request types of all five SDKs.+describe('string fields refuse a boolean or an object', () => {+ const invalid: Array<[unknown]> = [[{ order: 42 }], [true], [['a']]];it.each(invalid)('SendTextMessageDto refuses text %j', async text => {const errors = await validateDto(SendTextMessageDto, { chatId: '[email protected]', text });@@ -345,6 +346,18 @@ describe('string fields refuse a value that is not a string', () => {expect(errors.map(e => e.property)).toEqual(['contactNumber']);});+ it('still reads a number as its decimal string', async () => {+ const contact = plainToInstance(+ SendContactDto,+ { chatId: '[email protected]', contactName: 'Alice', contactNumber: 628999888777 },+ GLOBAL_VALIDATION_OPTIONS.transformOptions,+ );+ expect(contact.contactNumber).toBe('628999888777');+ expect(await validate(contact, GLOBAL_VALIDATION_OPTIONS)).toHaveLength(0);++ expect(await validateDto(SendTextMessageDto, { chatId: 628123456789, text: 5 })).toHaveLength(0);+ });+it('still takes the same values spelled as strings', async () => {expect(await validateDto(SendTextMessageDto, { chatId: '[email protected]', text: '{"order":42}' })).toHaveLength(0);expect(await validateDto(SendTextMessageDto, { chatId: '[email protected]', text: '628123456789' })).toHaveLength(0);diff --git a/test/message-send.e2e-spec.ts b/test/message-send.e2e-spec.tsindex 7aaedf0ca..be3e97bd2 100644--- a/test/message-send.e2e-spec.ts+++ b/test/message-send.e2e-spec.ts@@ -129,14 +129,22 @@ describe('Message send endpoints (e2e)', () => {});// Implicit conversion used to rewrite these into their string forms, so the engine was called with- // '[object Object]', 'true' or '5' and the customer received that as the message.- it.each([[{ order: 42 }], [true], [5]])('send-text refuses a text of %j and never reaches the engine', async text => {+ // '[object Object]' or 'true' and the customer received that as the message.+ it.each([[{ order: 42 }], [true]])('send-text refuses a text of %j and never reaches the engine', async text => {await post('send-text', { chatId: '[email protected]', text }).expect(400);await post('send-text', { chatId: text, text: 'hello' }).expect(400);expect(engine.sendTextMessage).not.toHaveBeenCalled();});+ // A number keeps the conversion every release has had: no-code clients post a value held as a number,+ // and the engine receives its decimal string.+ it('send-text still reads a numeric text as its decimal string', async () => {+ await post('send-text', { chatId: '[email protected]', text: 5 }).expect(201);++ expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', '5');+ });+it('send-image returns 201 and hands the base64 payload to the engine', async () => {const base64 = Buffer.from('GIF89a').toString('base64');const res = await post('send-image', {