Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(hardening): audit key lifecycle, de-dup WS status, concurrent webhook dispatch (#546)

Yudhi Armyndharis5c42b3944485
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 42134c77e..b0a0f52b9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security
+
+- **API-key lifecycle operations are now recorded in the audit log.** Creating, deleting, and revoking an API key previously left no audit entry (only failed authentication was logged). Each now writes an `api_key_created` / `api_key_deleted` / `api_key_revoked` event with the acting admin key, the client IP, and the target key — giving administrators a forensic trail for credential management. (#546)
+
+### Fixed
+
+- **A session status change is no longer broadcast twice over WebSocket.** Some engines signal one transition through both a generic state callback and a dedicated one; the WebSocket `session.status` emit is now de-duplicated the same way the webhook dispatch already was, so connected dashboards receive one event per transition. (#546)
+- **A slow webhook receiver no longer delays delivery to the others.** When the queue is disabled (or a queue add fails and falls back to direct delivery), the webhooks matching one event are now dispatched concurrently instead of sequentially, so one hanging or retrying endpoint can't head-of-line-block delivery to its siblings. (#546)
### Fixed
- **A plugin's stored secret array is no longer wiped when its length changes.** When a plugin config had a list of secret values (e.g. API keys), adding or removing an entry from the dashboard sent every other value back as the masked sentinel; on save, the merge couldn't position-match them and silently dropped all of them. Surviving entries now keep their stored secret across an append or removal, while a genuinely-new or edited row is still never grafted with a stored value. (#544)
diff --git a/src/modules/auth/auth.controller.spec.ts b/src/modules/auth/auth.controller.spec.ts
new file mode 100644
index 000000000..2036952d3
--- /dev/null
+++ b/src/modules/auth/auth.controller.spec.ts
@@ -0,0 +1,68 @@
+import type { Request } from 'express';
+import { AuthController } from './auth.controller';
+import { AuditAction } from '../audit/entities/audit-log.entity';
+import type { ApiKey } from './entities/api-key.entity';
+import type { AuthService } from './auth.service';
+import type { AuditService } from '../audit/audit.service';
+
+// API-key lifecycle operations (create / delete / revoke) must leave an audit trail — they were
+// previously unrecorded. These assert the controller emits the matching audit action with the acting
+// admin key, the resolved client IP, and the target key in metadata.
+describe('AuthController — API-key lifecycle audit logging', () => {
+ const actor = { id: 'admin-key', name: 'admin' } as unknown as ApiKey;
+ const makeReq = (): Request =>
+ ({ method: 'POST', path: '/auth/api-keys', clientIp: '203.0.113.7' }) as unknown as Request;
+
+ let authService: { createApiKey: jest.Mock; findOne: jest.Mock; delete: jest.Mock; revoke: jest.Mock };
+ let auditService: { logInfo: jest.Mock };
+ let controller: AuthController;
+
+ beforeEach(() => {
+ const createdKey = {
+ id: 'k1',
+ name: 'new-key',
+ role: 'user',
+ keyPrefix: 'ow_',
+ isActive: true,
+ usageCount: 0,
+ createdAt: new Date(),
+ };
+ authService = {
+ createApiKey: jest.fn().mockResolvedValue({ apiKey: createdKey, rawKey: 'raw-secret' }),
+ findOne: jest.fn().mockResolvedValue({ id: 'k1', name: 'target-key' }),
+ delete: jest.fn().mockResolvedValue(undefined),
+ revoke: jest.fn().mockResolvedValue({ ...createdKey, isActive: false }),
+ };
+ auditService = { logInfo: jest.fn().mockResolvedValue(null) };
+ controller = new AuthController(authService as unknown as AuthService, auditService as unknown as AuditService);
+ });
+
+ const lastContextFor = (
+ action: AuditAction,
+ ): { apiKey?: ApiKey; ipAddress?: string; metadata?: { targetKeyId?: string } } | undefined => {
+ const calls = auditService.logInfo.mock.calls as Array<
+ [AuditAction, { apiKey?: ApiKey; ipAddress?: string; metadata?: { targetKeyId?: string } }]
+ >;
+ return calls.find(c => c[0] === action)?.[1];
+ };
+
+ it('logs API_KEY_CREATED on create, with the acting key, IP, and target id', async () => {
+ await controller.create({ name: 'new-key' }, makeReq(), actor);
+ const ctx = lastContextFor(AuditAction.API_KEY_CREATED);
+ expect(ctx).toBeDefined();
+ expect(ctx?.apiKey).toBe(actor);
+ expect(ctx?.ipAddress).toBe('203.0.113.7');
+ expect(ctx?.metadata?.targetKeyId).toBe('k1');
+ });
+
+ it('logs API_KEY_DELETED on delete', async () => {
+ await controller.delete('k1', makeReq(), actor);
+ expect(authService.delete).toHaveBeenCalledWith('k1');
+ expect(lastContextFor(AuditAction.API_KEY_DELETED)?.metadata?.targetKeyId).toBe('k1');
+ });
+
+ it('logs API_KEY_REVOKED on revoke', async () => {
+ await controller.revoke('k1', makeReq(), actor);
+ expect(lastContextFor(AuditAction.API_KEY_REVOKED)?.metadata?.targetKeyId).toBe('k1');
+ });
+});
diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts
index dc157802d..7d7704b5b 100644
--- a/src/modules/auth/auth.controller.ts
+++ b/src/modules/auth/auth.controller.ts
@@ -1,14 +1,34 @@
-import { Controller, Get, Post, Put, Delete, Body, Param, HttpCode, HttpStatus } from '@nestjs/common';
+import { Controller, Get, Post, Put, Delete, Body, Param, Req, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
+import type { Request } from 'express';
import { AuthService } from './auth.service';
import { CreateApiKeyDto, UpdateApiKeyDto, ApiKeyResponseDto, ApiKeyCreatedResponseDto } from './dto';
-import { RequireRole } from './decorators/auth.decorators';
-import { ApiKeyRole } from './entities/api-key.entity';
+import { RequireRole, CurrentApiKey } from './decorators/auth.decorators';
+import { type ApiKey, ApiKeyRole } from './entities/api-key.entity';
+import { AuditService } from '../audit/audit.service';
+import { AuditAction } from './../audit/entities/audit-log.entity';
@ApiTags('auth')
@Controller('auth/api-keys')
export class AuthController {
- constructor(private readonly authService: AuthService) {}
+ constructor(
+ private readonly authService: AuthService,
+ private readonly auditService: AuditService,
+ ) {}
+
+ // Build the request-context block for an API-key lifecycle audit entry: who did it (the admin key from
+ // the guard), the resolved client IP, and the HTTP method/path.
+ private auditContext(
+ req: Request,
+ actor?: ApiKey,
+ ): { apiKey?: ApiKey; ipAddress?: string; method?: string; path?: string } {
+ return {
+ apiKey: actor,
+ ipAddress: (req as Request & { clientIp?: string }).clientIp ?? undefined,
+ method: req.method,
+ path: req.path,
+ };
+ }
@Post()
@RequireRole(ApiKeyRole.ADMIN)
@@ -18,8 +38,16 @@ export class AuthController {
description: 'API key created',
type: ApiKeyCreatedResponseDto,
})
- async create(@Body() dto: CreateApiKeyDto): Promise<ApiKeyCreatedResponseDto> {
+ async create(
+ @Body() dto: CreateApiKeyDto,
+ @Req() req: Request,
+ @CurrentApiKey() actor?: ApiKey,
+ ): Promise<ApiKeyCreatedResponseDto> {
const { apiKey, rawKey } = await this.authService.createApiKey(dto);
+ await this.auditService.logInfo(AuditAction.API_KEY_CREATED, {
+ ...this.auditContext(req, actor),
+ metadata: { targetKeyId: apiKey.id, targetKeyName: apiKey.name, role: apiKey.role },
+ });
return {
id: apiKey.id,
name: apiKey.name,
@@ -104,16 +132,29 @@ export class AuthController {
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Delete API key (admin only)' })
@ApiResponse({ status: 204, description: 'API key deleted' })
- async delete(@Param('id') id: string): Promise<void> {
+ async delete(@Param('id') id: string, @Req() req: Request, @CurrentApiKey() actor?: ApiKey): Promise<void> {
+ const target = await this.authService.findOne(id);
await this.authService.delete(id);
+ await this.auditService.logInfo(AuditAction.API_KEY_DELETED, {
+ ...this.auditContext(req, actor),
+ metadata: { targetKeyId: id, targetKeyName: target?.name },
+ });
}
@Post(':id/revoke')
@RequireRole(ApiKeyRole.ADMIN)
@ApiOperation({ summary: 'Revoke API key (admin only)' })
@ApiResponse({ status: 200, type: ApiKeyResponseDto })
- async revoke(@Param('id') id: string): Promise<ApiKeyResponseDto> {
+ async revoke(
+ @Param('id') id: string,
+ @Req() req: Request,
+ @CurrentApiKey() actor?: ApiKey,
+ ): Promise<ApiKeyResponseDto> {
const k = await this.authService.revoke(id);
+ await this.auditService.logInfo(AuditAction.API_KEY_REVOKED, {
+ ...this.auditContext(req, actor),
+ metadata: { targetKeyId: k.id, targetKeyName: k.name },
+ });
return {
id: k.id,
name: k.name,
diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.ts
index b5eec09f1..c69ca0038 100644
--- a/src/modules/auth/guards/api-key.guard.ts
+++ b/src/modules/auth/guards/api-key.guard.ts
@@ -78,6 +78,9 @@ export class ApiKeyGuard implements CanActivate {
// Attach API key to request for use in controllers
(request as Request & { apiKey: typeof apiKey }).apiKey = apiKey;
+ // Expose the trusted-proxy-aware client IP so controllers (e.g. the audit trail on key lifecycle
+ // ops) reuse the already-resolved value instead of re-deriving it.
+ (request as Request & { clientIp?: string }).clientIp = clientIp;
return true;
}
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 9aab4e6dd..c48de3283 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1459,6 +1459,19 @@ describe('SessionService', () => {
expect(qrStatus).toHaveLength(1);
});
+ it('does not double-EMIT session.status over WS when the same status is reported twice', async () => {
+ const callbacks = await startAndCaptureCallbacks();
+ (eventsGateway.emitSessionStatus as jest.Mock).mockClear();
+ callbacks.onStateChanged!(EngineStatus.QR_READY);
+ callbacks.onQRCode!('qr-data-abc'); // same QR_READY transition, second signal
+ await flush();
+
+ const qrEmits = ((eventsGateway.emitSessionStatus as jest.Mock).mock.calls as unknown[][]).filter(
+ c => c[1] === SessionStatus.QR_READY,
+ );
+ expect(qrEmits).toHaveLength(1);
+ });
+
it('persists and dispatches message.received only once when the engine re-fires the same message', async () => {
const callbacks = await startAndCaptureCallbacks();
(messageRepository.insert as jest.Mock).mockReset();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 481042174..6705cf371 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -110,9 +110,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// Reconnection state per session
private reconnectStates: Map<string, ReconnectState> = new Map();
- // Last session.status value dispatched to webhooks per session. Some engines signal one transition
- // via BOTH onStateChanged and a dedicated callback (onQRCode/onDisconnected), so this guards the
- // webhook POST against firing the same status twice. Cleared on delete().
+ // Last session.status value broadcast per session. Some engines signal one transition via BOTH
+ // onStateChanged and a dedicated callback (onQRCode/onDisconnected), so this guards both the WS emit
+ // and the webhook POST against firing the same status twice. Cleared on delete().
private readonly lastDispatchedStatus = new Map<string, SessionStatus>();
// Sessions currently being stopped/deleted. An in-flight executeReconnect awaits
@@ -1346,13 +1346,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
status,
action: 'status_update',
});
- // Emit real-time event to connected WebSocket clients
- this.eventsGateway.emitSessionStatus(id, status);
- // Mirror the status change to subscribed webhooks. Some engines signal one transition via both
- // onStateChanged AND a dedicated callback (onQRCode/onDisconnected), which would POST the same
- // status twice — dispatch only when the status actually changed from the last one we sent.
+ // Mirror the status change to WS clients AND subscribed webhooks — both de-duped. Some engines signal
+ // one transition via both onStateChanged AND a dedicated callback (onQRCode/onDisconnected), which
+ // would otherwise emit/POST the same status twice; only act when it actually changed from the last one.
if (this.lastDispatchedStatus.get(id) !== status) {
this.lastDispatchedStatus.set(id, status);
+ this.eventsGateway.emitSessionStatus(id, status);
void this.webhookService.dispatch(id, 'session.status', { sessionId: id, status });
}
}
diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.ts
index 2fec1d631..6f589751f 100644
--- a/src/modules/webhook/webhook.service.spec.ts
+++ b/src/modules/webhook/webhook.service.spec.ts
@@ -319,6 +319,35 @@ describe('WebhookService', () => {
timeoutSpy.mockRestore();
});
+ it('dispatches to sibling webhooks concurrently — a slow receiver does not block the others', async () => {
+ const wA = createMockWebhook({ id: 'wh-a', url: 'https://a.example/hook', events: ['message.received'] });
+ const wB = createMockWebhook({ id: 'wh-b', url: 'https://b.example/hook', events: ['message.received'] });
+ (repository.find as jest.Mock).mockResolvedValue([wA, wB]);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (hookManager.execute as jest.Mock).mockResolvedValue({ continue: true, data: {} });
+
+ let resolveSlow: (v: unknown) => void = () => undefined;
+ const slow = new Promise(r => (resolveSlow = r));
+ const calledUrls: string[] = [];
+ mockFetch.mockImplementation((url: string) => {
+ calledUrls.push(url);
+ return url.includes('a.example') ? slow : Promise.resolve({ ok: true, status: 200 });
+ });
+
+ const dispatchP = service.dispatch('sess-1', 'message.received', { from: '[email protected]' });
+ // Flush until both fetches fire (or give up): with the old sequential loop, only A ever fires while
+ // it hangs, so this exhausts and the assertion below fails — exactly the regression we guard.
+ for (let i = 0; i < 20 && calledUrls.length < 2; i++) {
+ await new Promise(r => setImmediate(r));
+ }
+
+ // B is delivered even though A is still hanging — sequential code would not have reached B yet.
+ expect(calledUrls).toEqual(expect.arrayContaining(['https://a.example/hook', 'https://b.example/hook']));
+
+ resolveSlow({ ok: true, status: 200 });
+ await dispatchP;
+ });
+
it('falls back to the original payload when a before-hook omits payload (no undefined body)', 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 29169ef16..cce74dde0 100644
--- a/src/modules/webhook/webhook.service.ts
+++ b/src/modules/webhook/webhook.service.ts
@@ -246,8 +246,10 @@ export class WebhookService {
const occurredAt = new Date().toISOString();
const idempotencyKey = generateIdempotencyKey(event, { ...data, sessionId }, occurredAt);
- // Dispatch to all matching webhooks
- for (const webhook of matchingWebhooks) {
+ // Dispatch to all matching webhooks concurrently — one slow/hanging receiver must not head-of-line-
+ // block delivery to the sibling webhooks of the same event (the direct/fallback paths await a
+ // recursive retry with backoff sleeps).
+ const tasks = matchingWebhooks.map(async webhook => {
// Generate unique delivery ID for each webhook
const deliveryId = generateDeliveryId();
@@ -275,7 +277,7 @@ export class WebhookService {
webhookId: webhook.id,
action: 'webhook_cancelled_by_plugin',
});
- continue;
+ return;
}
// Use the plugin-modified payload, falling back to the original if a before-hook returned a
@@ -426,7 +428,8 @@ export class WebhookService {
});
}
}
- }
+ });
+ await Promise.allSettled(tasks);
}
/**