Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(reliability): contain error-handling gaps on the engine-event path

rmyndharise9fd363030dd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ffcb7a747..744f25024 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Fixed
+
+- **Engine-event handlers no longer risk unhandled promise rejections.** Webhook dispatch is now
+ self-contained (a failed webhook lookup is logged and swallowed, not rejected into the fire-and-forget
+ callers), the `onMessage`/`onMessageCreate` hook chains carry a `.catch()`, and a process-level
+ `unhandledRejection` backstop logs (instead of crashing) anything that still slips through. A transient
+ DB hiccup on the busy message path can no longer drop the event silently or take the process down.
+- **Audit-log writes are best-effort.** A failed audit insert is logged and swallowed instead of turning
+ an otherwise-successful operation (create/delete/start/stop session, etc.) into a `500`.
+
## [0.2.8] - 2026-06-17
The engine-pluggability release: the whatsapp-web.js delivery-ack, message-type, and JID specifics are
diff --git a/src/main.ts b/src/main.ts
index 061ef4cb3..6420ff91c 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -13,6 +13,7 @@ import {
} from './config/bootstrap-security';
import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';
import { AuthService } from './modules/auth/auth.service';
+import { createLogger } from './common/services/logger.service';
import { Request, Response, NextFunction, json, urlencoded } from 'express';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
@@ -75,6 +76,14 @@ STORAGE_PATH=./data/media
}
async function bootstrap() {
+ // Backstop for promise rejections that escaped a local handler (e.g. a fire-and-forget engine-event
+ // dispatch). Node terminates the process on an unhandled rejection by default; for a long-running
+ // self-hosted gateway we'd rather log it and stay up than let one stray rejection kill all sessions.
+ const bootstrapLogger = createLogger('Bootstrap');
+ process.on('unhandledRejection', (reason: unknown) => {
+ bootstrapLogger.error('Unhandled promise rejection', reason instanceof Error ? reason.stack : String(reason));
+ });
+
// Fail fast: never start production with default/placeholder secrets.
assertNoDefaultSecretsInProduction({
nodeEnv: process.env.NODE_ENV,
diff --git a/src/modules/audit/audit.service.ts b/src/modules/audit/audit.service.ts
index cc4a85cb1..3fff6ec2b 100644
--- a/src/modules/audit/audit.service.ts
+++ b/src/modules/audit/audit.service.ts
@@ -3,6 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Between, LessThan } from 'typeorm';
import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entity';
import { ApiKey } from '../auth/entities/api-key.entity';
+import { createLogger } from '../../common/services/logger.service';
interface AuditContext {
apiKey?: ApiKey;
@@ -30,6 +31,8 @@ export interface AuditQueryOptions {
@Injectable()
export class AuditService {
+ private readonly logger = createLogger('AuditService');
+
constructor(
@InjectRepository(AuditLog, 'main')
private readonly auditRepository: Repository<AuditLog>,
@@ -39,7 +42,7 @@ export class AuditService {
action: AuditAction,
context: AuditContext = {},
severity: AuditSeverity = AuditSeverity.INFO,
- ): Promise<AuditLog> {
+ ): Promise<AuditLog | null> {
const auditLog = this.auditRepository.create({
action,
severity,
@@ -56,18 +59,29 @@ export class AuditService {
errorMessage: context.errorMessage || null,
});
- return this.auditRepository.save(auditLog);
+ // Audit logging is best-effort: a failed insert must never turn a succeeded operation into a 500
+ // (callers await this after the primary side-effect). Log and swallow.
+ try {
+ return await this.auditRepository.save(auditLog);
+ } catch (error) {
+ this.logger.error(
+ `Failed to write audit log for ${String(action)}`,
+ error instanceof Error ? error.stack : String(error),
+ { action: String(action) },
+ );
+ return null;
+ }
}
- async logInfo(action: AuditAction, context: AuditContext = {}): Promise<AuditLog> {
+ async logInfo(action: AuditAction, context: AuditContext = {}): Promise<AuditLog | null> {
return this.log(action, context, AuditSeverity.INFO);
}
- async logWarn(action: AuditAction, context: AuditContext = {}): Promise<AuditLog> {
+ async logWarn(action: AuditAction, context: AuditContext = {}): Promise<AuditLog | null> {
return this.log(action, context, AuditSeverity.WARN);
}
- async logError(action: AuditAction, context: AuditContext = {}): Promise<AuditLog> {
+ async logError(action: AuditAction, context: AuditContext = {}): Promise<AuditLog | null> {
return this.log(action, context, AuditSeverity.ERROR);
}
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index af7d4aa06..b6485e696 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -437,7 +437,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
void this.webhookService.dispatch(id, 'message.received', finalMessage);
// Emit real-time event to WebSocket clients
this.eventsGateway.emitMessage(id, finalMessage);
- });
+ })
+ .catch(err => this.logger.error(`onMessage handler failed for ${id}`, String(err)));
},
onMessageCreate: (message): void => {
// `message_create` fires for every message the account creates, including sends composed on a
@@ -478,7 +479,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
void this.webhookService.dispatch(id, 'message.sent', finalMessage);
// Emit real-time event to WebSocket clients (as message.sent, not message.received)
this.eventsGateway.emitMessageSent(id, finalMessage);
- });
+ })
+ .catch(err => this.logger.error(`onMessageCreate handler failed for ${id}`, String(err)));
},
onMessageAck: (messageId, status: DeliveryStatus): void => {
this.logger.debug(`Message ack: ${messageId} -> ${status}`, {
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 8a73b7105..b89ddf9f2 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -243,6 +243,12 @@ describe('WebhookService', () => {
mockFetch.mockReset();
});
+ it('resolves (never rejects) when the webhook lookup fails — callers fire-and-forget it', async () => {
+ (repository.find as jest.Mock).mockRejectedValue(new Error('db down'));
+ await expect(service.dispatch('sess-1', 'message.received', { x: 1 })).resolves.toBeUndefined();
+ expect(mockFetch).not.toHaveBeenCalled();
+ });
+
it('should dispatch to webhooks matching the event', async () => {
const webhook = createMockWebhook({ events: ['message.received'] });
(repository.find as jest.Mock).mockResolvedValue([webhook]);
diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.ts
index 0ff33b14f..8eef241c2 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -191,9 +191,20 @@ export class WebhookService {
}
async dispatch(sessionId: string, event: string, data: Record<string, unknown>): Promise<void> {
- const webhooks = await this.webhookRepository.find({
- where: { sessionId, active: true },
- });
+ // Callers fire-and-forget this (`void dispatch(...)`), so a failure looking up webhooks must be
+ // logged and swallowed here — otherwise it surfaces as an unhandled promise rejection.
+ let webhooks: Webhook[];
+ try {
+ webhooks = await this.webhookRepository.find({
+ where: { sessionId, active: true },
+ });
+ } catch (error) {
+ this.logger.error(`Webhook dispatch lookup failed for ${event}`, String(error), {
+ sessionId,
+ action: 'webhook_dispatch_lookup_failed',
+ });
+ return;
+ }
const matchingWebhooks = webhooks.filter(w => w.events.includes(event) || w.events.includes('*'));