Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): prevent hook re-entrancy amplification in the sandbox worker (#532)
Yudhi Armyndharis5f798dcf7e6b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8fddac3aa..e1eaab036 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **Bulk batch ids are unique per session, not globally.** A batch id claimed by one session no longer prevents another session from using the same id — the uniqueness constraint is now scoped to `(session, batchId)`, matching the per-session lookup, so an explicit cross-session reuse no longer fails with a `500`. Reusing an id within the same session is still rejected with a clear `400`. Existing databases are migrated in place. (#531)- **A message arriving while a session is being deleted is no longer persisted as an orphan.** The inbound-message handler re-checks that the session is still live after its asynchronous processing, so a message that races a session deletion can't leave behind a `messages` row (which has no cascade) for a session that no longer exists. (#531)+### Security++- **Hook re-entrancy is now blocked for sandboxed plugins too.** A plugin running in the worker-thread sandbox could re-fire the hook it was handling by issuing a capability call (for example, sending a message from within a `message:sending` handler), because the re-entrancy guard did not span the worker boundary — looping the event back into the plugin without bound. The host now runs each worker-initiated capability call inside the in-flight hook context, so such a re-fire is short-circuited exactly as it already was for in-process plugins. (#532)+## [0.7.12] - 2026-06-29### Addeddiff --git a/src/core/hooks/hook-manager.service.ts b/src/core/hooks/hook-manager.service.tsindex c825b2e1e..6aae375dc 100644--- a/src/core/hooks/hook-manager.service.ts+++ b/src/core/hooks/hook-manager.service.ts@@ -105,6 +105,20 @@ export class HookManager {return this.inFlightEvents.run(nextInFlight, () => this.runHandlers(event, data, options));}+ /**+ * Run `fn` with `events` marked in-flight on the active async context (merged with anything already+ * in flight). The re-entrancy guard in {@link execute} relies on AsyncLocalStorage, which does not+ * span the sandbox worker IPC boundary: a worker handling a hook can issue a capability call that+ * returns to the host on a fresh async context, where `getStore()` is empty. Wrapping that+ * round-trip in this method re-establishes the in-flight set so a capability that re-fires the same+ * in-flight event is short-circuited exactly as an in-process handler would be.+ */+ runInFlight<T>(events: Iterable<HookEvent>, fn: () => T): T {+ const merged = new Set<HookEvent>(this.inFlightEvents.getStore());+ for (const event of events) merged.add(event);+ return this.inFlightEvents.run(merged, fn);+ }+private async runHandlers<T>(event: HookEvent,data: T,diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 1b74a1dd5..2059d943d 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -618,6 +618,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,onHookSubscribe?: (event: string, priority?: number) => void,onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,+ runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,): PluginWorkerHost {const workerEntry = path.join(__dirname, 'sandbox', 'worker-bootstrap.js');return new PluginWorkerHost(@@ -630,6 +631,7 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {capDispatcher,onHookSubscribe,onLog,+ runWithHookGuard,);}@@ -745,6 +747,9 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {(verb, args) => dispatchCapabilityVerb(context, verb, args),onHookSubscribe,onLog,+ // Re-establish the in-flight hook context for worker-initiated capability calls, so a sandboxed+ // plugin that sends from within a send hook can't loop the event back into itself unboundedly.+ (events, run) => this.hookManager.runInFlight(events as HookEvent[], run),);this.sandboxHosts.set(pluginId, host);try {diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.tsindex 6d7452919..edf5cfdf7 100644--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts@@ -1,5 +1,7 @@import { PluginWorkerHost } from './plugin-worker-host';import { PluginWorkerChannel, HostToWorkerMessage, WorkerToHostMessage } from './protocol';+import { HookManager } from '../../hooks/hook-manager.service';+import { HookEvent } from '../../hooks/hook.interfaces';/** In-memory channel double: records what the host posts, lets the test push worker replies back. */class FakeChannel implements PluginWorkerChannel {@@ -361,4 +363,58 @@ describe('PluginWorkerHost', () => {jest.useRealTimers();});});++ describe('hook re-entrancy across the worker IPC boundary (amplification guard)', () => {+ const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));++ it('a worker capability that re-fires the in-flight hook event is not re-dispatched into the worker', async () => {+ const hm = new HookManager();+ const ch = new FakeChannel();+ const EVENT = 'message:sending' as HookEvent;++ // A worker capability call (messages.sendText) that re-fires message:sending on the host — the+ // exact amplification loop: without the guard the re-fire dispatches into the worker again, which+ // sends again, unboundedly.+ const capDispatcher = async (verb: string): Promise<unknown> => {+ if (verb === 'messages.sendText') {+ await hm.execute(EVENT, { reentrant: true }, { source: 'cap' });+ }+ return { messageId: 'wamid' };+ };++ const host = new PluginWorkerHost(ch, capDispatcher, undefined, undefined, (events, run) =>+ hm.runInFlight(events as HookEvent[], run),+ );++ // The host-side shim the loader registers: dispatch the event into the worker, await its result.+ hm.register('plg', EVENT, async ctx => {+ const r = await host.dispatchHook({+ event: 'message:sending',+ data: ctx.data,+ source: ctx.source,+ timeoutMs: 5000,+ });+ return { continue: r.continue, data: r.data };+ });++ // Fire the event: the shim posts exactly ONE 'hook' message into the worker.+ const exec = hm.execute(EVENT, { n: 1 }, { source: 'test' });+ await flush();+ const firstHooks = ch.sent.filter(m => m.kind === 'hook');+ expect(firstHooks).toHaveLength(1);+ const hookId = firstHooks[0].id;++ // The worker, mid-handler, issues a capability that re-fires message:sending on the host.+ ch.reply({ kind: 'cap', id: 99, verb: 'messages.sendText', args: ['s1', 'c1', 'hi'] });+ await flush();+ await flush();++ // The guard must short-circuit the re-fire: still exactly ONE dispatch into the worker.+ expect(ch.sent.filter(m => m.kind === 'hook')).toHaveLength(1);++ // The worker completes the original hook; the chain resolves normally.+ ch.reply({ kind: 'hook-result', id: hookId, continue: true });+ await expect(exec).resolves.toEqual({ continue: true, data: { n: 1 } });+ });+ });});diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.tsindex def0d5823..ee5aa237a 100644--- a/src/core/plugins/sandbox/plugin-worker-host.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.ts@@ -35,6 +35,11 @@ export class PluginWorkerHost {number,{ resolve: (result: { healthy: boolean; message?: string }) => void; timer: ReturnType<typeof setTimeout> }>();+ // Hook events currently dispatched to the worker and not yet settled, as a multiset. While the+ // worker handles a hook it may issue capability calls that round-trip to the host; those run inside+ // this in-flight set so a capability that re-fires the same event is short-circuited (HookManager's+ // AsyncLocalStorage re-entrancy guard does not span the worker IPC boundary).+ private readonly inFlightHookEvents = new Map<string, number>();constructor(private readonly channel: PluginWorkerChannel,@@ -46,11 +51,26 @@ export class PluginWorkerHost {private readonly onHookSubscribe?: (event: string, priority?: number) => void,// Routes a worker plugin's ctx.logger.* call to the host's per-plugin logger.private readonly onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,+ // Runs a worker-initiated capability call inside the in-flight hook context, so a capability that+ // re-fires an event this worker is currently handling is short-circuited (re-entrancy across IPC).+ // Absent => capability calls run with no hook guard (e.g. before the bridge is wired, or in tests).+ private readonly runWithHookGuard?: (inFlightEvents: string[], run: () => Promise<unknown>) => Promise<unknown>,) {this.channel.onMessage(message => this.handleMessage(message));this.channel.onExit(code => this.handleExit(code));}+ private incInFlightHook(event: string): void {+ this.inFlightHookEvents.set(event, (this.inFlightHookEvents.get(event) ?? 0) + 1);+ }++ private decInFlightHook(event: string): void {+ const count = this.inFlightHookEvents.get(event);+ if (count === undefined) return;+ if (count <= 1) this.inFlightHookEvents.delete(event);+ else this.inFlightHookEvents.set(event, count - 1);+ }+/*** Dispatch a hook event to the worker and await its handler result. Bounded by `timeoutMs`: if the* worker's handler is slow or wedged, this resolves `{ continue: true }` so the host's hook chain@@ -66,13 +86,20 @@ export class PluginWorkerHost {onTimeout?: () => void;}): Promise<{ continue: boolean; data?: unknown }> {const id = this.nextId++;+ this.incInFlightHook(options.event);return new Promise(resolve => {+ // settle decrements the in-flight counter on every exit path (worker result, timeout, or crash+ // drain) since it is what the hookPending entry's resolve runs.+ const settle = (result: { continue: boolean; data?: unknown }): void => {+ this.decInFlightHook(options.event);+ resolve(result);+ };const timer = setTimeout(() => {this.hookPending.delete(id);options.onTimeout?.();- resolve({ continue: true });+ settle({ continue: true });}, options.timeoutMs);- this.hookPending.set(id, { resolve, timer });+ this.hookPending.set(id, { resolve: settle, timer });this.channel.postMessage({kind: 'hook',id,@@ -224,7 +251,14 @@ export class PluginWorkerHost {return;}try {- const result = await this.capDispatcher(message.verb, message.args);+ const dispatcher = this.capDispatcher;+ const run = (): Promise<unknown> => dispatcher(message.verb, message.args);+ // Run inside the in-flight hook context so a capability that re-fires an event this worker is+ // currently handling is short-circuited by HookManager's re-entrancy guard (which otherwise+ // can't see across the IPC boundary). No hooks in flight => run directly, no wrapping cost.+ const inFlight = [...this.inFlightHookEvents.keys()];+ const result =+ this.runWithHookGuard && inFlight.length > 0 ? await this.runWithHookGuard(inFlight, run) : await run();this.channel.postMessage({ kind: 'cap-result', id: message.id, ok: true, result });} catch (error) {this.channel.postMessage({