Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): attach the quoted message on every Baileys send
Yudhi Armyndharis4e3702715f14
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex bb26280bc..624740285 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -14,6 +14,7 @@ import {MessageResult,PollInput,Product,+ Quotable,} from '../interfaces/whatsapp-engine.interface';import { toEngineParticipants } from './baileys-groups';import { buildVCard } from './vcard';@@ -148,7 +149,7 @@ export class BaileysMessaging {chatId: string,text: string,mentions?: string[],- sendOptions?: { linkPreview?: boolean; customPreview?: CustomLinkPreview },+ sendOptions?: { linkPreview?: boolean; customPreview?: CustomLinkPreview } & Quotable,): Promise<MessageResult> {this.host.ensureReady();const jid = await this.toDeliverableJid(chatId);@@ -159,6 +160,9 @@ export class BaileysMessaging {const options = {...(this.withEphemeral(jid) ?? {}),getUrlInfo: (text: string) => generateSafeLinkPreview(text),+ // Merged rather than assigned: getUrlInfo above must survive, or the library's own vulnerable+ // preview generator becomes reachable again on quoted sends only.+ ...((await this.quoteOption(sendOptions?.quotedMessageId)) ?? {}),};// `linkPreview: null` is Baileys' explicit "no preview": with the key absent it instead calls the// configured generator (Utils/messages.js:279-281), which for us means a blocking outbound fetch@@ -291,41 +295,57 @@ export class BaileysMessaging {async sendImageMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.host.ensureReady();const { data, mimetype } = await resolveMediaBuffer(media);- return this.sendContent(chatId, {- image: data,- caption: media.caption,- mimetype,- ...this.withMentions(media.mentions),- });+ return this.sendContent(+ chatId,+ {+ image: data,+ caption: media.caption,+ mimetype,+ ...this.withMentions(media.mentions),+ },+ await this.quoteOption(media.quotedMessageId),+ );}async sendVideoMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.host.ensureReady();const { data, mimetype } = await resolveMediaBuffer(media);- return this.sendContent(chatId, {- video: data,- caption: media.caption,- mimetype,- ...this.withMentions(media.mentions),- });+ return this.sendContent(+ chatId,+ {+ video: data,+ caption: media.caption,+ mimetype,+ ...this.withMentions(media.mentions),+ },+ await this.quoteOption(media.quotedMessageId),+ );}async sendAudioMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.host.ensureReady();const { data, mimetype } = await resolveMediaBuffer(media);- return this.sendContent(chatId, { audio: data, mimetype, ptt: media.ptt ?? false });+ return this.sendContent(+ chatId,+ { audio: data, mimetype, ptt: media.ptt ?? false },+ await this.quoteOption(media.quotedMessageId),+ );}async sendDocumentMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.host.ensureReady();const { data, mimetype } = await resolveMediaBuffer(media);- return this.sendContent(chatId, {- document: data,- mimetype,- fileName: media.filename ?? 'file',- caption: media.caption,- ...this.withMentions(media.mentions),- });+ return this.sendContent(+ chatId,+ {+ document: data,+ mimetype,+ fileName: media.filename ?? 'file',+ caption: media.caption,+ ...this.withMentions(media.mentions),+ },+ await this.quoteOption(media.quotedMessageId),+ );}async createCallLink(type: CallLinkType, startTime: number): Promise<string> {@@ -353,39 +373,55 @@ export class BaileysMessaging {async sendStickerMessage(chatId: string, media: MediaInput): Promise<MessageResult> {this.host.ensureReady();const { data, mimetype } = await resolveMediaBuffer(media);- return this.sendContent(chatId, { sticker: await toWebpSticker(data, mimetype) });+ return this.sendContent(+ chatId,+ { sticker: await toWebpSticker(data, mimetype) },+ await this.quoteOption(media.quotedMessageId),+ );}async sendLocationMessage(chatId: string, location: LocationInput): Promise<MessageResult> {this.host.ensureReady();- return this.sendContent(chatId, {- location: {- degreesLatitude: location.latitude,- degreesLongitude: location.longitude,- name: location.description,- address: location.address,+ return this.sendContent(+ chatId,+ {+ location: {+ degreesLatitude: location.latitude,+ degreesLongitude: location.longitude,+ name: location.description,+ address: location.address,+ },},- });+ await this.quoteOption(location.quotedMessageId),+ );}async sendContactMessage(chatId: string, contact: ContactCard): Promise<MessageResult> {this.host.ensureReady();- return this.sendContent(chatId, {- contacts: { displayName: contact.name, contacts: [{ vcard: buildVCard(contact) }] },- });+ return this.sendContent(+ chatId,+ {+ contacts: { displayName: contact.name, contacts: [{ vcard: buildVCard(contact) }] },+ },+ await this.quoteOption(contact.quotedMessageId),+ );}async sendPollMessage(chatId: string, poll: PollInput): Promise<MessageResult> {this.host.ensureReady();// selectableCount 1 = single choice; 0 = no limit, which is how WhatsApp expresses// "allow multiple answers". Baileys generates the poll's messageSecret itself.- return this.sendContent(chatId, {- poll: {- name: poll.name,- values: poll.options,- selectableCount: poll.allowMultipleAnswers ? 0 : 1,+ return this.sendContent(+ chatId,+ {+ poll: {+ name: poll.name,+ values: poll.options,+ selectableCount: poll.allowMultipleAnswers ? 0 : 1,+ },},- });+ await this.quoteOption(poll.quotedMessageId),+ );}async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {@@ -558,6 +594,18 @@ export class BaileysMessaging {}}+ /**+ * Turn an optional quoted-message id into Baileys' `quoted` send option.+ *+ * Baileys quotes by full stored message, never by id, so an id has to be resolved first — and an+ * id we cannot resolve is a hard failure rather than a silent unquoted send: the caller asked for+ * a reply, and a plain message delivered under that name is the wrong result reported as success.+ */+ private async quoteOption(quotedMessageId?: string): Promise<MiscMessageGenerationOptions | undefined> {+ if (!quotedMessageId) return undefined;+ return { quoted: await this.requireStored(quotedMessageId) };+ }+/** Resolve a previously-seen message from the store, or throw a clear not-found error. */private async requireStored(messageId: string): Promise<WAMessage> {const found = await this.host.getStoredMessage(messageId);diff --git a/src/engine/adapters/baileys-quoted-send.spec.ts b/src/engine/adapters/baileys-quoted-send.spec.tsnew file mode 100644index 000000000..e9de2f825--- /dev/null+++ b/src/engine/adapters/baileys-quoted-send.spec.ts@@ -0,0 +1,133 @@+import type { WASocket } from '@whiskeysockets/baileys';+import { BaileysMessaging, type BaileysMessagingHost } from './baileys-messaging';+import { MessageNotFoundError } from '../../common/errors/message-not-found.error';+import { createLogger } from '../../common/services/logger.service';++/**+ * Baileys quotes by full stored message, not by id: `MiscMessageGenerationOptions.quoted` is a+ * `WAMessage` (Types/Message.d.ts:246), and the contextInfo is attached after content generation+ * with no per-content-type branch (Utils/messages.js), so every send kind can carry one.+ *+ * The adapter can therefore only quote a message it has already persisted. That store dependency is+ * the whole reason these assertions check `getStoredMessage` traffic as well as the socket payload:+ * a resolver that silently returned undefined would send an unquoted message and report success,+ * which is exactly the failure this feature exists to avoid on the other engine.+ */++const logger = createLogger('baileys-quoted-send.spec');++const STORED = {+ key: { id: 'QUOTED-1', remoteJid: '[email protected]', fromMe: false },+ message: { conversation: 'the quoted text' },+};++const PNG = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',+ 'base64',+);++// `null`, not `undefined`, for the not-found case: passing undefined to a defaulted parameter+// selects the default, which would quietly turn that test into a second happy-path assertion.+function makeMessaging(stored: unknown = STORED): {+ messaging: BaileysMessaging;+ sock: { sendMessage: jest.Mock };+ getStoredMessage: jest.Mock;+} {+ const sock = { sendMessage: jest.fn().mockResolvedValue({ key: { id: 'M1' }, messageTimestamp: 1 }) };+ const getStoredMessage = jest.fn().mockResolvedValue(stored);+ const host = {+ ensureReady: jest.fn(),+ getSocket: () => sock as unknown as WASocket,+ logger,+ toNeutralJid: (j: string) => j,+ toEngineJid: (j: string) => j,+ normalizedSelfJid: () => '[email protected]',+ getEphemeralExpiration: () => undefined,+ toUnixSeconds: () => 1,+ loadLib: () => Promise.resolve({} as never),+ getStoredMessage,+ putStoredMessage: () => undefined,+ recordLidMapping: () => undefined,+ getOnMessageCreate: () => undefined,+ mapMessage: () => Promise.resolve({} as never),+ } as unknown as BaileysMessagingHost;+ return { messaging: new BaileysMessaging(host), sock, getStoredMessage };+}++const optionsOf = (sock: { sendMessage: jest.Mock }): Record<string, unknown> => {+ const [, , options] = sock.sendMessage.mock.calls[0] as unknown[];+ return (options ?? {}) as Record<string, unknown>;+};++const CHAT = '[email protected]';++describe('BaileysMessaging — a quote rides along with every content kind', () => {+ // One case per content kind rather than media alone: the poll, location and contact paths each+ // build their own content object, so a thread that covered only the shared media helper would+ // leave three senders silently unquoted while this file stayed green.+ it.each([+ [+ 'image',+ (m: BaileysMessaging) =>+ m.sendImageMessage(CHAT, { data: PNG, mimetype: 'image/png', quotedMessageId: 'QUOTED-1' }),+ ],+ [+ 'document',+ (m: BaileysMessaging) =>+ m.sendDocumentMessage(CHAT, { data: PNG, mimetype: 'application/pdf', quotedMessageId: 'QUOTED-1' }),+ ],+ [+ 'location',+ (m: BaileysMessaging) => m.sendLocationMessage(CHAT, { latitude: 1, longitude: 2, quotedMessageId: 'QUOTED-1' }),+ ],+ [+ 'contact',+ (m: BaileysMessaging) =>+ m.sendContactMessage(CHAT, { name: 'Alice', number: '628999', quotedMessageId: 'QUOTED-1' }),+ ],+ [+ 'poll',+ (m: BaileysMessaging) => m.sendPollMessage(CHAT, { name: 'Q', options: ['a', 'b'], quotedMessageId: 'QUOTED-1' }),+ ],+ ['text', (m: BaileysMessaging) => m.sendTextMessage(CHAT, 'hi', undefined, { quotedMessageId: 'QUOTED-1' })],+ ])('%s send attaches the stored message as `quoted`', async (_kind, send) => {+ const { messaging, sock } = makeMessaging();++ await send(messaging);++ expect(sock.sendMessage).toHaveBeenCalledTimes(1);+ expect(optionsOf(sock).quoted).toBe(STORED);+ });++ // Known-negative control. Without it an implementation that attached the quote unconditionally —+ // or that resolved the store on every send — would satisfy every assertion above.+ it('sends unquoted, and never touches the store, when no id is supplied', async () => {+ const { messaging, sock, getStoredMessage } = makeMessaging();++ await messaging.sendImageMessage(CHAT, { data: PNG, mimetype: 'image/png' });++ expect(optionsOf(sock).quoted).toBeUndefined();+ expect(getStoredMessage).not.toHaveBeenCalled();+ });++ it('leaves the existing text options intact while adding the quote', async () => {+ const { messaging, sock } = makeMessaging();++ await messaging.sendTextMessage(CHAT, 'hi', undefined, { quotedMessageId: 'QUOTED-1' });++ // getUrlInfo is passed on every text send so Baileys' own vulnerable preview generator stays+ // unreachable; merging the quote must not displace it.+ expect(typeof optionsOf(sock).getUrlInfo).toBe('function');+ });++ it('refuses an unresolvable id instead of sending unquoted', async () => {+ const { messaging, sock } = makeMessaging(null);++ await expect(+ messaging.sendImageMessage(CHAT, { data: PNG, mimetype: 'image/png', quotedMessageId: 'MISSING' }),+ ).rejects.toBeInstanceOf(MessageNotFoundError);+ // Reporting success on a message that went out without its quote is the defect; failing after+ // the send would not fix it.+ expect(sock.sendMessage).not.toHaveBeenCalled();+ });+});