Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: reliability & hardening — Baileys message.sent parity, DB env validation, session write guards (#637)

Yudhi Armyndharisff2899d3d32e
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index 02a1659d3..1a51627ae 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -24,6 +24,12 @@ describe('validateEnv', () => {
expect(() => validateEnv({ PORT: '2785' })).not.toThrow();
});
+ it('rejects a non-numeric database timeout knob (a typo would become NaN and break the pg pool)', () => {
+ expect(() => validateEnv({ DATABASE_STATEMENT_TIMEOUT_MS: 'abc' })).toThrow(/DATABASE_STATEMENT_TIMEOUT_MS/);
+ expect(() => validateEnv({ DATABASE_IDLE_TIMEOUT_MS: '30s' })).toThrow(/DATABASE_IDLE_TIMEOUT_MS/);
+ expect(() => validateEnv({ DATABASE_CONNECTION_TIMEOUT_MS: '10000' })).not.toThrow();
+ });
+
it('rejects an ENGINE_TYPE typo instead of silently falling back to whatsapp-web.js', () => {
expect(() => validateEnv({ ENGINE_TYPE: 'bailys' })).toThrow(/ENGINE_TYPE/);
expect(() => validateEnv({ ENGINE_TYPE: 'whatsapp-web.js' })).not.toThrow();
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index afaaf2784..bb0ce7dd0 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -85,6 +85,9 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'WEBHOOK_MAX_RETRIES',
'WEBHOOK_RETRY_DELAY',
'DATABASE_POOL_SIZE',
+ 'DATABASE_STATEMENT_TIMEOUT_MS',
+ 'DATABASE_IDLE_TIMEOUT_MS',
+ 'DATABASE_CONNECTION_TIMEOUT_MS',
'REDIS_CONNECT_TIMEOUT_MS',
'MAX_CONCURRENT_SESSIONS', // 0 = unlimited
'INGRESS_INSTANCE_TTL',
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index a0e1a3255..6a0f3760a 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -581,6 +581,35 @@ describe('BaileysAdapter messaging', () => {
expect(res).toEqual({ id: 'OUT1', timestamp: 1700000001 });
});
+ it('emits onMessageCreate for the own send so message.sent fires (parity with the wwjs engine)', async () => {
+ const onMessageCreate = jest.fn();
+ // A realistic own-send return: fromMe + remoteJid + content, which the API-send echo path maps.
+ fakeSock.sendMessage.mockResolvedValue({
+ key: { id: 'OUT1', fromMe: true, remoteJid: '[email protected]' },
+ message: { conversation: 'hello' },
+ messageTimestamp: 1700000001,
+ });
+ const adapter = await readyAdapter({ onMessageCreate });
+ await adapter.sendTextMessage('[email protected]', 'hello');
+ // The echo is emitted off the response path via an async mapMessage chain; let it settle.
+ for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve));
+
+ expect(onMessageCreate).toHaveBeenCalledTimes(1);
+ expect(onMessageCreate).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'OUT1', fromMe: true, body: 'hello', type: 'text' }),
+ );
+ });
+
+ it('skips the own-send echo when the returned message carries no neutral content (best-effort)', async () => {
+ const onMessageCreate = jest.fn();
+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
+ const adapter = await readyAdapter({ onMessageCreate });
+ await adapter.sendTextMessage('[email protected]', 'hi');
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(onMessageCreate).not.toHaveBeenCalled();
+ });
+
it('sendTextMessage honors the chat disappearing timer when one is cached (#473)', async () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
const adapter = await readyAdapter();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index e341405ba..fa35e935e 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -483,6 +483,8 @@ export class BaileysAdapter implements IWhatsAppEngine {
error: err instanceof Error ? err.message : String(err),
}),
);
+ // Parity with the wwjs engine's message_create → message.sent (see emitOwnSendEcho).
+ void this.emitOwnSendEcho(sent);
}
return {
id: sent?.key?.id ?? '',
@@ -1073,7 +1075,11 @@ export class BaileysAdapter implements IWhatsAppEngine {
return withInboundDownloadTimeout(download, inboundMediaTimeoutMs(), () => stream?.destroy?.());
}
- private async mapMessage(msg: WAMessage, contentType: string | undefined): Promise<IncomingMessage> {
+ private async mapMessage(
+ msg: WAMessage,
+ contentType: string | undefined,
+ opts?: { skipMediaDownload?: boolean },
+ ): Promise<IncomingMessage> {
const b = await this.loadLib();
const content = msg.message ?? {};
// Read body/isPtt off the NORMALIZED content: a disappearing message (ephemeralMessage), a captioned
@@ -1112,7 +1118,9 @@ export class BaileysAdapter implements IWhatsAppEngine {
contentType === 'documentWithCaptionMessage' ||
contentType === 'stickerMessage';
if (isMediaType) {
- if (!isMediaDownloadEnabled()) {
+ // The outbound "sent" echo passes skipMediaDownload: the sender already holds the media, and for
+ // parity with the wwjs message.sent (which carries no media buffer) we emit only the marker here.
+ if (opts?.skipMediaDownload || !isMediaDownloadEnabled()) {
// Emit the omitted marker so the media field is present (webhook/n8n/dashboard contract).
// mimetype is available pre-download from the message content.
const normalizedContent = b.normalizeMessageContent(content) ?? content;
@@ -1419,10 +1427,38 @@ export class BaileysAdapter implements IWhatsAppEngine {
error: err instanceof Error ? err.message : String(err),
}),
);
+ // wwjs fires `message_create` for its own API sends, which SessionService turns into `message.sent`.
+ // Baileys' own socket-sends echo back only as a `type:'append'` upsert (skipped as history sync), so
+ // that event never fired for API sends. Emit the outbound "created" callback here for parity —
+ // best-effort and off the response path, with no media re-download (matching the wwjs payload).
+ void this.emitOwnSendEcho(sent);
}
return { id: sent?.key?.id ?? '', timestamp: this.toUnixSeconds(sent?.messageTimestamp) };
}
+ /**
+ * Emit the engine-neutral "message created" callback for a message this session just sent via the API,
+ * so downstream `message.sent` webhook/WS/hook delivery matches the whatsapp-web.js engine. Best-effort:
+ * a mapping failure must never fail the send that already succeeded.
+ */
+ private async emitOwnSendEcho(sent: WAMessage): Promise<void> {
+ if (!this.callbacks.onMessageCreate) return;
+ try {
+ const b = await this.loadLib();
+ if (!sent.message || !sent.key?.remoteJid) return;
+ const normalizedRoot = b.normalizeMessageContent(sent.message) ?? sent.message;
+ const contentType = b.getContentType(normalizedRoot);
+ // protocol / reaction / empty own messages carry no neutral "sent" content.
+ if (!contentType || contentType === 'protocolMessage' || contentType === 'reactionMessage') return;
+ const neutral = await this.mapMessage(sent, contentType, { skipMediaDownload: true });
+ this.callbacks.onMessageCreate(neutral);
+ } catch (err) {
+ this.logger.warn('Failed to emit own-send echo', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
/** 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);
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index fd1bf325d..5ce807238 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -670,13 +670,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
this.sessionErrors.delete(id);
- void this.sessionRepository.update(id, {
- status: SessionStatus.READY,
- phone,
- pushName,
- connectedAt: new Date(),
- lastActiveAt: new Date(),
- });
+ void this.sessionRepository
+ .update(id, {
+ status: SessionStatus.READY,
+ phone,
+ pushName,
+ connectedAt: new Date(),
+ lastActiveAt: new Date(),
+ })
+ .catch(err =>
+ this.logger.warn('Failed to persist session ready state', {
+ sessionId: id,
+ error: err instanceof Error ? err.message : String(err),
+ }),
+ );
},
onMessage: (message): void => {
if (!this.isLiveEngine(id, engine)) return;
@@ -707,7 +714,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
action: 'message_received',
});
// Update last active timestamp
- void this.sessionRepository.update(id, { lastActiveAt: new Date() });
+ void this.sessionRepository.update(id, { lastActiveAt: new Date() }).catch(() => undefined);
// Convert IncomingMessage to plain object for dispatch
const messageData = { ...message };
@@ -822,7 +829,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
action: 'message_sent',
});
// Update last active timestamp
- void this.sessionRepository.update(id, { lastActiveAt: new Date() });
+ void this.sessionRepository.update(id, { lastActiveAt: new Date() }).catch(() => undefined);
const messageData = { ...message };
// Execute hook for message sent - plugins can modify or stop processing