Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): attach the quoted message on every whatsapp-web.js send

Yudhi Armyndharis5f87f4ba3b14
diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.ts
index 2a25b7f22..acdfbc7bb 100644
--- a/src/engine/adapters/wwebjs-messaging.ts
+++ b/src/engine/adapters/wwebjs-messaging.ts
@@ -9,6 +9,7 @@ import {
MessageReaction,
MessageResult,
PollInput,
+ Quotable,
} from '../interfaces/whatsapp-engine.interface';
import { MessageWithReactions, SerializedWid } from '../types/whatsapp-web-js.types';
import { BadRequestException } from '@nestjs/common';
@@ -247,6 +248,22 @@ export class WwebjsMessaging {
* Error carries no status and no recipient, so letting it through produced an opaque 500 for what
* is really a caller-visible fact the gateway already established: `getNumberId` returned null.
*/
+ /**
+ * The send options that attach a quote, or nothing at all when the caller asked for none.
+ *
+ * `ignoreQuoteErrors` defaults to TRUE in the library (documented at Client.js:1383, applied at
+ * :1480): with it left alone an id whatsapp-web.js cannot resolve sends the message ANYWAY,
+ * unquoted, and reports success. A caller who asked for a reply and received a loose message has
+ * no signal that anything went wrong, so this opts out and lets the failure surface.
+ *
+ * A second, narrower drop is NOT covered by that flag: if the message resolves but `canReplyMsg`
+ * is false, `quotedMsgOptions` stays empty and the send proceeds unquoted (Injected/Utils.js:
+ * 187-195). That one is upstream behaviour we cannot switch off from here.
+ */
+ private quoteOptions(quotedMessageId?: string): { quotedMessageId?: string; ignoreQuoteErrors?: boolean } {
+ return quotedMessageId ? { quotedMessageId, ignoreQuoteErrors: false } : {};
+ }
+
private async sendResolved<T>(chatId: string, send: (to: string) => Promise<T>): Promise<T> {
const to = await this.resolveSendId(chatId);
try {
@@ -287,7 +304,7 @@ export class WwebjsMessaging {
chatId: string,
text: string,
mentions?: string[],
- options?: { linkPreview?: boolean; customPreview?: CustomLinkPreview },
+ options?: { linkPreview?: boolean; customPreview?: CustomLinkPreview } & Quotable,
): Promise<MessageResult> {
this.host.ensureReady();
// wwebjs accepts neutral `<phone>@c.us` WIDs directly as mentionedJidList, so no de-normalization
@@ -303,7 +320,12 @@ export class WwebjsMessaging {
if (options?.customPreview) {
throw new EngineNotSupportedError('sendTextMessage(customPreview)');
}
- const sendOptions: { mentions?: string[]; linkPreview?: boolean } = {};
+ const sendOptions: {
+ mentions?: string[];
+ linkPreview?: boolean;
+ quotedMessageId?: string;
+ ignoreQuoteErrors?: boolean;
+ } = this.quoteOptions(options?.quotedMessageId);
if (mentions?.length) sendOptions.mentions = mentions;
if (options?.linkPreview === false) sendOptions.linkPreview = false;
@@ -367,6 +389,7 @@ export class WwebjsMessaging {
// sendAudioAsVoice only for audio, sendMediaAsDocument only for documents;
// {...undefined} contributes no keys.
...extraOptions,
+ ...this.quoteOptions(media.quotedMessageId),
}),
);
@@ -383,7 +406,9 @@ export class WwebjsMessaging {
name: location.description || '',
address: location.address || '',
});
- const msg = await this.sendResolved(chatId, to => this.client().sendMessage(to, loc));
+ const msg = await this.sendResolved(chatId, to =>
+ this.client().sendMessage(to, loc, this.quoteOptions(location.quotedMessageId)),
+ );
return toMessageResult(msg);
}
@@ -396,6 +421,7 @@ export class WwebjsMessaging {
const msg = await this.sendResolved(chatId, to =>
this.client().sendMessage(to, vcard, {
parseVCards: true,
+ ...this.quoteOptions(contact.quotedMessageId),
}),
);
return toMessageResult(msg);
@@ -414,6 +440,7 @@ export class WwebjsMessaging {
const msg = await this.sendResolved(chatId, to =>
this.client().sendMessage(to, messageMedia, {
sendMediaAsSticker: true,
+ ...this.quoteOptions(media.quotedMessageId),
}),
);
return toMessageResult(msg);
@@ -433,7 +460,11 @@ export class WwebjsMessaging {
type PollSendOptions = ConstructorParameters<typeof Poll>[2];
const pollOptions = { allowMultipleAnswers: poll.allowMultipleAnswers === true } as PollSendOptions;
const msg = await this.sendResolved(chatId, to =>
- this.client().sendMessage(to, new Poll(poll.name, poll.options, pollOptions)),
+ this.client().sendMessage(
+ to,
+ new Poll(poll.name, poll.options, pollOptions),
+ this.quoteOptions(poll.quotedMessageId),
+ ),
);
return toMessageResult(msg);
}
diff --git a/src/engine/adapters/wwebjs-quoted-send.spec.ts b/src/engine/adapters/wwebjs-quoted-send.spec.ts
new file mode 100644
index 000000000..c948989b5
--- /dev/null
+++ b/src/engine/adapters/wwebjs-quoted-send.spec.ts
@@ -0,0 +1,121 @@
+import type { Client } from 'whatsapp-web.js';
+import { WwebjsMessaging } from './wwebjs-messaging';
+import { createLogger } from '../../common/services/logger.service';
+import { type WwebjsEngineHost } from './wwebjs-host';
+
+/**
+ * whatsapp-web.js attaches a quote as a plain send option, orthogonal to the content kind:
+ * `quotedMessageId` is copied into `internalOptions` (Client.js:1475) BEFORE the content-kind
+ * dispatch that moves the payload into `.media` / `.location` / `.poll` / `.contactCard`, so a quote
+ * never competes with what is being sent.
+ *
+ * The reason these tests assert `ignoreQuoteErrors: false` rather than just the id: the library
+ * default is TRUE (Client.js:1383 documents `[ignoreQuoteErrors = true]`, applied at :1480), which
+ * makes an unresolvable quote send the message ANYWAY, unquoted, and report success. A caller who
+ * asked for a reply and got a loose message with a 201 has no way to detect it. Opting out turns
+ * that into an error the caller can see.
+ */
+
+const logger = createLogger('wwebjs-quoted-send.spec');
+
+const QUOTED = '[email protected]_3EB0ABCD';
+
+function makeMessaging(): { messaging: WwebjsMessaging; client: { sendMessage: jest.Mock } } {
+ const client = {
+ sendMessage: jest.fn().mockResolvedValue({ id: { _serialized: 'M1' }, timestamp: 1 }),
+ };
+ const host = {
+ ensureReady: jest.fn(),
+ ensureNotChannelRecipient: jest.fn(),
+ getClient: () => client as unknown as Client,
+ logger,
+ config: {},
+ getNumberId: jest.fn(),
+ capInboundMediaFor: jest.fn(),
+ isPageTransportError: () => false,
+ reportIfPageTransportError: jest.fn(),
+ } as unknown as WwebjsEngineHost;
+ return { messaging: new WwebjsMessaging(host), client };
+}
+
+const optionsOf = (client: { sendMessage: jest.Mock }): Record<string, unknown> => {
+ const [, , options] = client.sendMessage.mock.calls[0] as unknown[];
+ return (options ?? {}) as Record<string, unknown>;
+};
+
+const CHAT = '[email protected]';
+// Base64 rather than a URL: a URL payload runs the real remote-media loader through the SSRF guard,
+// so the test would exercise the network instead of the option plumbing it is about.
+const IMAGE = {
+ data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
+ mimetype: 'image/png',
+};
+
+describe('WwebjsMessaging — a quote rides along with every content kind', () => {
+ // Each of these builds its own options object (or, for location and poll, had none at all before
+ // this change), so covering only the shared media funnel would leave the others silently unquoted.
+ it.each([
+ ['image', (m: WwebjsMessaging) => m.sendImageMessage(CHAT, { ...IMAGE, quotedMessageId: QUOTED })],
+ ['document', (m: WwebjsMessaging) => m.sendDocumentMessage(CHAT, { ...IMAGE, quotedMessageId: QUOTED })],
+ ['sticker', (m: WwebjsMessaging) => m.sendStickerMessage(CHAT, { ...IMAGE, quotedMessageId: QUOTED })],
+ [
+ 'location',
+ (m: WwebjsMessaging) => m.sendLocationMessage(CHAT, { latitude: 1, longitude: 2, quotedMessageId: QUOTED }),
+ ],
+ [
+ 'contact',
+ (m: WwebjsMessaging) => m.sendContactMessage(CHAT, { name: 'Alice', number: '628999', quotedMessageId: QUOTED }),
+ ],
+ [
+ 'poll',
+ (m: WwebjsMessaging) => m.sendPollMessage(CHAT, { name: 'Q', options: ['a', 'b'], quotedMessageId: QUOTED }),
+ ],
+ ['text', (m: WwebjsMessaging) => m.sendTextMessage(CHAT, 'hi', undefined, { quotedMessageId: QUOTED })],
+ ])('%s send forwards the quoted id with quote errors made visible', async (_kind, send) => {
+ const { messaging, client } = makeMessaging();
+
+ await send(messaging);
+
+ expect(client.sendMessage).toHaveBeenCalledTimes(1);
+ expect(optionsOf(client).quotedMessageId).toBe(QUOTED);
+ // The library would otherwise send unquoted and report success on a bad id.
+ expect(optionsOf(client).ignoreQuoteErrors).toBe(false);
+ });
+
+ // Known-negative control: without it an implementation that hardcoded the keys onto every send
+ // would satisfy every assertion above while changing behaviour for unquoted callers too.
+ it('adds no quote keys at all when no id is supplied', async () => {
+ const { messaging, client } = makeMessaging();
+
+ await messaging.sendImageMessage(CHAT, IMAGE);
+
+ expect(optionsOf(client)).not.toHaveProperty('quotedMessageId');
+ expect(optionsOf(client)).not.toHaveProperty('ignoreQuoteErrors');
+ });
+
+ it('keeps the caption and mentions it already sent alongside the quote', async () => {
+ const { messaging, client } = makeMessaging();
+
+ await messaging.sendImageMessage(CHAT, {
+ ...IMAGE,
+ caption: 'look',
+ mentions: ['[email protected]'],
+ quotedMessageId: QUOTED,
+ });
+
+ expect(optionsOf(client)).toMatchObject({
+ caption: 'look',
+ mentions: ['[email protected]'],
+ quotedMessageId: QUOTED,
+ });
+ });
+
+ it('keeps sendMediaAsDocument, which shares the options object with the quote', async () => {
+ const { messaging, client } = makeMessaging();
+
+ await messaging.sendDocumentMessage(CHAT, { ...IMAGE, quotedMessageId: QUOTED });
+
+ expect(optionsOf(client).sendMediaAsDocument).toBe(true);
+ expect(optionsOf(client).quotedMessageId).toBe(QUOTED);
+ });
+});