Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(integration): harden provisioning + ingress before release (#576)
Yudhi Armyndharis32b92c44e3ea
diff --git a/src/core/hooks/hook-manager.service.spec.ts b/src/core/hooks/hook-manager.service.spec.tsindex 919999f61..3d6fc2781 100644--- a/src/core/hooks/hook-manager.service.spec.ts+++ b/src/core/hooks/hook-manager.service.spec.ts@@ -2,7 +2,7 @@// so the no-await rule doesn't apply to them here./* eslint-disable @typescript-eslint/require-await */import { HookManager } from './hook-manager.service';-import { HookContext, HookResult } from './hook.interfaces';+import { HookContext, HookResult, HookEvent } from './hook.interfaces';describe('HookManager', () => {let hm: HookManager;@@ -185,3 +185,43 @@ describe('HookManager re-entrancy guard', () => {expect(seen).toEqual(['received', 'sent']);});});++describe('HookManager.isInFlight + selective re-entrancy guard (conversation.send pattern)', () => {+ const SENDING: HookEvent[] = ['message:sending'];++ it('isInFlight is false at the top level and true only inside a matching in-flight context', () => {+ const hm = new HookManager();+ expect(hm.isInFlight('message:sending')).toBe(false);+ let matching = false;+ let unrelated = false;+ hm.runInFlight(SENDING, () => {+ matching = hm.isInFlight('message:sending');+ unrelated = hm.isInFlight('message:received');+ });+ expect(matching).toBe(true);+ expect(unrelated).toBe(false);+ });++ it('a top-level guarded send still fires message:sending for unrelated observers; genuine re-entrancy suppresses it', async () => {+ const hm = new HookManager();+ let observerCalls = 0;+ hm.register('audit', 'message:sending', async ctx => {+ observerCalls++;+ return { continue: true, data: ctx.data };+ });+ // Mirrors the plugin-loader binding for ctx.conversations.send: guard ONLY on an already-in-flight event.+ const runGuarded = <T>(events: HookEvent[], run: () => Promise<T>): Promise<T> =>+ events.some(e => hm.isInFlight(e)) ? hm.runInFlight(events, run) : run();++ // Top-level send: an unrelated audit/moderation observer MUST see the outbound message:sending.+ await runGuarded(SENDING, () => hm.execute('message:sending', {}, { source: 'send' }));+ expect(observerCalls).toBe(1);++ // A send issued from WITHIN a message:sending handler's context (echo-loop) MUST be suppressed.+ observerCalls = 0;+ await hm.runInFlight(SENDING, () =>+ runGuarded(SENDING, () => hm.execute('message:sending', {}, { source: 'reentrant-send' })),+ );+ expect(observerCalls).toBe(0);+ });+});diff --git a/src/core/hooks/hook-manager.service.ts b/src/core/hooks/hook-manager.service.tsindex 6aae375dc..778736614 100644--- a/src/core/hooks/hook-manager.service.ts+++ b/src/core/hooks/hook-manager.service.ts@@ -119,6 +119,13 @@ export class HookManager {return this.inFlightEvents.run(merged, fn);}+ /** True if `event` is already in-flight on the active async context (an ancestor handler is running+ * it). Lets a caller wrap a capability in {@link runInFlight} ONLY for genuine re-entrancy, instead+ * of unconditionally seeding the event and suppressing it for unrelated observers on a top-level call. */+ isInFlight(event: HookEvent): boolean {+ return this.inFlightEvents.getStore()?.has(event) ?? false;+ }+private async runHandlers<T>(event: HookEvent,data: T,diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex 3099abb8b..8ac369ad0 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -294,6 +294,27 @@ describe('PluginLoaderService — uninstall', () => {);await expect(loader.uninstallPlugin('core-engine')).rejects.toThrow(/built-in/i);});++ it('rejects a plugin that declares ingress routes but omits the webhook:ingress permission', () => {+ // loadPlugin must run validateIngressManifest, so a malformed ingress declaration fails to load+ // rather than silently loading and becoming provisionable.+ const dir = path.join(pluginsDir, 'bad-ingress');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(+ path.join(dir, 'manifest.json'),+ JSON.stringify({+ id: 'bad-ingress',+ name: 'Bad Ingress',+ version: '1.0.0',+ type: 'extension',+ main: 'index.js',+ ingress: [{ route: 'events', signature: { headerName: 'X-Sig', scheme: 'hmac-sha256' } }],+ // permissions intentionally omitted → validateIngressManifest must reject+ }),+ );+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');+ expect(() => loader.loadPlugin(dir)).toThrow(/webhook:ingress/i);+ });});describe('PluginLoaderService — skips dot-prefixed directories on load (crash-leftover .bak)', () => {diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 896cb30a2..69b2b1b11 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -21,6 +21,7 @@ import {IPlugin,PluginType,PluginLogger,+ validateIngressManifest,} from './plugin.interfaces';import { isNetHostAllowed, performPluginFetch } from './plugin-net';import { PluginStorageService } from './plugin-storage.service';@@ -203,6 +204,10 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {if (!manifest.id || !manifest.name || !manifest.version || !manifest.type || !manifest.main) {throw new Error(`Invalid manifest: missing required fields`);}+ // Reject a malformed ingress declaration (SDK-major mismatch, missing webhook:ingress permission,+ // duplicate/empty routes, non-positive toleranceSec) at load time instead of letting it silently+ // load and become provisionable. No-op for plugins that declare no ingress.+ validateIngressManifest(manifest);// Check if plugin already loadedif (this.plugins.has(manifest.id)) {@@ -973,8 +978,13 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {},// Re-establish the in-flight hook context around the downstream send so an adapter that calls// conversation.send from within its own ingress handling can't echo-loop back into itself via- // its own outbound message:sending hook (mirrors the sandboxed worker-cap wrap below).- runGuarded: (events, run) => this.hookManager.runInFlight(events as HookEvent[], run),+ // its own outbound message:sending hook. Gate on an ALREADY-in-flight event (mirrors the+ // worker-cap wrap's `inFlight.length > 0` check): a plain top-level send must NOT suppress+ // message:sending for unrelated observers (audit/moderation) — only genuine re-entrancy does.+ runGuarded: (events, run) =>+ (events as HookEvent[]).some(e => this.hookManager.isInFlight(e))+ ? this.hookManager.runInFlight(events as HookEvent[], run)+ : run(),sendText: (sessionId, opts) => this.getMessageService().sendText(sessionId, opts),reply: (sessionId, opts) => this.getMessageService().reply(sessionId, opts),} satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability,diff --git a/src/modules/integration/dto/instance.dto.ts b/src/modules/integration/dto/instance.dto.tsindex 016ce965e..854cfedbd 100644--- a/src/modules/integration/dto/instance.dto.ts+++ b/src/modules/integration/dto/instance.dto.ts@@ -1,4 +1,4 @@-import { IsBoolean, IsObject, IsOptional, IsString, Matches, MaxLength } from 'class-validator';+import { IsBoolean, IsNotEmpty, IsObject, IsOptional, IsString, Matches, MaxLength } from 'class-validator';import { IngressUrl } from '../ingress-url';// Safe charset: also prevents an instanceId containing ':' (which would collide the P1 ordering key).@@ -11,6 +11,7 @@ export class CreateInstanceDto {@IsOptional()@IsString()+ @IsNotEmpty({ message: 'sessionScope must not be empty (omit it for all sessions)' })@MaxLength(256)sessionScope?: string;@@ -31,6 +32,7 @@ export class UpdateInstanceDto {@IsOptional()@IsString()+ @IsNotEmpty({ message: 'sessionScope must not be empty (omit it for all sessions)' })@MaxLength(256)sessionScope?: string;diff --git a/src/modules/integration/ingress-enqueue.service.spec.ts b/src/modules/integration/ingress-enqueue.service.spec.tsindex a0876b15f..ba5423b0b 100644--- a/src/modules/integration/ingress-enqueue.service.spec.ts+++ b/src/modules/integration/ingress-enqueue.service.spec.ts@@ -58,4 +58,16 @@ describe('IngressEnqueueService', () => {await expect(svc.enqueue(data, 'd1')).resolves.toBeUndefined();});++ it('falls back to inline dispatch (never throws) when queue.add() fails, e.g. Redis unreachable', async () => {+ // Without this, the throw would 500 the ingress request; the provider retries, dedup returns+ // "duplicate", and the already-persisted event is lost forever (no job, no DLQ row).+ (config.get as jest.Mock).mockReturnValue(true);+ queue.add.mockRejectedValue(new Error('Redis connection is closed'));+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, queue as never);++ await expect(svc.enqueue(data, 'd1')).resolves.toBeUndefined();+ expect(queue.add).toHaveBeenCalledWith('ingress', data, { jobId: 'd1' });+ expect(loader.dispatchWebhookForInstance).toHaveBeenCalledWith(data);+ });});diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.tsindex cf00b5595..a74dcc198 100644--- a/src/modules/integration/ingress-enqueue.service.ts+++ b/src/modules/integration/ingress-enqueue.service.ts@@ -29,11 +29,29 @@ export class IngressEnqueueService {const useQueue = queueEnabled && !!this.ingressQueue;if (useQueue && this.ingressQueue) {- // jobId = deliveryId gives BullMQ exactly-once enqueue semantics.- await this.ingressQueue.add('ingress', data, { jobId });- return;+ try {+ // jobId = deliveryId gives BullMQ exactly-once enqueue semantics.+ await this.ingressQueue.add('ingress', data, { jobId });+ return;+ } catch (err) {+ // Redis unreachable (enableOfflineQueue:false makes add() reject) — fall through to inline+ // dispatch. Without this, the already-persisted event would be lost forever: the throw would+ // 500 the ingress request, the provider retries, dedup returns "duplicate", and no job was+ // ever enqueued (no DLQ row either). Mirrors WebhookService's queue-add fallback.+ this.logger.error(+ 'Ingress queue add failed; dispatching inline',+ err instanceof Error ? err.message : String(err),+ {+ pluginId: data.pluginId,+ instanceId: data.instanceId,+ route: data.route,+ deliveryId: data.deliveryId,+ action: 'ingress_queue_add_failed',+ },+ );+ }}- // Queue disabled: dispatch inline AFTER the ingress_events row was persisted+ // Queue disabled OR queue.add() failed: dispatch inline AFTER the ingress_events row was persisted// (persist-before-dispatch still holds), mirroring the webhook direct-delivery fallback.try {await this.loader.dispatchWebhookForInstance(data);diff --git a/src/modules/integration/plugin-instance.service.spec.ts b/src/modules/integration/plugin-instance.service.spec.tsindex 286e882ea..53c36b39b 100644--- a/src/modules/integration/plugin-instance.service.spec.ts+++ b/src/modules/integration/plugin-instance.service.spec.ts@@ -83,4 +83,14 @@ describe('PluginInstanceService provisioning', () => {expect(await service.resolve('chatwoot', 'acct1')).toBeNull();expect(await service.remove('chatwoot', 'acct1')).toBe(false);});++ it('normalizes an empty sessionScope to null (all-sessions) on mint/create/update, never a literal ""', async () => {+ // '' would break outbound send (falsy sessionId) and be unrecoverable from the UI; store null instead.+ const minted = await service.mint('chatwoot', 'm1', { sessionScope: '' });+ expect(minted.sessionScope).toBeNull();+ const created = await service.create('chatwoot', 'acct1', { sessionScope: '' });+ expect(created.sessionScope).toBeNull();+ const patched = await service.update('chatwoot', 'acct1', { sessionScope: '' });+ expect(patched?.sessionScope).toBeNull();+ });});diff --git a/src/modules/integration/plugin-instance.service.ts b/src/modules/integration/plugin-instance.service.tsindex 923438ee0..1bd8c6640 100644--- a/src/modules/integration/plugin-instance.service.ts+++ b/src/modules/integration/plugin-instance.service.ts@@ -29,7 +29,7 @@ export class PluginInstanceService {id,pluginId,instanceId,- sessionScope: opts.sessionScope ?? null,+ sessionScope: opts.sessionScope || null,secret: randomBytes(32).toString('hex'),verifyToken: opts.verifyToken ?? null,config: opts.config ?? null,@@ -58,7 +58,7 @@ export class PluginInstanceService {id,pluginId,instanceId,- sessionScope: opts.sessionScope ?? null,+ sessionScope: opts.sessionScope || null,secret: randomBytes(32).toString('hex'),verifyToken: opts.verifyToken ?? null,config: opts.config ?? null,@@ -92,7 +92,7 @@ export class PluginInstanceService {): Promise<PluginInstance | null> {const inst = await this.resolve(pluginId, instanceId);if (!inst) return null;- if (patch.sessionScope !== undefined) inst.sessionScope = patch.sessionScope;+ if (patch.sessionScope !== undefined) inst.sessionScope = patch.sessionScope || null;if (patch.config !== undefined) inst.config = patch.config;return this.repo.save(inst);}diff --git a/src/modules/integration/redrive.controller.spec.ts b/src/modules/integration/redrive.controller.spec.tsnew file mode 100644index 000000000..35ee5763b--- /dev/null+++ b/src/modules/integration/redrive.controller.spec.ts@@ -0,0 +1,13 @@+import { Reflector } from '@nestjs/core';+import { RedriveController } from './redrive.controller';+import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';++describe('RedriveController authz', () => {+ it('is ADMIN-gated (re-dispatching DLQ payloads can cause real sends; a VIEWER/OPERATOR key must not)', () => {+ // The ApiKeyGuard only enforces a role when REQUIRED_ROLE_KEY metadata is present; without this+ // decorator any authenticated key (incl. read-only VIEWER) could POST the redrive action.+ const role = new Reflector().get<ApiKeyRole>(REQUIRED_ROLE_KEY, RedriveController);+ expect(role).toBe(ApiKeyRole.ADMIN);+ });+});diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.tsindex 8b459651e..6ba2a0386 100644--- a/src/modules/integration/redrive.controller.ts+++ b/src/modules/integration/redrive.controller.ts@@ -1,8 +1,13 @@import { Controller, Param, Post } from '@nestjs/common';+import { RequireRole } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';import { RedriveService } from './redrive.service';-// NOT @Public — this is an operator action guarded by the global ApiKeyGuard (X-API-Key header).+// Re-dispatching DLQ'd inbound payloads can cause real downstream sends, so this operator action is+// ADMIN-gated — matching the sibling IntegrationInstanceController. (A bare API key, even VIEWER,+// must NOT be able to trigger it.)@Controller('integration/instances')+@RequireRole(ApiKeyRole.ADMIN)export class RedriveController {constructor(private readonly redrive: RedriveService) {}