Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): hold single sends the gateway would refuse
Yudhi Armyndharisb59a4e3da7a5
diff --git a/dashboard/src/pages/MessageTester.test.ts b/dashboard/src/pages/MessageTester.test.tsindex 4ce0dd7a6..2c73bd9e8 100644--- a/dashboard/src/pages/MessageTester.test.ts+++ b/dashboard/src/pages/MessageTester.test.ts@@ -144,18 +144,26 @@ function groupJsonResponse(data: unknown, status = 200): Response {return new Response(JSON.stringify(data), { status, headers: { 'Content-Type': 'application/json' } });}-function stubGroupGateway(groups: { id: string; name?: string }[], refuseFirstWith?: number): { textSends: string[] } {+function stubGroupGateway(+ groups: { id: string; name?: string }[],+ refuseFirstWith?: number,+): { textSends: string[]; imageBodies: { chatId: string; url?: string; caption?: string }[] } {const previousFetch = globalThis.fetch;restoreFetch = () => {globalThis.fetch = previousFetch;};const textSends: string[] = [];+ const imageBodies: { chatId: string; url?: string; caption?: string }[] = [];globalThis.fetch = ((input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;if (url.endsWith('/sessions')) {return Promise.resolve(groupJsonResponse([{ id: 's1', name: 'Main', status: 'ready', phone: '15550000000' }]));}if (url.endsWith('/sessions/s1/groups')) return Promise.resolve(groupJsonResponse(groups));+ if (url.endsWith('/messages/send-image')) {+ imageBodies.push(JSON.parse(String(init?.body)) as { chatId: string; url?: string; caption?: string });+ return Promise.resolve(groupJsonResponse({ messageId: 'img1', timestamp: 1 }, 201));+ }if (url.endsWith('/messages/send-text')) {const { chatId } = JSON.parse(String(init?.body)) as { chatId: string };textSends.push(chatId);@@ -166,7 +174,7 @@ function stubGroupGateway(groups: { id: string; name?: string }[], refuseFirstWi}return Promise.resolve(groupJsonResponse([]));}) as typeof fetch;- return { textSends };+ return { textSends, imageBodies };}async function renderGroupsAsWriter(): Promise<void> {@@ -271,6 +279,30 @@ test('an empty message or a media type with no file or URL keeps Send disabled',assert.equal(sendMessageButton().disabled, true);});+test('a group media send holds a URL or caption the gateway would refuse, and sends the URL trimmed', async () => {+ const gateway = stubGroupGateway([{ id: '[email protected]', name: 'Family' }]);+ await renderGroupsAsWriter();+ rtl.fireEvent.click(await rtl.screen.findByRole('checkbox', { name: 'Family' }));+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: 'Image' }));+ const mediaUrl = window.document.getElementById('mt-3')!;+ const caption = window.document.getElementById('mt-14')!;++ // Without a scheme the gateway reads the string as base64 and refuses it, once per group.+ rtl.fireEvent.change(mediaUrl, { target: { value: 'cdn.example.com/a.jpg' } });+ await rtl.screen.findByText('Use a full http:// or https:// address, like https://example.com/file.pdf.');+ assert.equal(sendMessageButton().disabled, true);++ rtl.fireEvent.change(mediaUrl, { target: { value: ' https://cdn.example.com/a.jpg' } });+ rtl.fireEvent.change(caption, { target: { value: 'x'.repeat(1025) } });+ assert.equal(sendMessageButton().disabled, true);+ rtl.fireEvent.change(caption, { target: { value: 'x'.repeat(1024) } });+ await rtl.waitFor(() => assert.equal(sendMessageButton().disabled, false));++ rtl.fireEvent.click(sendMessageButton());+ await rtl.waitFor(() => assert.equal(gateway.imageBodies.length, 1));+ assert.equal(gateway.imageBodies[0].url, 'https://cdn.example.com/a.jpg');+});+test('a session that stops being ready is replaced by what the selector shows', async () => {const status: Record<string, string> = { s1: 'ready', s2: 'ready' };const sends: string[] = [];diff --git a/dashboard/src/pages/MessageTester.tsx b/dashboard/src/pages/MessageTester.tsxindex 9761b1e63..41fd5de99 100644--- a/dashboard/src/pages/MessageTester.tsx+++ b/dashboard/src/pages/MessageTester.tsx@@ -73,6 +73,16 @@ const messageTypes = [// The types that share the media upload/URL block (base64 XOR url + mimetype).const mediaMessageTypes: readonly string[] = ['image', 'video', 'audio', 'document', 'sticker'];+// The gateway's @MaxLength bounds on the single-send bodies. A multi-group send repeats one body per group,+// so a body over any of them would be refused once per group.+const MESSAGE_TEXT_MAX_LENGTH = 4096;+const MEDIA_FILENAME_MAX_LENGTH = 255;+const LOCATION_TEXT_MAX_LENGTH = 1024;+const CONTACT_NAME_MAX_LENGTH = 255;+const CONTACT_NUMBER_MAX_LENGTH = 30;+const POLL_NAME_MAX_LENGTH = 255;+const POLL_OPTION_MAX_LENGTH = 100;+// Hint the native file picker at the right category (documents accept anything).const mediaAccept: Record<(typeof messageTypes)[number], string> = {text: '*/*',@@ -331,8 +341,9 @@ export function MessageTester() {messageType === 'bulk' &&!!mediaFile &&mediaFile.base64.length * bulkRecipientList.length > BULK_INLINE_MEDIA_MAX_BYTES;- const bulkMediaUrlInvalid =- messageType === 'bulk' && !mediaFile && mediaUrl.trim() !== '' && !isHttpMediaUrl(mediaUrl);+ // The gateway reads a media string as a URL only with an http(s) prefix and decodes anything else as+ // base64, so a URL without one is refused (or sent as garbage bytes) for every recipient alike.+ const mediaUrlInvalid = !mediaFile && mediaUrl.trim() !== '' && !isHttpMediaUrl(mediaUrl);// Audio goes out without a caption (the bulk service does not forward one), so text next to an audio// attachment would be dropped while the batch reports success. Refuse it instead of sending half.const bulkAudioWithText = bulkAttachment?.kind === 'audio' && content.trim().length > 0;@@ -343,22 +354,45 @@ export function MessageTester() {// send repeats the request per group, so a body the backend would refuse must not start the run.let formValid = true;if (messageType === 'text') {- formValid = content.trim().length > 0;+ formValid = content.trim().length > 0 && captionLength(content) <= MESSAGE_TEXT_MAX_LENGTH;} else if (isMediaMessageType) {- formValid = !!mediaFile || mediaUrl.trim().length > 0;+ // The text field goes out as the caption on image and video and as the filename on a document.+ const contentMax =+ messageType === 'document'+ ? MEDIA_FILENAME_MAX_LENGTH+ : messageType === 'image' || messageType === 'video'+ ? BULK_CAPTION_MAX_LENGTH+ : Infinity;+ formValid = (!!mediaFile || isHttpMediaUrl(mediaUrl)) && captionLength(content) <= contentMax;} else if (messageType === 'location') {- formValid = !Number.isNaN(lat) && !Number.isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;+ formValid =+ !Number.isNaN(lat) &&+ !Number.isNaN(lng) &&+ lat >= -90 &&+ lat <= 90 &&+ lng >= -180 &&+ lng <= 180 &&+ captionLength(locationDescription.trim()) <= LOCATION_TEXT_MAX_LENGTH &&+ captionLength(locationAddress.trim()) <= LOCATION_TEXT_MAX_LENGTH;} else if (messageType === 'contact') {- formValid = contactName.trim().length > 0 && contactNumber.trim().length > 0;+ formValid =+ contactName.trim().length > 0 &&+ captionLength(contactName.trim()) <= CONTACT_NAME_MAX_LENGTH &&+ contactNumber.trim().length > 0 &&+ captionLength(contactNumber.trim()) <= CONTACT_NUMBER_MAX_LENGTH;} else if (messageType === 'poll') {- formValid = pollQuestion.trim().length > 0 && pollOptionsFilled.length >= 2;+ formValid =+ pollQuestion.trim().length > 0 &&+ captionLength(pollQuestion.trim()) <= POLL_NAME_MAX_LENGTH &&+ pollOptionsFilled.length >= 2 &&+ pollOptionsFilled.every(option => captionLength(option) <= POLL_OPTION_MAX_LENGTH);} else if (messageType === 'forward') {formValid = forwardTo.trim().length > 0 && forwardMessageId.trim().length > 0;} else if (messageType === 'bulk') {formValid =(content.trim().length > 0 || bulkAttachment !== null) &&!bulkMediaTooLarge &&- !bulkMediaUrlInvalid &&+ !mediaUrlInvalid &&!bulkAudioWithText &&!bulkCaptionTooLong &&bulkRecipientList.length > 0 &&@@ -482,7 +516,7 @@ export function MessageTester() {// backend accepts url XOR base64 and requires a mimetype for base64 (always provided here).const payload: SendMediaPayload = mediaFile? { base64: mediaFile.base64, mimetype: mediaFile.mimetype }- : { url: mediaUrl };+ : { url: mediaUrl.trim() };if ((messageType === 'image' || messageType === 'video') && content) payload.caption = content;if (messageType === 'document' && content) payload.filename = content;return messageApi.sendMedia(session, target, messageType, payload);@@ -490,7 +524,7 @@ export function MessageTester() {case 'sticker': {const payload: SendMediaPayload = mediaFile? { base64: mediaFile.base64, mimetype: mediaFile.mimetype }- : { url: mediaUrl };+ : { url: mediaUrl.trim() };return messageApi.sendSticker(session, target, payload);}case 'location':@@ -595,11 +629,9 @@ export function MessageTester() {placeholder="https://example.com/file.jpg"disabled={!!mediaFile}/>- {messageType === 'bulk' && (- <span className="hint error" role="status">- {bulkMediaUrlInvalid ? t('messageTester.bulkMediaUrlInvalid') : ''}- </span>- )}+ <span className="hint error" role="status">+ {mediaUrlInvalid ? t('messageTester.bulkMediaUrlInvalid') : ''}+ </span></div><div className="form-group"><label>