Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(engine): add BaileysMessageStoreService (persisted, bounded)

rmyndharis1ecf6c63013c
diff --git a/src/engine/adapters/baileys-message-store.service.spec.ts b/src/engine/adapters/baileys-message-store.service.spec.ts
new file mode 100644
index 000000000..040cc0966
--- /dev/null
+++ b/src/engine/adapters/baileys-message-store.service.spec.ts
@@ -0,0 +1,66 @@
+import { DataSource, Repository } from 'typeorm';
+import { BaileysStoredMessage } from './baileys-stored-message.entity';
+import { BaileysMessageStoreService } from './baileys-message-store.service';
+
+describe('BaileysMessageStoreService', () => {
+ let ds: DataSource;
+ let repo: Repository<BaileysStoredMessage>;
+ let service: BaileysMessageStoreService;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'sqlite', database: ':memory:', entities: [BaileysStoredMessage], synchronize: true });
+ await ds.initialize();
+ repo = ds.getRepository(BaileysStoredMessage);
+ service = new BaileysMessageStoreService(repo);
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ delete process.env.BAILEYS_MESSAGE_STORE_LIMIT;
+ });
+
+ // Partial WAMessage fixture — cast through unknown so strict checks don't fire on the incomplete shape.
+ const msg = (id: string) =>
+ ({
+ key: { id, remoteJid: '[email protected]', fromMe: false },
+ message: { conversation: id },
+ }) as unknown as Parameters<BaileysMessageStoreService['put']>[1];
+
+ it('round-trips a WAMessage through BufferJSON', async () => {
+ await service.put('s1', msg('M1'));
+ const got = await service.getMessage('s1', 'M1');
+ expect(got?.key?.id).toBe('M1');
+ expect(got?.message?.conversation).toBe('M1');
+ });
+
+ it('returns null for an unknown id and is session-scoped', async () => {
+ await service.put('s1', msg('M1'));
+ expect(await service.getMessage('s1', 'NOPE')).toBeNull();
+ expect(await service.getMessage('s2', 'M1')).toBeNull();
+ });
+
+ it('is idempotent on (sessionId, waMessageId)', async () => {
+ await service.put('s1', msg('M1'));
+ await service.put('s1', msg('M1'));
+ expect(await repo.count({ where: { sessionId: 's1' } })).toBe(1);
+ });
+
+ it('evicts oldest beyond the per-session cap', async () => {
+ process.env.BAILEYS_MESSAGE_STORE_LIMIT = '2';
+ const s = new BaileysMessageStoreService(repo);
+ await s.put('s1', msg('M1'));
+ await s.put('s1', msg('M2'));
+ await s.put('s1', msg('M3'));
+ expect(await s.getMessage('s1', 'M1')).toBeNull(); // oldest evicted
+ expect(await s.getMessage('s1', 'M3')).not.toBeNull();
+ expect(await repo.count({ where: { sessionId: 's1' } })).toBeLessThanOrEqual(2);
+ });
+
+ it('clearSession removes only that session', async () => {
+ await service.put('s1', msg('M1'));
+ await service.put('s2', msg('M2'));
+ await service.clearSession('s1');
+ expect(await service.getMessage('s1', 'M1')).toBeNull();
+ expect(await service.getMessage('s2', 'M2')).not.toBeNull();
+ });
+});
diff --git a/src/engine/adapters/baileys-message-store.service.ts b/src/engine/adapters/baileys-message-store.service.ts
new file mode 100644
index 000000000..2299e8999
--- /dev/null
+++ b/src/engine/adapters/baileys-message-store.service.ts
@@ -0,0 +1,70 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+import { Repository } from 'typeorm';
+import { BufferJSON } from '@whiskeysockets/baileys';
+import type { WAMessage } from '@whiskeysockets/baileys';
+import { BaileysStoredMessage } from './baileys-stored-message.entity';
+import { BaileysMessageStore } from '../types/baileys.types';
+
+function positiveIntFromEnv(name: string, fallback: number): number {
+ const parsed = Number.parseInt(process.env[name] ?? '', 10);
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
+}
+
+@Injectable()
+export class BaileysMessageStoreService implements BaileysMessageStore {
+ constructor(
+ @InjectRepository(BaileysStoredMessage, 'data')
+ private readonly repo: Repository<BaileysStoredMessage>,
+ ) {}
+
+ async put(sessionId: string, msg: WAMessage): Promise<void> {
+ const waMessageId = msg.key?.id;
+ if (!waMessageId) {
+ return;
+ }
+ const serializedMessage = JSON.stringify(msg, BufferJSON.replacer);
+ // Idempotent: the same message arrives from the send return AND the messages.upsert echo.
+ await this.repo.upsert({ sessionId, waMessageId, serializedMessage }, ['sessionId', 'waMessageId']);
+ await this.enforceLimit(sessionId);
+ }
+
+ async getMessage(sessionId: string, messageId: string): Promise<WAMessage | null> {
+ const row = await this.repo.findOne({ where: { sessionId, waMessageId: messageId } });
+ if (!row) {
+ return null;
+ }
+ return JSON.parse(row.serializedMessage, BufferJSON.reviver) as WAMessage;
+ }
+
+ async clearSession(sessionId: string): Promise<void> {
+ await this.repo.delete({ sessionId });
+ }
+
+ /**
+ * Per-session row cap: keep the newest N rows, delete the rest.
+ * Uses a NOT IN subquery over the N keep-IDs so ties in createdAt (fast inserts in tests)
+ * don't incorrectly evict recently added rows.
+ */
+ private async enforceLimit(sessionId: string): Promise<void> {
+ const limit = positiveIntFromEnv('BAILEYS_MESSAGE_STORE_LIMIT', 5000);
+ const total = await this.repo.count({ where: { sessionId } });
+ if (total <= limit) {
+ return;
+ }
+ // Find the IDs of the N rows to keep (newest N by insertion order; waMessageId as stable tiebreaker).
+ const keepRows = await this.repo.find({
+ where: { sessionId },
+ order: { createdAt: 'DESC', waMessageId: 'DESC' },
+ take: limit,
+ select: ['id'],
+ });
+ const keepIds = keepRows.map(r => r.id);
+ await this.repo
+ .createQueryBuilder()
+ .delete()
+ .where('sessionId = :sessionId', { sessionId })
+ .andWhere('id NOT IN (:...keepIds)', { keepIds })
+ .execute();
+ }
+}
diff --git a/src/engine/engine.module.ts b/src/engine/engine.module.ts
index caf1485ae..8ddf47d51 100644
--- a/src/engine/engine.module.ts
+++ b/src/engine/engine.module.ts
@@ -1,9 +1,13 @@
import { Global, Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
import { EngineFactory } from './engine.factory';
+import { BaileysStoredMessage } from './adapters/baileys-stored-message.entity';
+import { BaileysMessageStoreService } from './adapters/baileys-message-store.service';
@Global()
@Module({
- providers: [EngineFactory],
+ imports: [TypeOrmModule.forFeature([BaileysStoredMessage], 'data')],
+ providers: [EngineFactory, BaileysMessageStoreService],
exports: [EngineFactory],
})
export class EngineModule {}
diff --git a/src/engine/types/baileys.types.ts b/src/engine/types/baileys.types.ts
index b380ce6d7..c600c115d 100644
--- a/src/engine/types/baileys.types.ts
+++ b/src/engine/types/baileys.types.ts
@@ -1,3 +1,18 @@
+import type { WAMessage } from '@whiskeysockets/baileys';
+
+/**
+ * Persistence boundary for the Baileys engine's message store. The adapter depends on this narrow
+ * interface (not the concrete Nest service) so it stays unit-testable with a fake.
+ */
+export interface BaileysMessageStore {
+ /** Persist a message (idempotent on the same id) so it can be referenced by reply/forward/react/delete. */
+ put(sessionId: string, msg: WAMessage): Promise<void>;
+ /** Look up a previously-seen message by its id, or null. */
+ getMessage(sessionId: string, messageId: string): Promise<WAMessage | null>;
+ /** Remove all stored messages for a session (called on logout). */
+ clearSession(sessionId: string): Promise<void>;
+}
+
/**
* Per-call construction config for {@link BaileysAdapter}. Engine-neutral fields come from the
* factory; `authDir` is the base multi-file auth directory from the opaque `engine.baileys.*` blob
@@ -8,6 +23,8 @@ export interface BaileysAdapterConfig {
authDir: string;
proxyUrl?: string;
proxyType?: 'http' | 'https' | 'socks4' | 'socks5';
+ /** Persisted store for reply/forward/react/delete. Provided by the plugin; the four ops require it. */
+ messageStore?: BaileysMessageStore;
}
/**
diff --git a/test/__mocks__/@whiskeysockets/baileys.ts b/test/__mocks__/@whiskeysockets/baileys.ts
index 16dc8b0e9..e3df0b27c 100644
--- a/test/__mocks__/@whiskeysockets/baileys.ts
+++ b/test/__mocks__/@whiskeysockets/baileys.ts
@@ -14,3 +14,31 @@ export const useMultiFileAuthState = jest.fn();
export const fetchLatestBaileysVersion = jest.fn();
export const getContentType = jest.fn();
export const DisconnectReason = { loggedOut: 401 };
+
+// Inline implementation mirrored from @whiskeysockets/baileys/lib/Utils/generics.js
+// (the package is pure ESM; ts-jest runs CJS, so the mock owns the serialisation helpers)
+
+type BufferLike = { type: 'Buffer'; data: string | number[] };
+type BufferJsonObject = { buffer?: boolean; type?: string; data?: string | number[]; value?: string | number[] };
+
+export const BufferJSON = {
+ replacer: (_k: string, value: unknown): unknown => {
+ if (Buffer.isBuffer(value) || value instanceof Uint8Array) {
+ return { type: 'Buffer', data: Buffer.from(value).toString('base64') };
+ }
+ if (typeof value === 'object' && value !== null && (value as BufferLike).type === 'Buffer') {
+ return { type: 'Buffer', data: Buffer.from((value as BufferLike).data).toString('base64') };
+ }
+ return value;
+ },
+ reviver: (_: string, value: unknown): unknown => {
+ if (typeof value === 'object' && value !== null) {
+ const obj = value as BufferJsonObject;
+ if (obj.buffer === true || obj.type === 'Buffer') {
+ const val = obj.data ?? obj.value;
+ return typeof val === 'string' ? Buffer.from(val, 'base64') : Buffer.from(val ?? []);
+ }
+ }
+ return value;
+ },
+};