Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(hooks): add AsyncLocalStorage re-entrancy guard to HookManager

rmyndharisd62175640c83
diff --git a/src/core/hooks/hook-manager.service.spec.ts b/src/core/hooks/hook-manager.service.spec.ts
index 8be56cca6..8725dd5e7 100644
--- a/src/core/hooks/hook-manager.service.spec.ts
+++ b/src/core/hooks/hook-manager.service.spec.ts
@@ -2,6 +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';
describe('HookManager', () => {
let hm: HookManager;
@@ -105,7 +106,7 @@ describe('HookManager', () => {
expect(hm.hasHooks('session:created')).toBe(false);
});
- it('unregisterPlugin removes only that plugin’s hooks', () => {
+ it("unregisterPlugin removes only that plugin's hooks", () => {
hm.register('A', 'session:ready', async ctx => ({ continue: true, data: ctx.data }));
hm.register('A', 'session:ready', async ctx => ({ continue: true, data: ctx.data }));
hm.register('B', 'session:ready', async ctx => ({ continue: true, data: ctx.data }));
@@ -114,3 +115,43 @@ describe('HookManager', () => {
expect(hm.getHookCount('session:ready')).toBe(1); // only B remains
});
});
+
+describe('HookManager re-entrancy guard', () => {
+ let manager: HookManager;
+
+ beforeEach(() => {
+ manager = new HookManager();
+ });
+
+ it('short-circuits a handler that re-fires the same event (no infinite recursion)', async () => {
+ let calls = 0;
+ manager.register('p1', 'message:sending', async (ctx: HookContext): Promise<HookResult> => {
+ calls += 1;
+ const inner = await manager.execute('message:sending', ctx.data, { source: 'test' });
+ expect(inner).toEqual({ continue: true, data: ctx.data });
+ return { continue: true };
+ });
+
+ const result = await manager.execute('message:sending', { n: 1 }, { source: 'test' });
+
+ expect(calls).toBe(1);
+ expect(result.continue).toBe(true);
+ });
+
+ it('does NOT block a handler that fires a DIFFERENT event', async () => {
+ const seen: string[] = [];
+ manager.register('p1', 'message:received', async (ctx: HookContext): Promise<HookResult> => {
+ seen.push('received');
+ await manager.execute('message:sent', ctx.data, { source: 'test' });
+ return { continue: true };
+ });
+ manager.register('p2', 'message:sent', async (): Promise<HookResult> => {
+ seen.push('sent');
+ return { continue: true };
+ });
+
+ await manager.execute('message:received', { n: 1 }, { source: 'test' });
+
+ expect(seen).toEqual(['received', 'sent']);
+ });
+});
diff --git a/src/core/hooks/hook-manager.service.ts b/src/core/hooks/hook-manager.service.ts
index bd764ec74..7a7bd6f66 100644
--- a/src/core/hooks/hook-manager.service.ts
+++ b/src/core/hooks/hook-manager.service.ts
@@ -1,4 +1,5 @@
import { Injectable, Logger } from '@nestjs/common';
+import { AsyncLocalStorage } from 'node:async_hooks';
import { HookEvent, HookHandler, HookContext, HookRegistration } from './hook.interfaces';
@Injectable()
@@ -6,6 +7,11 @@ export class HookManager {
private readonly logger = new Logger(HookManager.name);
private readonly hooks = new Map<HookEvent, HookRegistration[]>();
private readonly pluginHooks = new Map<string, Set<string>>(); // pluginId -> hookIds
+ // Events in-flight on the active async context. A handler that re-fires the SAME event
+ // (e.g. a message:sending handler that sends) is short-circuited instead of recursing.
+ // NOTE: the context does not span the async engine `message_create` echo, so this guards
+ // synchronous re-entry only (the async message:sent echo loop is documented, deferred).
+ private readonly inFlightEvents = new AsyncLocalStorage<Set<HookEvent>>();
/**
* Register a hook handler
@@ -85,6 +91,24 @@ export class HookManager {
event: HookEvent,
data: T,
options: { sessionId?: string; source: string },
+ ): Promise<{ continue: boolean; data: T }> {
+ const inFlight = this.inFlightEvents.getStore();
+ if (inFlight?.has(event)) {
+ this.logger.warn(
+ `Hook re-entrancy blocked: ${event} re-fired by a handler of the same event (source: ${options.source})`,
+ );
+ return { continue: true, data };
+ }
+
+ const nextInFlight = new Set<HookEvent>(inFlight);
+ nextInFlight.add(event);
+ return this.inFlightEvents.run(nextInFlight, () => this.runHandlers(event, data, options));
+ }
+
+ private async runHandlers<T>(
+ event: HookEvent,
+ data: T,
+ options: { sessionId?: string; source: string },
): Promise<{ continue: boolean; data: T }> {
const registrations = this.hooks.get(event) || [];
@@ -106,18 +130,15 @@ export class HookManager {
ctx.data = currentData;
const result = await registration.handler(ctx);
- // Update data if modified
if (result.data !== undefined) {
currentData = result.data as T;
}
- // Stop chain if continue is false
if (!result.continue) {
this.logger.debug(`Hook chain stopped by ${registration.pluginId} at event ${event}`);
return { continue: false, data: currentData };
}
- // Propagate error
if (result.error) {
throw result.error;
}