Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): quote a message whose received hooks are still running
Yudhi Armyndharis49b35946fd87
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 86af4dc72..5a1c30426 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- A reply, button click or quoting send made from a `message:received` plugin hook stores the text of the message it quotes, so the dashboard shows that quote instead of an empty box.- The dashboard dev server proxies only `/api/` paths, so a full reload of the API Keys page (`/api-keys`) loads the dashboard instead of being forwarded to the backend.- The dashboard Chats thread renders an `@<digits>` mention as `@FirstName` when that participant has posted in the loaded thread and their id matches the digits in the body. This covers whatsapp-web.js, where the author id and the mention carry the same digits. On Baileys the author is normalized to the phone number when the lid mapping is known while the body keeps the lid digits, so those mentions stay as WhatsApp sent them, as does any mention of someone who has not posted. The resolved name renders inside its own `<bdi>` element, outside Linkify's `ignoreTags`-respected walk, so a push name can never become a clickable link, however it's spelled. Thanks @TanmayChachra.- The dashboard Plugins page shows a plugin's status and type in the selected language; they rendered as raw English values (`installed`, `extension`) in every locale.diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsindex f07643365..9f132c439 100644--- a/src/modules/message/message-send.service.spec.ts+++ b/src/modules/message/message-send.service.spec.ts@@ -14,6 +14,7 @@ import { TemplateService } from '../template/template.service';import { Template } from '../template/entities/template.entity';import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { SendPacingService } from './send-pacing.service';+import type { MessageProjector } from '../session/message-projector.service';/** Pacing is off by default in these tests; the governor's own spec covers its behaviour. */const inertPacing = (): SendPacingService =>@@ -1103,6 +1104,58 @@ describe('MessageSendService', () => {});});+ describe('quoting a message whose message:received hooks are still running', () => {+ // A plugin that replies from its message:received hook sends before the inbound row is written,+ // so the table has nothing to quote. The projector's in-flight copy stands in for it.+ const inFlight = { chatId: '[email protected]', body: 'what are your hours?' };+ const quoteOf = (): unknown => {+ const calls = (repository.create as jest.Mock).mock.calls as [{ metadata: { quotedMessage: unknown } }][];+ return calls[0][0].metadata.quotedMessage;+ };+ const withProjector = (live: { chatId: string; body: unknown } = inFlight): MessageSendService =>+ new MessageSendService(+ repository as Repository<Message>,+ sessionService as unknown as SessionService,+ engines,+ hookManager as HookManager,+ templateService as unknown as TemplateService,+ inertPacing(),+ undefined,+ undefined,+ undefined,+ {+ inFlightInbound: jest.fn((sessionId: string, id: string) =>+ sessionId === 'sess-1' && id === 'wa-live' ? live : undefined,+ ),+ } as unknown as MessageProjector,+ );++ it('reply stores the body of the message the hook chain carries', async () => {+ await withProjector().reply('sess-1', { chatId: '[email protected]', quotedMessageId: 'wa-live', text: '9 to 5' });+ expect(quoteOf()).toEqual({ id: 'wa-live', body: 'what are your hours?' });+ });++ it('a quoting send stores it too', async () => {+ await withProjector().sendText('sess-1', { chatId: '[email protected]', text: '9 to 5', quotedMessageId: 'wa-live' });+ expect(quoteOf()).toEqual({ id: 'wa-live', body: 'what are your hours?' });+ });++ it('reply does not copy the in-flight body into another chat', async () => {+ await withProjector().reply('sess-1', { chatId: '[email protected]', quotedMessageId: 'wa-live', text: 'hi' });+ expect(quoteOf()).toEqual({ id: 'wa-live', body: '' });+ });++ it('quotes a body a hook rewrote into something other than text as empty', async () => {+ // A rewrite is only checked for its id and chatId; the dashboard renders the quote as a string.+ await withProjector({ chatId: '[email protected]', body: 42 }).reply('sess-1', {+ chatId: '[email protected]',+ quotedMessageId: 'wa-live',+ text: 'hi',+ });+ expect(quoteOf()).toEqual({ id: 'wa-live', body: '' });+ });+ });+// ── reply / forward ───────────────────────────────────────────────describe('reply', () => {diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsindex 31b09a802..6afe93fe4 100644--- a/src/modules/message/message-send.service.ts+++ b/src/modules/message/message-send.service.ts@@ -3,6 +3,7 @@ import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { In, Repository, QueryDeepPartialEntity } from 'typeorm';import { SessionService } from '../session/session.service';+import { MessageProjector } from '../session/message-projector.service';import { EngineRegistry } from '../../engine/engine-registry.service';import { SendTextMessageDto, SendMediaMessageDto, SendAudioMessageDto, MessageResponseDto } from './dto';import { SendTemplateMessageDto } from './dto/send-template.dto';@@ -95,6 +96,10 @@ export class MessageSendService {// literal forms only, never on its lid.@Optional()private readonly lidMappingStore?: LidMappingStoreService,+ // Optional for the same reason; absent means a quote is read from stored rows only, so a reply+ // sent while the quoted message's `message:received` hooks still run stores an empty quote.+ @Optional()+ private readonly messageProjector?: MessageProjector,) {}async sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {@@ -599,7 +604,9 @@ export class MessageSendService {* to that chat (any of its phone, lid or group forms): the pending row is saved before the engine* refuses a cross-chat quote, and copying a foreign body would store it under a chat a* chat-restricted key may use. The send routes may quote across chats, and the guard refuses a- * chat-restricted key any quotedMessageId there, so they pass no chat.+ * chat-restricted key any quotedMessageId there, so they pass no chat. While the quoted message's+ * `message:received` hooks are still running it has no row yet, so the copy that hook chain+ * carries answers instead, under the same chat restriction.*/private async resolveQuotedBody(sessionId: string, quotedMessageId: string, chatId?: string): Promise<string> {try {@@ -613,6 +620,12 @@ export class MessageSendService {},): [];+ // A `message:received` hook that answers the message runs before its row is written. A hook+ // rewrite is checked for its id and chatId only, so a body that is not text quotes as ''.+ const inFlight = this.messageProjector?.inFlightInbound(sessionId, quotedMessageId);+ if (inFlight && (!chatId || inFlight.chatId === chatId || expanded.includes(inFlight.chatId))) {+ return typeof inFlight.body === 'string' ? inFlight.body : '';+ }const quoted = await this.messageRepository.findOne({where: chatId? { sessionId, chatId: In([...new Set([chatId, ...expanded])]), waMessageId: quotedMessageId }diff --git a/src/modules/session/message-projector.service.spec.ts b/src/modules/session/message-projector.service.spec.tsindex 03d037445..0b325b8d6 100644--- a/src/modules/session/message-projector.service.spec.ts+++ b/src/modules/session/message-projector.service.spec.ts@@ -488,6 +488,47 @@ describe('MessageProjector (inbound projection)', () => {expect(webhookService.dispatch).toHaveBeenCalledWith(SESSION_ID, 'message.received', rewritten);});+ it('exposes the message its hook chain carries, rewrites included, until the row is written', async () => {+ // A handler that replies to the message runs before the insert, so the reply's quote preview+ // has no row to read. The chain's copy stands in, and must be the redacted one when an earlier+ // handler rewrote it: the quote is stored next to the rewritten row.+ const engine = makeEngine();+ engines.set(SESSION_ID, engine);+ const seen: unknown[] = [];+ hookManager.execute.mockImplementationOnce(+ (_event: string, data: IncomingMessage, options: { accept: (d: unknown) => boolean }) => {+ seen.push(projector.inFlightInbound(SESSION_ID, 'wamid.1'));+ const rewritten = { ...data, body: '[redacted]' };+ options.accept(rewritten);+ seen.push(projector.inFlightInbound(SESSION_ID, 'wamid.1'));+ return Promise.resolve({ continue: true, data: rewritten });+ },+ );+ let finishInsert: () => void = () => undefined;+ messageRepository.insert.mockImplementationOnce(+ () =>+ new Promise(resolve => {+ finishInsert = () => resolve({ identifiers: [{ id: 1 }], generatedMaps: [{}] });+ }),+ );++ projector.handleInboundMessage(SESSION_ID, engine, makeIncoming());+ await new Promise(resolve => setImmediate(resolve));++ expect(seen).toEqual([+ expect.objectContaining({ chatId: '[email protected]', body: 'hello' }),+ expect.objectContaining({ chatId: '[email protected]', body: '[redacted]' }),+ ]);+ // Still in flight while the insert is pending: a reply the handler did not await lands here.+ expect(projector.inFlightInbound(SESSION_ID, 'wamid.1')).toMatchObject({ body: '[redacted]' });++ finishInsert();+ await new Promise(resolve => setImmediate(resolve));++ expect(projector.inFlightInbound(SESSION_ID, 'wamid.1')).toBeUndefined();+ expect(projector.inFlightInbound('other-session', 'wamid.1')).toBeUndefined();+ });+it('routes a status broadcast to the status store instead of the message table', async () => {const engine = makeEngine();engines.set(SESSION_ID, engine);diff --git a/src/modules/session/message-projector.service.ts b/src/modules/session/message-projector.service.tsindex 27eafbbc9..08fccbd4f 100644--- a/src/modules/session/message-projector.service.ts+++ b/src/modules/session/message-projector.service.ts@@ -86,6 +86,10 @@ export class MessageProjector {this.logger.error(`Unexpected failure applying message mutation: ${key}`, String(err));});+ // Inbound messages whose `message:received` chain is running, by `${sessionId}:${waMessageId}`. The+ // row is written only after the chain, so a handler that quotes the message reads it from here.+ private readonly inboundInFlight = new Map<string, { message: InboundMessageData }>();+// Reaction/edit applies, extracted to a plain collaborator. It shares this instance's// messageMutations queue, so the public enqueue path and the queued applies serialize on one chain.private readonly mutationProjector: MessageMutationProjector;@@ -138,18 +142,40 @@ export class MessageProjector {void this.sessionRepository.update(id, { lastActiveAt: new Date() }).catch(() => undefined);// Convert IncomingMessage to plain object for dispatchconst messageData = { ...message };+ // Tracks the chain's current copy, so a quote taken mid-chain carries an earlier handler's rewrite.+ const inFlight = { message: messageData };+ const inFlightKey = `${id}:${message.id}`;+ this.inboundInFlight.set(inFlightKey, inFlight);// Execute hook for message received - plugins can modify or stop processingvoid this.hookManager.execute('message:received', messageData, {sessionId: id,source: 'Engine',- accept: isMessagePayload,+ accept: data => {+ if (!isMessagePayload(data)) return false;+ inFlight.message = data;+ return true;+ },}).then(({ data }) =>this.projectInboundMessage(id, engine, this.messageOrEngineCopy(id, 'message:received', data, message)),)- .catch(err => this.logger.error(`onMessage handler failed for ${id}`, String(err)));+ .catch(err => this.logger.error(`onMessage handler failed for ${id}`, String(err)))+ .finally(() => {+ // A re-fire of the same id may have replaced the entry; leave that one to its own chain.+ if (this.inboundInFlight.get(inFlightKey) === inFlight) this.inboundInFlight.delete(inFlightKey);+ });+ }++ /**+ * The inbound message a `message:received` chain is carrying, as the chain last rewrote it, from the+ * moment the chain starts until the message's row is written; undefined otherwise. The row does not+ * exist while the chain runs, so a handler that replies to the message finds nothing to quote in the+ * table.+ */+ inFlightInbound(sessionId: string, waMessageId: string): Pick<IncomingMessage, 'chatId' | 'body'> | undefined {+ return waMessageId ? this.inboundInFlight.get(`${sessionId}:${waMessageId}`)?.message : undefined;}/**