Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
Merge PR #285: error-handling hardening (non-rejecting dispatch, hook .catch, unhandledRejection backstop, best-effort audit)
rmyndharis1122513394e0
diff --cc CHANGELOG.mdindex 7e1b26269,744f25024..1e18ac034--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,43 -7,15 +7,50 @@@ and this project adheres to [Semantic V## [Unreleased]+### Security++- **Write endpoints for groups, contacts, labels, channels, catalog, and status now require the+ `OPERATOR` role**, closing an unintended privilege gap where a `VIEWER`-role API key could create/leave+ groups, manage participants, block contacts, post statuses, send products, and mutate labels. Read+ (`GET`) endpoints remain open to any valid key, matching the message/session controllers.+ > ⚠️ If you used a `VIEWER` key for any of these write operations, switch it to `OPERATOR` (or `ADMIN`).+- Patched a high-severity `ws` advisory (and a moderate `qs` DoS) on the live socket.io transport by+ bumping in-range deps (`ws`→8.21.0, `engine.io`→6.6.9, `qs`→6.15.2, plus the incidental+ re-resolutions `npm audit fix` pulled in) in both the API and dashboard. Lockfile-only — no+ `package.json`/API change. The remaining advisories are build-only (`sqlite3`→`node-gyp`→`tar`)+ and require a breaking `sqlite3` major, deferred.++### Added++- **`LOG_LEVEL` is now honored.** It was read into config/compose but never applied (logging was hardcoded+ to `info`); the level (`error`/`warn`/`info`/`debug`/`verbose`) is now set at bootstrap.+- **Automatic audit-log retention.** Audit logs older than `AUDIT_RETENTION_DAYS` (default 90; `0` disables)+ are pruned daily and once at startup — the existing `cleanup()` was never scheduled, so `audit_logs` grew+ without bound.+### Fixed+- **Bulk-message batch status is now correct on cancel and stop-on-error.** A cancelled batch could be+ silently reverted to `PROCESSING` (the final save overwrote the `CANCELLED` status with the stale+ in-memory one), and a `stopOnError` abort was reported as `COMPLETED` whenever at least one message had+ already been sent. The terminal status is now re-derived (cancelled → `CANCELLED` with reconciled+ counters; stop-on-error → `FAILED`; otherwise `COMPLETED`/`FAILED`).+- Bulk-message item `type` is now validated against the allowed set (`text`/`image`/`video`/`audio`/`document`)+ with `@IsIn`, so an invalid type is rejected up front instead of failing mid-send.+- **Graceful shutdown is now robust.** `onModuleDestroy` clears reconnect timers first and destroys engines+ in parallel, each isolated and time-bounded — so one hung/throwing Chromium can no longer abort teardown+ of the other sessions or stall shutdown.+- **A session that exhausts its reconnect attempts is now marked `FAILED` with a reason** (surfaced via+ `lastError`) instead of sitting silently `DISCONNECTED` forever.+- **BullMQ webhook jobs are auto-evicted** (`removeOnComplete`/`removeOnFail` retention) so completed/failed+ job payloads no longer accumulate unbounded in Redis (audit M19).+ - **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-17diff --cc src/main.tsindex 8b688b648,6420ff91c..f52956a87--- a/src/main.ts+++ b/src/main.ts@@@ -4,7 -4,6 +4,7 @@@ import { SwaggerModule } from '@nestjs/import helmet from 'helmet';import { AppModule } from './app.module';import { ShutdownService } from './common/services/shutdown.service';- import { LoggerService, LogLevel } from './common/services/logger.service';++import { LoggerService, LogLevel, createLogger } from './common/services/logger.service';import { createSwaggerConfig } from './config/swagger.config';import {resolveCorsPolicy,@@@ -76,12 -76,14 +76,20 @@@ STORAGE_PATH=./data/medi}async function bootstrap() {+ // Apply the operator-configured log verbosity (LOG_LEVEL) before anything logs. Unset/invalid → INFO.+ const requestedLevel = process.env.LOG_LEVEL?.trim().toLowerCase();+ if (requestedLevel && (Object.values(LogLevel) as string[]).includes(requestedLevel)) {+ LoggerService.setLogLevel(requestedLevel as LogLevel);+ }++ // 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,