Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix: hardening batch 2 — webhook-failure retention, body-size cap, channel limit, adapter log labels (#640)
Yudhi Armyndharis287e14416dc1
diff --git a/.env.example b/.env.exampleindex aef2788be..17895b6bd 100644--- a/.env.example+++ b/.env.example@@ -180,6 +180,8 @@ S3_SECRET_ACCESS_KEY=WEBHOOK_TIMEOUT=10000 # Timeout in millisecondsWEBHOOK_MAX_RETRIES=3 # Number of retry attemptsWEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms+# Days to keep webhook delivery-failure records before pruning them (default 90; set <= 0 to disable).+# WEBHOOK_FAILURE_RETENTION_DAYS=90# Block outbound WEBHOOK deliveries to internal/reserved addresses (SSRF# protection). ON by default; set to "false" only on closed networks. When on,# webhook URLs resolving to loopback/private/link-local/metadata ranges arediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 121e84f6c..7bf94ece4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,9 +11,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Dashboard `<select>` elements replaced with a custom dropdown component.** The "All Status" filter (Sessions), "All Severities" filter (Logs), and language picker (Login) now use a reusable `CustomSelect` component that matches the dashboard design system with proper dark/light theming, keyboard navigation (arrows, Home/End, type-ahead, Escape), and responsive behavior. Focus returns to the trigger on close, matching native `<select>` semantics. Thanks @haseeblodhi1899.- The **"Install a plugin" modal is wider on desktop** (480px → 680px) to give the plugin catalog list more room, while still collapsing to a full-width bottom sheet on small screens.+- **Webhook delivery-failure records are pruned on a retention window.** `webhook_delivery_failures` is an append-only log written on every terminally-failed delivery, so under a receiver outage it grew without bound. It is now pruned to `WEBHOOK_FAILURE_RETENTION_DAYS` (default 90; set `<= 0` to disable) once at startup and daily, mirroring the existing audit-log retention.### Fixed+- **Baileys API sends now emit `message.sent`** (parity with the whatsapp-web.js engine). The wwjs engine fires this for the account's own sends; the Baileys engine's own socket-sends echo back only as a skipped history-sync upsert, so `message.sent` webhooks / WebSocket events / the `message:sent` hook never fired for Baileys API sends. They now fire for text and every media/location/contact/poll/reply/forward send (reactions and deletes excluded).+- **Config & reliability hardening.** `DATABASE_STATEMENT_TIMEOUT_MS`, `DATABASE_IDLE_TIMEOUT_MS`, and `DATABASE_CONNECTION_TIMEOUT_MS` are validated at boot — a typo previously reached the config layer as `NaN` and broke the PostgreSQL pool. An unparseable `BODY_SIZE_LIMIT` no longer silently disables the request body-size cap (it falls back to the 25 MB default). The channel-messages endpoint no longer forwards `NaN` to the engine on a non-numeric `?limit`. The fire-and-forget session-row writes in the engine callbacks now handle a transient DB fault instead of surfacing an unhandled rejection, and a set of engine-adapter warning logs no longer mislabel their component name.- **A terminally-failed or un-reinitializable session no longer strands its browser process or wedges at "already started".** When an engine reports a terminal error, and when a reconnect attempt's re-initialization throws, the dead or half-built engine is now evicted from the session registry and its Chromium process is force-killed instead of being left in place — previously it kept holding a concurrency slot and caused a later start to be rejected as already running. Deleting a session likewise force-kills its browser (rather than a graceful close that could hang on a wedged Chromium and orphan the process).- **The dark theme now covers every dashboard surface.** A number of components used hardcoded colors instead of the theme's CSS variables, so several surfaces stayed light in dark mode — most visibly the Infrastructure "Database Migrations" card, plus status/severity badges, toasts, danger-hover states, and toggle tracks across most pages. They now use the theme tokens (and translucent semantic fills) so they follow the active theme in both light and dark. A new `--info` token themes the blue badges (permission, SQLite, info logs, qr-ready pill) that previously had no theme-aware color, and the root `<html>` background no longer stays white when the dark theme is selected on a light-OS device (visible on overscroll).diff --git a/src/config/bootstrap-security.spec.ts b/src/config/bootstrap-security.spec.tsindex 320a44420..bc678c353 100644--- a/src/config/bootstrap-security.spec.ts+++ b/src/config/bootstrap-security.spec.ts@@ -90,6 +90,16 @@ describe('resolveBodyLimit', () => {it('honors an explicit limit', () => {expect(resolveBodyLimit('5mb')).toBe('5mb');});+ it('falls back to the default for a value the body-size parser cannot understand (which would silently disable the cap)', () => {+ expect(resolveBodyLimit('unlimited')).toBe('25mb');+ expect(resolveBodyLimit('none')).toBe('25mb');+ expect(resolveBodyLimit('abc')).toBe('25mb');+ });+ it('still honors valid numeric/unit limits, preserving case and unit', () => {+ expect(resolveBodyLimit('10MB')).toBe('10MB');+ expect(resolveBodyLimit('1024')).toBe('1024');+ expect(resolveBodyLimit('1.5gb')).toBe('1.5gb');+ });});describe('assertNoDefaultSecretsInProduction', () => {diff --git a/src/config/bootstrap-security.ts b/src/config/bootstrap-security.tsindex 2da78bd9f..08f015ed4 100644--- a/src/config/bootstrap-security.ts+++ b/src/config/bootstrap-security.ts@@ -57,10 +57,16 @@ export function isUpgradeInsecureRequestsEnabled(cspEnv?: string, nodeEnv?: strireturn nodeEnv === 'production';}-/** Request body-size cap (DoS hardening). Default is media-aware (base64 sends ride in the JSON body). */+/**+ * Request body-size cap (DoS hardening). Default is media-aware (base64 sends ride in the JSON body).+ * A value the body-size parser can't understand (e.g. 'unlimited', 'none', a typo) resolves to a null+ * limit downstream, which SILENTLY DISABLES the cap — so an unparseable value falls back to the default+ * instead. Accepts a positive number with an optional bytes unit (b/kb/mb/gb/tb/pb).+ */+const BODY_LIMIT_PATTERN = /^\d+(\.\d+)?\s?(b|kb|mb|gb|tb|pb)?$/i;export function resolveBodyLimit(bodySizeEnv?: string): string {const trimmed = bodySizeEnv?.trim();- return trimmed ? trimmed : '25mb';+ return trimmed && BODY_LIMIT_PATTERN.test(trimmed) ? trimmed : '25mb';}/** Known weak/default/placeholder secret values that must never reach production. */diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex fa35e935e..f47950e0f 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -515,7 +515,7 @@ export class BaileysAdapter implements IWhatsAppEngine {// Presence is best-effort — a failure here must never surface as a 500 on the direct typing// endpoint or MCP tool (mirrors the whatsapp-web.js adapter; #583 R4). A migrated contact can// yield `No LID for user` on the presence path even when the actual send succeeds.- this.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, String(error));+ this.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, { error: String(error) });}}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex b0216ce0d..b126413e9 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -712,7 +712,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginprivate async clearLocalAuth(): Promise<void> {const dir = path.join(path.resolve(this.config.sessionDataPath), `session-${this.config.sessionId}`);await fs.promises.rm(dir, { recursive: true, force: true }).catch((error: unknown) => {- this.logger.warn(`Could not clear stale auth at ${dir}`, String(error));+ this.logger.warn(`Could not clear stale auth at ${dir}`, { error: String(error) });});}@@ -763,7 +763,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// This allows reconnecting without needing to scan QR againawait client.destroy();} catch (error) {- this.logger.warn('Destroy client failed:', String(error));+ this.logger.warn('Destroy client failed:', { error: String(error) });// Already destroyed or not initialized - ignore} finally {this.finishClientTeardown(client);@@ -778,12 +778,12 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// Logout clears session data - user will need to scan QR againawait client.logout();} catch (error) {- this.logger.warn('Logout failed:', String(error));+ this.logger.warn('Logout failed:', { error: String(error) });// Fall back to destroy if logout failstry {await client.destroy();} catch (destroyError) {- this.logger.warn('Client destroy also failed during logout fallback', String(destroyError));+ this.logger.warn('Client destroy also failed during logout fallback', { error: String(destroyError) });}} finally {this.finishClientTeardown(client);@@ -1023,7 +1023,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginisBlocked: contact.isBlocked,};} catch (error) {- this.logger.warn(`Failed to get contact: ${contactId}`, String(error));+ this.logger.warn(`Failed to get contact: ${contactId}`, { error: String(error) });return null;}}@@ -1260,7 +1260,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginlinkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};} catch (error) {- this.logger.warn(`Failed to get group: ${groupId}`, String(error));+ this.logger.warn(`Failed to get group: ${groupId}`, { error: String(error) });return null;}}@@ -1845,7 +1845,7 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin// Presence is best-effort and already swallowed here — it never breaks the surrounding send —// so log at WARN, not ERROR: a migrated contact routinely yields `No LID for user` on the// presence path and an ERROR line reads as a fault when nothing actually failed (#582).- this.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, String(error));+ this.logger.warn(`Could not set chat state '${state}' for ${chatId} (best-effort)`, { error: String(error) });}}diff --git a/src/modules/channel/channel.controller.spec.ts b/src/modules/channel/channel.controller.spec.tsnew file mode 100644index 000000000..5b8e5a1f7--- /dev/null+++ b/src/modules/channel/channel.controller.spec.ts@@ -0,0 +1,28 @@+import { ChannelController } from './channel.controller';+import { ChannelService } from './channel.service';++describe('ChannelController.getMessages limit parsing', () => {+ const build = () => {+ const service = { getChannelMessages: jest.fn().mockResolvedValue([]) };+ const controller = new ChannelController(service as unknown as ChannelService);+ return { controller, service };+ };++ it('falls back to the engine default (undefined) when ?limit is not numeric — never forwards NaN', async () => {+ const { controller, service } = build();+ await controller.getMessages('s1', 'ch1@newsletter', 'abc');+ expect(service.getChannelMessages).toHaveBeenCalledWith('s1', 'ch1@newsletter', undefined);+ });++ it('forwards a valid numeric limit unchanged', async () => {+ const { controller, service } = build();+ await controller.getMessages('s1', 'ch1@newsletter', '25');+ expect(service.getChannelMessages).toHaveBeenCalledWith('s1', 'ch1@newsletter', 25);+ });++ it('forwards undefined when ?limit is omitted (engine default)', async () => {+ const { controller, service } = build();+ await controller.getMessages('s1', 'ch1@newsletter', undefined);+ expect(service.getChannelMessages).toHaveBeenCalledWith('s1', 'ch1@newsletter', undefined);+ });+});diff --git a/src/modules/channel/channel.controller.ts b/src/modules/channel/channel.controller.tsindex 7a33f58a5..185d20f74 100644--- a/src/modules/channel/channel.controller.ts+++ b/src/modules/channel/channel.controller.ts@@ -49,7 +49,10 @@ export class ChannelController {@Param('channelId') channelId: string,@Query('limit') limit?: string,) {- return this.channelService.getChannelMessages(sessionId, channelId, limit ? parseInt(limit, 10) : undefined);+ // A non-empty non-numeric ?limit (e.g. `?limit=abc`) is truthy, so a bare `parseInt` would forward+ // NaN to the engine (wwjs then returns an unpredictable/empty set). Fall back to the engine default.+ const parsed = limit !== undefined ? parseInt(limit, 10) : NaN;+ return this.channelService.getChannelMessages(sessionId, channelId, Number.isNaN(parsed) ? undefined : parsed);}@Post('subscribe')diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 9d38574a7..15042e4d2 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -68,6 +68,7 @@ describe('WebhookService', () => {failureRepository = {insert: jest.fn().mockResolvedValue({}),find: jest.fn().mockResolvedValue([]),+ delete: jest.fn().mockResolvedValue({ affected: 0 }),};configService = {@@ -267,6 +268,40 @@ describe('WebhookService', () => {// ── dispatch (direct mode — queue disabled) ───────────────────────+ describe('delivery-failure retention', () => {+ afterEach(() => service.onModuleDestroy());++ it('pruneDeliveryFailures deletes rows older than the retention window and returns the count', async () => {+ (failureRepository.delete as jest.Mock).mockResolvedValue({ affected: 3 });+ await expect(service.pruneDeliveryFailures(90)).resolves.toBe(3);+ expect(failureRepository.delete).toHaveBeenCalledTimes(1);+ });++ it('onModuleInit skips scheduling when WEBHOOK_FAILURE_RETENTION_DAYS <= 0 (retention disabled)', () => {+ const prev = process.env.WEBHOOK_FAILURE_RETENTION_DAYS;+ process.env.WEBHOOK_FAILURE_RETENTION_DAYS = '0';+ try {+ service.onModuleInit();+ expect(failureRepository.delete).not.toHaveBeenCalled();+ } finally {+ if (prev === undefined) delete process.env.WEBHOOK_FAILURE_RETENTION_DAYS;+ else process.env.WEBHOOK_FAILURE_RETENTION_DAYS = prev;+ }+ });++ it('onModuleInit prunes once at startup when retention is enabled', () => {+ const prev = process.env.WEBHOOK_FAILURE_RETENTION_DAYS;+ process.env.WEBHOOK_FAILURE_RETENTION_DAYS = '30';+ try {+ service.onModuleInit();+ expect(failureRepository.delete).toHaveBeenCalledTimes(1);+ } finally {+ if (prev === undefined) delete process.env.WEBHOOK_FAILURE_RETENTION_DAYS;+ else process.env.WEBHOOK_FAILURE_RETENTION_DAYS = prev;+ }+ });+ });+describe('dispatch (direct mode)', () => {const mockFetch = undiciFetch as jest.Mock;diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 148b498f9..28c16f65f 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -1,6 +1,13 @@-import { Injectable, NotFoundException, Optional, BadRequestException } from '@nestjs/common';+import {+ Injectable,+ NotFoundException,+ Optional,+ BadRequestException,+ OnModuleInit,+ OnModuleDestroy,+} from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { FindManyOptions, In, Repository } from 'typeorm';+import { FindManyOptions, In, LessThan, Repository } from 'typeorm';import { ConfigService } from '@nestjs/config';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';@@ -46,9 +53,10 @@ export interface WebhookJobData {}@Injectable()-export class WebhookService {+export class WebhookService implements OnModuleInit, OnModuleDestroy {private readonly logger = createLogger('WebhookService');private readonly queueEnabled: boolean;+ private cleanupTimer?: ReturnType<typeof setInterval>;constructor(@InjectRepository(Webhook, 'data')@@ -66,6 +74,49 @@ export class WebhookService {this.queueEnabled = configService.get<boolean>('queue.enabled', false);}+ /**+ * Periodically prune webhook_delivery_failures older than WEBHOOK_FAILURE_RETENTION_DAYS+ * (default 90; set <= 0 to disable). Runs once at startup, then daily. The table is an append-only+ * log written on every terminally-failed delivery, so without this it grows without bound under a+ * receiver outage. (Mirrors AuditService's audit-log retention.)+ */+ onModuleInit(): void {+ const parsed = Number.parseInt(process.env.WEBHOOK_FAILURE_RETENTION_DAYS ?? '', 10);+ const retentionDays = Number.isInteger(parsed) ? Math.max(0, parsed) : 90;+ if (retentionDays <= 0) {+ this.logger.log('Webhook delivery-failure retention disabled (WEBHOOK_FAILURE_RETENTION_DAYS <= 0)');+ return;+ }+ const runPrune = (): void => {+ this.pruneDeliveryFailures(retentionDays)+ .then(n => {+ if (n > 0) this.logger.log(`Pruned ${n} webhook delivery-failure(s) older than ${retentionDays} day(s)`);+ })+ .catch(err =>+ this.logger.error('Webhook delivery-failure cleanup failed', err instanceof Error ? err.stack : String(err)),+ );+ };+ runPrune(); // prune once at startup+ this.cleanupTimer = setInterval(runPrune, 24 * 60 * 60 * 1000);+ this.cleanupTimer.unref?.();+ }++ onModuleDestroy(): void {+ if (this.cleanupTimer) {+ clearInterval(this.cleanupTimer);+ }+ }++ /**+ * Delete delivery-failure rows older than the retention window. Returns the number removed.+ */+ async pruneDeliveryFailures(olderThanDays: number): Promise<number> {+ const cutoff = new Date();+ cutoff.setDate(cutoff.getDate() - olderThanDays);+ const result = await this.failureRepository.delete({ createdAt: LessThan(cutoff) });+ return result.affected || 0;+ }+/*** Reject an internal/unsafe webhook URL at registration, so a bad URL fails* synchronously with a 400 instead of silently failing at delivery time. Honors the same