Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): run a sandboxed hook chain at its lowest priority

Yudhi Armyndharis29845931fe6d
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index 32d8b33ea..8f3b052cb 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -479,7 +479,10 @@ export type HookHandler<T = unknown> = (ctx: HookContext<T>) => Promise<HookResu
### Hook Manager behavior
`HookManager` (`src/core/hooks/hook-manager.service.ts`) is a NestJS provider. Handlers are stored per
-event and run in **priority order** (lower `priority` first; default `100`). On `execute(event, data,
+event and run in **priority order** (lower `priority` first; default `100`; a priority that is not a
+finite number runs at `100`). A sandboxed plugin's handlers for one event share a single host-side
+registration at the lowest priority among them, so relative to other plugins they all run at that point,
+and among themselves in their own order. On `execute(event, data,
{ sessionId, source })` it walks the chain, threading each handler's returned `data` into the next; a
handler that returns `{ continue: false }` stops the chain. A handler that **throws** is logged and the
chain continues with the previous data (one bad plugin can't break the chain). Same-event re-entrancy
diff --git a/src/core/hooks/hook-manager.service.spec.ts b/src/core/hooks/hook-manager.service.spec.ts
index d750c7515..d6eb8c952 100644
--- a/src/core/hooks/hook-manager.service.spec.ts
+++ b/src/core/hooks/hook-manager.service.spec.ts
@@ -186,6 +186,59 @@ describe('HookManager re-entrancy guard', () => {
});
});
+describe('HookManager priority', () => {
+ it('runs a non-numeric or non-finite priority at the default, keeping every other handler in order', async () => {
+ const hm = new HookManager();
+ const order: string[] = [];
+ const push = (name: string) => () => {
+ order.push(name);
+ return Promise.resolve({ continue: true });
+ };
+ hm.register('rewrite', 'message:sending', push('rewrite@50'), 50);
+ hm.register('junk', 'message:sending', push('junk'), 'high' as unknown as number);
+ hm.register('nan', 'message:sending', push('nan'), NaN);
+ hm.register('veto', 'message:sending', push('veto@10'), 10);
+
+ await hm.execute('message:sending', {}, { source: 't' });
+
+ expect(order).toEqual(['veto@10', 'rewrite@50', 'junk', 'nan']);
+ });
+
+ it('setPriority moves an existing registration and re-sorts its chain', async () => {
+ const hm = new HookManager();
+ const order: string[] = [];
+ hm.register('a', 'message:sent', () => (order.push('a'), Promise.resolve({ continue: true })), 100);
+ const id = hm.register('b', 'message:sent', () => (order.push('b'), Promise.resolve({ continue: true })), 200);
+
+ hm.setPriority(id, 1);
+ await hm.execute('message:sent', {}, { source: 't' });
+
+ expect(order).toEqual(['b', 'a']);
+ });
+
+ it('runs every handler once when one moves a later registration ahead of itself mid-chain', async () => {
+ const hm = new HookManager();
+ const order: string[] = [];
+ let cId = '';
+ hm.register('a', 'message:sent', () => (order.push('a'), Promise.resolve({ continue: true })), 10);
+ hm.register(
+ 'b',
+ 'message:sent',
+ () => {
+ order.push('b');
+ hm.setPriority(cId, 1);
+ return Promise.resolve({ continue: true });
+ },
+ 20,
+ );
+ cId = hm.register('c', 'message:sent', () => (order.push('c'), Promise.resolve({ continue: true })), 30);
+
+ await hm.execute('message:sent', {}, { source: 't' });
+
+ expect(order).toEqual(['a', 'b', 'c']);
+ });
+});
+
describe('HookManager.isInFlight + selective re-entrancy guard (conversation.send pattern)', () => {
const SENDING: HookEvent[] = ['message:sending'];
diff --git a/src/core/hooks/hook-manager.service.ts b/src/core/hooks/hook-manager.service.ts
index 501d2018d..31d2870a6 100644
--- a/src/core/hooks/hook-manager.service.ts
+++ b/src/core/hooks/hook-manager.service.ts
@@ -2,6 +2,16 @@ import { Injectable, Logger } from '@nestjs/common';
import { AsyncLocalStorage } from 'node:async_hooks';
import { HookEvent, HookHandler, HookContext, HookRegistration } from './hook.interfaces';
+/**
+ * The priority a registration actually runs at: a finite number as given, anything else the default
+ * 100. The chain is sorted by `a.priority - b.priority`; one NaN or string in it makes the comparator
+ * return NaN and the order of EVERY handler for that event implementation-defined (a veto can land
+ * after a rewrite). Sandboxed plugins send their priority over IPC, so no type can be assumed.
+ */
+export function normalizeHookPriority(priority: unknown): number {
+ return typeof priority === 'number' && Number.isFinite(priority) ? priority : 100;
+}
+
@Injectable()
export class HookManager {
private readonly logger = new Logger(HookManager.name);
@@ -23,7 +33,7 @@ export class HookManager {
pluginId,
event,
handler,
- priority,
+ priority: normalizeHookPriority(priority),
};
// Add to event handlers
@@ -41,7 +51,7 @@ export class HookManager {
}
this.pluginHooks.get(pluginId)!.add(id);
- this.logger.debug(`Hook registered: ${event} by ${pluginId} (priority: ${priority})`);
+ this.logger.debug(`Hook registered: ${event} by ${pluginId} (priority: ${registration.priority})`);
return id;
}
@@ -67,6 +77,17 @@ export class HookManager {
}
}
+ /** Move an existing registration to `priority` (normalized like {@link register}) and re-sort its chain. */
+ setPriority(hookId: string, priority: number): void {
+ for (const registrations of this.hooks.values()) {
+ const registration = registrations.find(r => r.id === hookId);
+ if (!registration) continue;
+ registration.priority = normalizeHookPriority(priority);
+ registrations.sort((a, b) => a.priority - b.priority);
+ return;
+ }
+ }
+
/**
* Unregister all hooks for a plugin
*/
@@ -138,7 +159,9 @@ export class HookManager {
data: T,
options: { sessionId?: string; source: string },
): Promise<{ continue: boolean; data: T }> {
- const registrations = this.hooks.get(event) || [];
+ // A snapshot: a registration added or moved while this chain awaits a handler (a sandboxed plugin
+ // re-subscribing at a lower priority) must not make the loop skip or repeat one.
+ const registrations = [...(this.hooks.get(event) ?? [])];
if (registrations.length === 0) {
return { continue: true, data };
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
index b8bc267c8..4a84f07e0 100644
--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
@@ -163,6 +163,35 @@ describe('PluginLoaderService — sandbox tier routing', () => {
expect(registerSpy.mock.calls.filter(c => c[1] === 'message:received')).toHaveLength(1);
});
+ it('runs the shim at the lowest priority the worker asked for, and ignores a non-numeric one', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ const hookManager = (loader as unknown as { hookManager: HookManager }).hookManager;
+ const order: string[] = [];
+ hookManager.register('other', 'message:sending', () => {
+ order.push('other@100');
+ return Promise.resolve({ continue: true });
+ });
+ await loader.enablePlugin('p1');
+ loader.hosts[0].dispatchHook.mockImplementation(() => {
+ order.push('p1');
+ return Promise.resolve({ continue: true });
+ });
+
+ // The worker's first handler asks for 200; a later one for 1 (it re-subscribes); junk is ignored.
+ loader.capturedOnHookSubscribe!('message:sending', 200);
+ loader.capturedOnHookSubscribe!('message:sending', 1);
+ loader.capturedOnHookSubscribe!('message:sending', 'high' as unknown as number);
+ loader.capturedOnHookSubscribe!('message:sending', NaN);
+ await hookManager.execute('message:sending', {}, { source: 't' });
+
+ expect(order).toEqual(['p1', 'other@100']);
+ expect(hookManager.getRegisteredHooks()['message:sending']).toEqual([
+ { pluginId: 'p1', priority: 1 },
+ { pluginId: 'other', priority: 100 },
+ ]);
+ });
+
it('forwards the host in-flight chain to the worker with each dispatch', async () => {
const loader = makeLoader();
seed(loader, { builtIn: false, instance: null });
diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.ts
index 04f66b973..8db356221 100644
--- a/src/core/plugins/plugin-sandbox-bridge.ts
+++ b/src/core/plugins/plugin-sandbox-bridge.ts
@@ -1,7 +1,7 @@
import * as path from 'path';
import { ConfigService } from '@nestjs/config';
import { createLogger } from '../../common/services/logger.service';
-import { HookManager, HookEvent, KNOWN_HOOK_EVENTS, isKnownHookEvent } from '../hooks';
+import { HookManager, HookEvent, KNOWN_HOOK_EVENTS, isKnownHookEvent, normalizeHookPriority } from '../hooks';
import { PluginCapabilityPermission, PluginContext, PluginInstance, PluginStatus } from './plugin.interfaces';
import { PluginStorageService } from './plugin-storage.service';
import { PluginHostServices } from './plugin-host-services';
@@ -399,13 +399,18 @@ export class PluginSandboxBridge {
// growth + an O(n log n) re-sort). Three guards, all local to this enableSandboxed call (dropped on
// disable): reject unknown events (bounds growth to the finite known set + drops events that can
// never fire), dedup per event, and a belt-and-suspenders size cap.
+ //
+ // One shim per event runs the worker's whole chain for it, so it sits at the LOWEST priority any of
+ // the worker's handlers asked for: the worker re-subscribes when a later handler lowers it, and the
+ // shim moves up. Pinning it to the first handler's priority let another plugin's handler run before
+ // a sandboxed handler that asked to go first (a redaction ahead of a mirror, say).
private buildHookSubscribeHandler(
pluginId: string,
plugin: PluginInstance,
): (event: string, priority?: number) => void {
- const subscribedEvents = new Set<HookEvent>();
+ const subscribedEvents = new Map<HookEvent, { hookId: string; priority: number }>();
let unknownEventWarned = false;
- return (event: string, priority?: number): void => {
+ return (event: string, rawPriority?: number): void => {
if (!isKnownHookEvent(event)) {
if (!unknownEventWarned) {
unknownEventWarned = true; // warn at most once per plugin so a flood isn't a log-flood vector
@@ -417,13 +422,20 @@ export class PluginSandboxBridge {
}
return;
}
- if (subscribedEvents.has(event)) return;
+ const priority = normalizeHookPriority(rawPriority);
+ const existing = subscribedEvents.get(event);
+ if (existing) {
+ if (priority < existing.priority) {
+ this.hookManager.setPriority(existing.hookId, priority);
+ existing.priority = priority;
+ }
+ return;
+ }
if (subscribedEvents.size >= KNOWN_HOOK_EVENTS.size) return; // can't exceed the known set
- subscribedEvents.add(event);
// Per-event rate-limit state for the hook-error log; local to this enable call so it is dropped
// on disable exactly like subscribedEvents.
const hookErrorLogState = new Map<string, { lastAt: number; suppressed: number }>();
- this.hookManager.register(
+ const hookId = this.hookManager.register(
pluginId,
event,
async hookCtx => {
@@ -495,6 +507,7 @@ export class PluginSandboxBridge {
},
priority,
);
+ subscribedEvents.set(event, { hookId, priority });
};
}
diff --git a/src/core/plugins/sandbox/worker-hooks.spec.ts b/src/core/plugins/sandbox/worker-hooks.spec.ts
index 03849e8b2..b7c735139 100644
--- a/src/core/plugins/sandbox/worker-hooks.spec.ts
+++ b/src/core/plugins/sandbox/worker-hooks.spec.ts
@@ -27,6 +27,33 @@ describe('WorkerHookRegistry', () => {
expect(sent.filter(m => m.kind === 'hook-subscribe')).toHaveLength(1);
});
+ it('re-subscribes when a later handler lowers the event priority, and only then', () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+
+ reg.register('message:sending', () => Promise.resolve({ continue: true }), 200);
+ reg.register('message:sending', () => Promise.resolve({ continue: true }), 1);
+ reg.register('message:sending', () => Promise.resolve({ continue: true }), 300);
+
+ expect(sent.filter(m => m.kind === 'hook-subscribe')).toEqual([
+ { kind: 'hook-subscribe', event: 'message:sending', priority: 200 },
+ { kind: 'hook-subscribe', event: 'message:sending', priority: 1 },
+ ]);
+ });
+
+ it('compares a later priority against the default when the first one is not a finite number', () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+
+ reg.register('message:sending', () => Promise.resolve({ continue: true }), 'abc');
+ reg.register('message:sending', () => Promise.resolve({ continue: true }), 1);
+
+ expect(sent.filter(m => m.kind === 'hook-subscribe')).toEqual([
+ { kind: 'hook-subscribe', event: 'message:sending', priority: 100 },
+ { kind: 'hook-subscribe', event: 'message:sending', priority: 1 },
+ ]);
+ });
+
it('runs the handler on a hook and replies with continue + modified data', async () => {
const { sent, post } = collect();
const reg = new WorkerHookRegistry(post);
diff --git a/src/core/plugins/sandbox/worker-hooks.ts b/src/core/plugins/sandbox/worker-hooks.ts
index a51a973e1..a2f451cac 100644
--- a/src/core/plugins/sandbox/worker-hooks.ts
+++ b/src/core/plugins/sandbox/worker-hooks.ts
@@ -39,11 +39,18 @@ export class WorkerHookRegistry {
constructor(private readonly post: (message: WorkerToHostMessage) => void) {}
- register(event: string, handler: WorkerHookHandler, priority = 100): void {
+ register(event: string, handler: WorkerHookHandler, rawPriority: unknown = 100): void {
+ // The host runs a non-finite or non-numeric priority at 100; compare and sort on that same value,
+ // or a junk first priority would stop a later lower one from moving the shim up.
+ const priority = typeof rawPriority === 'number' && Number.isFinite(rawPriority) ? rawPriority : 100;
const list = this.handlers.get(event);
if (list) {
+ const lowest = list[0].priority;
list.push({ handler, priority });
list.sort((a, b) => a.priority - b.priority);
+ // The host runs this event's whole worker chain from one shim; move it up to the new lowest
+ // priority so this handler still runs ahead of other plugins' handlers it asked to precede.
+ if (priority < lowest) this.post({ kind: 'hook-subscribe', event, priority });
return;
}
this.handlers.set(event, [{ handler, priority }]);