Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): enable initial sync + dialect-agnostic chatId filter + debug logging (#375)

Tobias Strebitzer3d8483a4fb0c
diff --git a/.env.example b/.env.example
index ebb7d251f..0e8dc9473 100644
--- a/.env.example
+++ b/.env.example
@@ -70,6 +70,12 @@ PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--d
# global Node.js version floor. Node.js 22 LTS is recommended for all deployments.
BAILEYS_AUTH_DIR=./data/baileys
# NOTE: proxy (PROXY_URL/PROXY_TYPE) is not yet supported by the baileys engine; it is ignored.
+# Pull the FULL message-history archive on connect (large). Off by default: the engine still enables the
+# initial sync (contacts, chats, recent messages, lid mappings) without downloading the entire history.
+BAILEYS_SYNC_FULL_HISTORY=false
+# Surface the Baileys library's own logs for debugging (trace|debug|info|warn|error). Silent by default.
+# `trace` dumps the decoded WhatsApp wire frames to stdout (context "baileys-wire").
+# BAILEYS_LOG_LEVEL=debug
# Humanise single sends: show a "typing…" indicator and pause briefly (length-scaled, jittered)
# before each text send so messages don't look instantaneous (anti-ban). ON by default — set to
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c7d186325..6a9d1327e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,8 +22,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
now carried by a typed `WaId` value object; it is in-memory only and serializes to the exact same
neutral string, so **no webhook / WebSocket / REST response shape changes**.
+- **`BAILEYS_LOG_LEVEL`** (trace|debug|info|warn|error, silent by default) surfaces the Baileys library's
+ own diagnostics; `trace` dumps the decoded WhatsApp wire frames to stdout (context "baileys-wire") for
+ analysis.
+
### Fixed
+- **Baileys engine: contacts, chats and recent history now sync on connect.** Baileys defaults
+ `shouldSyncHistoryMessage` to `() => !!syncFullHistory`, so with `syncFullHistory` unset it silently
+ disabled the **entire** initial sync - the address-book/app-state sync never ran, so no contacts, chat
+ list, recent messages, or `lid -> phone` mappings ever arrived. The adapter now passes
+ `shouldSyncHistoryMessage: () => true`, enabling the sync while keeping the full-archive download
+ opt-in via `BAILEYS_SYNC_FULL_HISTORY` (WhatsApp sends the recent window + contact snapshot, not the
+ entire message history).
+
+- **Message history `chatId` filter now matches across dialects.** A chat addressed as `<phone>@c.us` (the
+ neutral list id) now also returns messages stored under `<phone>@s.whatsapp.net` (e.g. an outbound send
+ addressed by a raw engine id), so the conversation view is no longer empty when the stored and queried
+ dialects differ - the same resolution the `from` filter uses.
+
- **Baileys engine: contact and chat *listing* ids are now engine-neutral (`@c.us`).** `getContacts` /
`getChats` / `getContactById` previously returned the raw `<phone>@s.whatsapp.net` id (visible in the
dashboard, and mismatched against the `@c.us` chatId stored on messages). They now emit the neutral
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index ccdac4e12..a13de5851 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -60,6 +60,45 @@ function createSilentLogger(): BaileysLogger {
return logger;
}
+const BAILEYS_LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error'];
+
+/**
+ * Baileys logger, silent by default. Set `BAILEYS_LOG_LEVEL` (trace|debug|info|warn|error) to surface
+ * Baileys' own diagnostics - the history/app-state sync decision flow ("awaiting notification", "App
+ * state sync complete", MAC errors) at debug/info, and the raw decoded WA wire frames at trace. Emits
+ * JSON lines to stdout (context "baileys-wire") independent of the app log level, so a run can be
+ * captured with `BAILEYS_LOG_LEVEL=trace node dist/main > baileys-wire.log`.
+ */
+function createBaileysLogger(): BaileysLogger {
+ const configured = (process.env.BAILEYS_LOG_LEVEL ?? 'silent').toLowerCase();
+ if (!BAILEYS_LOG_LEVELS.includes(configured)) {
+ return createSilentLogger();
+ }
+ const threshold = BAILEYS_LOG_LEVELS.indexOf(configured);
+ const write =
+ (lvl: string) =>
+ (obj: unknown, msg?: string): void => {
+ if (BAILEYS_LOG_LEVELS.indexOf(lvl) < threshold) {
+ return;
+ }
+ const rec =
+ typeof obj === 'string' ? { msg: obj } : { ...(obj as Record<string, unknown>), ...(msg ? { msg } : {}) };
+ process.stdout.write(
+ JSON.stringify({ ts: new Date().toISOString(), level: lvl, context: 'baileys-wire', ...rec }) + '\n',
+ );
+ };
+ const logger: BaileysLogger = {
+ level: configured,
+ child: () => logger,
+ trace: write('trace'),
+ debug: write('debug'),
+ info: write('info'),
+ warn: write('warn'),
+ error: write('error'),
+ };
+ return logger;
+}
+
export class BaileysAdapter implements IWhatsAppEngine {
private static readonly MAX_RECONNECT_ATTEMPTS = 5;
@@ -164,10 +203,18 @@ export class BaileysAdapter implements IWhatsAppEngine {
version,
browser: BAILEYS_BROWSER,
printQRInTerminal: false,
+ // Enable the initial sync. Baileys defaults `shouldSyncHistoryMessage` to `() => !!syncFullHistory`,
+ // so leaving both unset disables ALL history + app-state sync - no contacts, chats, recent history,
+ // or lid->phone mappings ever arrive (the address-book app-state sync only runs once history sync is
+ // enabled; see WhiskeySockets/Baileys Socket/index.js + Socket/chats.js). Returning true enables it
+ // while keeping the full-archive download opt-in: with syncFullHistory false WhatsApp sends the
+ // RECENT window + the full contact/app-state snapshot, not the entire message history.
+ shouldSyncHistoryMessage: () => true,
+ syncFullHistory: process.env.BAILEYS_SYNC_FULL_HISTORY === 'true',
// BaileysLogger matches ILogger exactly; cast needed because the module resolves
// the type through a deep import path that TypeScript does not auto-unify here.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
- logger: createSilentLogger() as unknown as ILogger,
+ logger: createBaileysLogger() as unknown as ILogger,
});
this.sock = sock;
@@ -175,21 +222,44 @@ export class BaileysAdapter implements IWhatsAppEngine {
sock.ev.on('connection.update', update => this.handleConnectionUpdate(update));
sock.ev.on('messages.upsert', event => this.handleMessagesUpsert(event));
sock.ev.on('messages.update', updates => this.handleMessagesUpdate(updates));
- sock.ev.on('contacts.upsert', contacts => this.sessionStore.upsertContacts(contacts));
- sock.ev.on('contacts.update', updates => this.sessionStore.upsertContacts(updates));
- sock.ev.on('chats.upsert', chats => this.sessionStore.upsertChats(chats));
- sock.ev.on('chats.update', updates => this.sessionStore.upsertChats(updates));
+ sock.ev.on('contacts.upsert', contacts => {
+ this.logContactEvent('contacts.upsert', contacts);
+ this.sessionStore.upsertContacts(contacts);
+ });
+ sock.ev.on('contacts.update', updates => {
+ this.logContactEvent('contacts.update', updates);
+ this.sessionStore.upsertContacts(updates);
+ });
+ sock.ev.on('chats.upsert', chats => {
+ this.logger.debug('Baileys chats event', { action: 'baileys_chats', event: 'upsert', count: chats?.length ?? 0 });
+ this.sessionStore.upsertChats(chats);
+ });
+ sock.ev.on('chats.update', updates => {
+ this.logger.debug('Baileys chats event', {
+ action: 'baileys_chats',
+ event: 'update',
+ count: updates?.length ?? 0,
+ });
+ this.sessionStore.upsertChats(updates);
+ });
sock.ev.on('messaging-history.set', history => {
this.sessionStore.upsertContacts(history.contacts);
this.sessionStore.upsertChats(history.chats);
// lidPnMappings is not in the installed @whiskeysockets/[email protected] type definition but
// is present at runtime in later protocol versions; cast to access it safely.
- const lidPnMappings = (history as unknown as { lidPnMappings?: { lid: string; pn: string }[] }).lidPnMappings;
+ const h = history as unknown as { lidPnMappings?: { lid: string; pn: string }[]; syncType?: unknown };
+ const lidPnMappings = h.lidPnMappings;
this.sessionStore.addLidMappings(lidPnMappings ?? []);
this.logger.debug('History sync received', {
action: 'baileys_history_set',
sessionId: this.config.sessionId,
+ syncType: h.syncType,
+ isLatest: history.isLatest,
+ progress: history.progress,
+ chats: history.chats?.length ?? 0,
+ messages: history.messages?.length ?? 0,
contacts: history.contacts?.length ?? 0,
+ namedContacts: history.contacts?.filter(c => c.name || c.notify).length ?? 0,
lidContacts: history.contacts?.filter(c => c.lid).length ?? 0,
lidPnMappings: lidPnMappings?.length ?? 0,
});
@@ -712,6 +782,29 @@ export class BaileysAdapter implements IWhatsAppEngine {
}
}
+ /** Diagnostic: log a contacts event's size + whether records carry names/lids (and a small sample). */
+ private logContactEvent(
+ event: string,
+ records: Array<{
+ id?: string;
+ name?: string;
+ notify?: string;
+ verifiedName?: string;
+ lid?: string;
+ jid?: string;
+ }> = [],
+ ): void {
+ const list = records ?? [];
+ this.logger.debug('Baileys contacts event', {
+ action: 'baileys_contacts',
+ event,
+ count: list.length,
+ withName: list.filter(r => r.name || r.notify || r.verifiedName).length,
+ withLid: list.filter(r => r.lid).length,
+ sample: list.slice(0, 3).map(r => ({ id: r.id, name: r.name, notify: r.notify, lid: r.lid, jid: r.jid })),
+ });
+ }
+
private async processInboundMessage(msg: WAMessage): Promise<void> {
try {
const b = await this.loadLib();
diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.ts
index 261a59fd4..3a74cdd0a 100644
--- a/src/modules/message/message.service.spec.ts
+++ b/src/modules/message/message.service.spec.ts
@@ -399,6 +399,41 @@ describe('MessageService', () => {
});
});
+ // ── getMessages chatId filter is dialect-agnostic ─────────────────
+ describe('getMessages chatId filter matches across dialects', () => {
+ // A message stored with the raw @s.whatsapp.net chatId (e.g. an outbound send addressed by a raw id).
+ const stored = { id: 'm1', from: '[email protected]', chatId: '[email protected]' } as Message;
+
+ const makeChatQb = () => {
+ let chatIds: string[] | null = null;
+ const qb = {
+ where: jest.fn().mockReturnThis(),
+ orderBy: jest.fn().mockReturnThis(),
+ skip: jest.fn().mockReturnThis(),
+ take: jest.fn().mockReturnThis(),
+ andWhere: jest.fn().mockImplementation((_clause: string, params?: { chatIds?: string[] }) => {
+ if (params?.chatIds) chatIds = params.chatIds;
+ return qb;
+ }),
+ getManyAndCount: jest.fn().mockImplementation(() => {
+ const matched = chatIds && chatIds.includes(stored.chatId) ? [stored] : [];
+ return Promise.resolve([matched, matched.length]);
+ }),
+ };
+ return qb;
+ };
+
+ it('returns a @s.whatsapp.net-stored message when filtering by the neutral @c.us chat id', async () => {
+ lidMappingStore.lidsForPhone.mockReturnValue([]);
+ const qb = makeChatQb();
+ (repository.createQueryBuilder as jest.Mock).mockReturnValue(qb);
+
+ const { messages } = await service.getMessages('sess-1', { chatId: '[email protected]' });
+
+ expect(messages.map(m => m.id)).toEqual(['m1']);
+ });
+ });
+
// ── sendVideo / sendAudio / sendDocument / sendSticker ────────────
describe('sendVideo', () => {
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 0060967a2..58522a08a 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -275,14 +275,17 @@ export class MessageService {
.take(limit);
if (chatId) {
- query.andWhere('message.chatId = :chatId', { chatId });
+ // Match across dialects: a stored chatId may be `@s.whatsapp.net` (e.g. an outbound send addressed
+ // by a raw engine id) while the caller filters by the neutral `@c.us` from the chat list - same
+ // chat, different dialect. Resolving both sides through the table keeps them equal.
+ query.andWhere('message.chatId IN (:...chatIds)', { chatIds: this.resolveJidCandidates(chatId) });
}
if (from) {
// Resolve the filter through the lid->phone table so a phone matches not just the stored
// `<phone>@c.us` id but also any lid that resolves to the same person - turning the prior
// silent miss (a lid-stored author vs a phone filter) into a hit.
- query.andWhere('message.from IN (:...froms)', { froms: this.resolveFromCandidates(from) });
+ query.andWhere('message.from IN (:...froms)', { froms: this.resolveJidCandidates(from) });
}
const [messages, total] = await query.getManyAndCount();
@@ -290,13 +293,13 @@ export class MessageService {
}
/**
- * Expand a `from` filter into every stored id that refers to the same person: the literal input (so an
- * exact lid/group filter still matches), the phone in both user dialects, and every lid the resolution
- * table maps to that phone.
+ * Expand a JID filter into every stored id that refers to the same chat/person: the literal input (so
+ * an exact group/lid filter still matches), the user-part in both user dialects (`@c.us` /
+ * `@s.whatsapp.net`), and every lid the resolution table maps to that phone.
*/
- private resolveFromCandidates(from: string): string[] {
- const phone = userPart(from);
- const candidates = new Set<string>([from, `${phone}@c.us`, `${phone}@s.whatsapp.net`]);
+ private resolveJidCandidates(value: string): string[] {
+ const phone = userPart(value);
+ const candidates = new Set<string>([value, `${phone}@c.us`, `${phone}@s.whatsapp.net`]);
for (const lid of this.lidMappingStore.lidsForPhone(phone)) {
candidates.add(`${lid}@lid`);
}