Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): baileys reply/forward/react/delete via the persisted store
rmyndharisffb38bd98201
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cea16a1a3..c736d862b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@ plugins instead of in core (#265).it via `POST /plugins/auto-reply/enable` to exercise the capability layer end-to-end. (#294)- **Baileys engine (minimal slice)** — `ENGINE_TYPE=baileys` now selects a second, browser-free WhatsApp engine built on `@whiskeysockets/baileys` (WebSocket/Noise protocol, no Chromium). This first slice supports linking (QR + pairing code), sending and receiving **text**, recipient resolution, and typing presence; all other operations return HTTP 501 until later slices add a message store. Config: `BAILEYS_AUTH_DIR` (default `./data/baileys`). Proxy is not yet supported on this engine. (#299)- **Baileys engine — media/location/contact sends.** The Baileys engine (`ENGINE_TYPE=baileys`) can now send image/video/audio/document/sticker, location, and contact messages (slice 2a). URL media is fetched through the same SSRF-guarded path as the whatsapp-web.js engine (host guard + byte cap + timeout, no redirects). Reply/forward/react/delete remain unsupported (HTTP 501) until a later slice adds a message store. (#307)+- **Baileys engine — reply/forward/react/delete.** The Baileys engine can now reply to, forward, react to, and delete (revoke-for-everyone) messages, backed by a persisted per-session message store (`baileys_stored_messages`, bounded by `BAILEYS_MESSAGE_STORE_LIMIT`, default 5000). Delete-for-me and reading reactions remain unsupported (HTTP 501). (#PR)### Changeddiff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex b6e72e11b..592537393 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -45,7 +45,13 @@ import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error'import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';-const newAdapter = (): BaileysAdapter => new BaileysAdapter({ sessionId: 'sess-1', authDir: './data/baileys' });+const fakeStore = {+ put: jest.fn().mockResolvedValue(undefined),+ getMessage: jest.fn(),+ clearSession: jest.fn().mockResolvedValue(undefined),+};+const newAdapter = (): BaileysAdapter =>+ new BaileysAdapter({ sessionId: 'sess-1', authDir: './data/baileys', messageStore: fakeStore });const noopCallbacks = (over: Partial<EngineEventCallbacks> = {}): EngineEventCallbacks => over;@@ -419,3 +425,100 @@ describe('BaileysAdapter media sends', () => {).rejects.toBeInstanceOf(EngineNotReadyError);});});++describe('BaileysAdapter store-backed ops', () => {+ beforeEach(() => {+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };+ jest.clearAllMocks();+ fakeSock.sendMessage.mockResolvedValue({+ key: { id: 'OUT', remoteJid: '[email protected]', fromMe: true },+ messageTimestamp: 1700000009,+ });+ });++ const ready = async (): Promise<BaileysAdapter> => {+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('connection.update', { connection: 'open' });+ return adapter;+ };++ const stored = {+ key: { id: 'TARGET', remoteJid: '[email protected]', fromMe: false },+ message: { conversation: 'hi' },+ };++ it('replyToMessage quotes the stored message', async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.replyToMessage('[email protected]', 'TARGET', 'my reply');+ expect(fakeStore.getMessage).toHaveBeenCalledWith('sess-1', 'TARGET');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(+ '[email protected]',+ { text: 'my reply' },+ { quoted: stored },+ );+ });++ it('forwardMessage forwards the stored message', async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.forwardMessage('[email protected]', '[email protected]', 'TARGET');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { forward: stored });+ });++ it('reactToMessage sends the stored key', async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.reactToMessage('[email protected]', 'TARGET', '👍');+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', {+ react: { text: '👍', key: stored.key },+ });+ });++ it('deleteMessage revokes via the stored key', async () => {+ fakeStore.getMessage.mockResolvedValue(stored);+ const adapter = await ready();+ await adapter.deleteMessage('[email protected]', 'TARGET', true);+ expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { delete: stored.key });+ });++ it('throws when the referenced message is not in the store', async () => {+ fakeStore.getMessage.mockResolvedValue(null);+ const adapter = await ready();+ await expect(adapter.replyToMessage('c', 'GONE', 'x')).rejects.toThrow(/not found/i);+ });++ it('deleteMessage for-me (forEveryone=false) is not supported', async () => {+ const adapter = await ready();+ await expect(adapter.deleteMessage('c', 'TARGET', false)).rejects.toBeInstanceOf(EngineNotSupportedError);+ });++ it('populates the store on an inbound message', async () => {+ const adapter = newAdapter();+ await adapter.initialize({});+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ { key: { remoteJid: '[email protected]', fromMe: false, id: 'IN9' }, message: { conversation: 'hi' } },+ ],+ });+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const inboundMatcher = expect.objectContaining({ key: expect.objectContaining({ id: 'IN9' }) });+ expect(fakeStore.put).toHaveBeenCalledWith('sess-1', inboundMatcher);+ });++ it('populates the store on an outgoing send', async () => {+ const adapter = await ready();+ await adapter.sendTextMessage('[email protected]', 'hello');+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment+ const outboundMatcher = expect.objectContaining({ key: expect.objectContaining({ id: 'OUT' }) });+ expect(fakeStore.put).toHaveBeenCalledWith('sess-1', outboundMatcher);+ });++ it('clears the store on logout', async () => {+ const adapter = await ready();+ await adapter.logout();+ expect(fakeStore.clearSession).toHaveBeenCalledWith('sess-1');+ });+});diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex 715a2388b..f90d01d0d 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -5,7 +5,7 @@ import makeWASocket, {getContentType,useMultiFileAuthState,} from '@whiskeysockets/baileys';-import type { AnyMessageContent, WAMessage, WASocket } from '@whiskeysockets/baileys';+import type { AnyMessageContent, MiscMessageGenerationOptions, WAMessage, WASocket } from '@whiskeysockets/baileys';import { buildIncomingMessageFromBaileys, mapBaileysStatus } from './baileys-message-mapper';import type { ILogger } from '@whiskeysockets/baileys/lib/Utils/logger.js';import {@@ -185,6 +185,7 @@ export class BaileysAdapter implements IWhatsAppEngine {}this.sock = null;this.setStatus(EngineStatus.DISCONNECTED);+ await this.config.messageStore?.clearSession(this.config.sessionId).catch(() => undefined);// ponytail: leaves the multi-file auth dir on disk; a fresh link overwrites it. Add fs cleanup if// stale creds ever block re-linking.}@@ -227,6 +228,13 @@ export class BaileysAdapter implements IWhatsAppEngine {async sendTextMessage(chatId: string, text: string): Promise<MessageResult> {this.ensureReady();const sent = await this.sock!.sendMessage(chatId, { text });+ if (sent) {+ void this.config.messageStore?.put(this.config.sessionId, sent).catch(err =>+ this.logger.warn('Failed to persist sent message to store', {+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ }return {id: sent?.key?.id ?? '',timestamp: this.toUnixSeconds(sent?.messageTimestamp),@@ -299,18 +307,37 @@ export class BaileysAdapter implements IWhatsAppEngine {});}- // ----- Gated: not supported by this minimal slice (no store) ------ /* eslint-disable @typescript-eslint/no-unused-vars */+ async replyToMessage(chatId: string, quotedMsgId: string, text: string): Promise<MessageResult> {+ this.ensureReady();+ const quoted = await this.requireStored(quotedMsgId);+ return this.sendContent(chatId, { text }, { quoted });+ }- replyToMessage(_chatId: string, _quotedMsgId: string, _text: string): Promise<MessageResult> {- return this.unsupported('replyToMessage');+ async forwardMessage(fromChatId: string, toChatId: string, messageId: string): Promise<MessageResult> {+ this.ensureReady();+ const forward = await this.requireStored(messageId);+ return this.sendContent(toChatId, { forward });}- forwardMessage(_fromChatId: string, _toChatId: string, _messageId: string): Promise<MessageResult> {- return this.unsupported('forwardMessage');++ async reactToMessage(chatId: string, messageId: string, emoji: string): Promise<void> {+ this.ensureReady();+ const target = await this.requireStored(messageId);+ await this.sock!.sendMessage(chatId, { react: { text: emoji, key: target.key } });}- reactToMessage(_chatId: string, _messageId: string, _emoji: string): Promise<void> {- return this.unsupported('reactToMessage');++ async deleteMessage(chatId: string, messageId: string, forEveryone = true): Promise<void> {+ this.ensureReady();+ if (!forEveryone) {+ // Baileys only supports revoke-for-everyone via sendMessage; delete-for-me is not implemented.+ throw new EngineNotSupportedError('deleteMessage (delete-for-me)');+ }+ const target = await this.requireStored(messageId);+ await this.sock!.sendMessage(chatId, { delete: target.key });}++ // ----- Gated: not supported by this minimal slice (no store) -----+ /* eslint-disable @typescript-eslint/no-unused-vars */+getMessageReactions(_chatId: string, _messageId: string): Promise<MessageReaction[]> {return this.unsupported('getMessageReactions');}@@ -359,9 +386,6 @@ export class BaileysAdapter implements IWhatsAppEngine {revokeGroupInviteCode(_groupId: string): Promise<string> {return this.unsupported('revokeGroupInviteCode');}- deleteMessage(_chatId: string, _messageId: string, _forEveryone?: boolean): Promise<void> {- return this.unsupported('deleteMessage');- }getChatHistory(_chatId: string, _limit?: number, _includeMedia?: boolean): Promise<IncomingMessage[]> {return this.unsupported('getChatHistory');}@@ -465,6 +489,11 @@ export class BaileysAdapter implements IWhatsAppEngine {} else {this.callbacks.onMessage?.(incoming);}+ void this.config.messageStore?.put(this.config.sessionId, msg).catch(err =>+ this.logger.warn('Failed to persist message to store', {+ error: err instanceof Error ? err.message : String(err),+ }),+ );}}@@ -539,11 +568,33 @@ export class BaileysAdapter implements IWhatsAppEngine {}/** Send a Baileys content object and shape the result like the other sends. */- private async sendContent(chatId: string, content: AnyMessageContent): Promise<MessageResult> {- const sent = await this.sock!.sendMessage(chatId, content);+ private async sendContent(+ chatId: string,+ content: AnyMessageContent,+ options?: MiscMessageGenerationOptions,+ ): Promise<MessageResult> {+ const sent = options+ ? await this.sock!.sendMessage(chatId, content, options)+ : await this.sock!.sendMessage(chatId, content);+ if (sent) {+ void this.config.messageStore?.put(this.config.sessionId, sent).catch(err =>+ this.logger.warn('Failed to persist sent message to store', {+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ }return { id: sent?.key?.id ?? '', timestamp: this.toUnixSeconds(sent?.messageTimestamp) };}+ /** 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.config.messageStore?.getMessage(this.config.sessionId, messageId);+ if (!found?.key) {+ throw new Error(`Message ${messageId} not found`);+ }+ return found;+ }+private unsupported(method: string): Promise<any> {return Promise.reject(new EngineNotSupportedError(method));}diff --git a/src/plugins/engines/baileys/index.spec.ts b/src/plugins/engines/baileys/index.spec.tsindex 5a49c2303..e73a6bebb 100644--- a/src/plugins/engines/baileys/index.spec.ts+++ b/src/plugins/engines/baileys/index.spec.ts@@ -37,13 +37,17 @@ describe('BaileysPlugin.createEngine (opaque config)', () => {);});- it('advertises the slice-2a supported feature set', () => {+ it('advertises the slice-2b supported feature set', () => {expect(new BaileysPlugin().getFeatures()).toEqual(['text-messages','typing-indicator','media-messages','location-messages','contact-messages',+ 'message-replies',+ 'message-forwarding',+ 'message-reactions',+ 'message-deletion',]);});diff --git a/src/plugins/engines/baileys/index.ts b/src/plugins/engines/baileys/index.tsindex a33ec8512..90ed03463 100644--- a/src/plugins/engines/baileys/index.ts+++ b/src/plugins/engines/baileys/index.ts@@ -51,7 +51,17 @@ export class BaileysPlugin implements IEnginePlugin {}getFeatures(): string[] {- return ['text-messages', 'typing-indicator', 'media-messages', 'location-messages', 'contact-messages'];+ return [+ 'text-messages',+ 'typing-indicator',+ 'media-messages',+ 'location-messages',+ 'contact-messages',+ 'message-replies',+ 'message-forwarding',+ 'message-reactions',+ 'message-deletion',+ ];}getEngineLibrary(): { name: string; version: string } {diff --git a/test/baileys-engine.e2e-spec.ts b/test/baileys-engine.e2e-spec.tsindex e48da3000..bf396e85b 100644--- a/test/baileys-engine.e2e-spec.ts+++ b/test/baileys-engine.e2e-spec.ts@@ -60,6 +60,10 @@ describe('Baileys engine boot (e2e)', () => {'media-messages','location-messages','contact-messages',+ 'message-replies',+ 'message-forwarding',+ 'message-reactions',+ 'message-deletion',]);});});