Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): bound capability RPCs, surface sandbox hook errors, and validate plugin search results (#954)

Yudhi Armyndharis7585c24f07dd
diff --git a/.env.example b/.env.example
index f8f208815..7f03ec90e 100644
--- a/.env.example
+++ b/.env.example
@@ -420,6 +420,13 @@ PLUGINS_DIR=./data/plugins # Plugin directory
# Cap on a plugin .zip downloaded by install-from-URL (matches the 5 MB upload limit). A non-positive
# or non-numeric value falls back to the default.
# PLUGIN_DOWNLOAD_MAX_BYTES=5242880 # default 5 MiB
+# Host-side budget for one sandboxed plugin capability call; a wedged call is failed and its in-flight
+# slot freed (the late-settling work is only logged, not cancelled). A non-positive or non-numeric
+# value falls back to the default.
+# PLUGIN_CAP_TIMEOUT_MS=30000 # default 30s
+# Per-plugin bound on ctx.storage writes; writes beyond it are rejected. A non-positive or non-numeric
+# value falls back to the default.
+# PLUGIN_STORAGE_MAX_BYTES=52428800 # default 50 MiB
# =============================================================================
# SECURITY
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 6418add53..fcc4e4cfc 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -229,6 +229,17 @@ export default () => ({
const n = parseInt(process.env.PLUGIN_DOWNLOAD_MAX_BYTES ?? '', 10);
return Number.isFinite(n) && n > 0 ? n : 5 * 1024 * 1024;
})(),
+ // Host-side budget for ONE worker-initiated capability call (see PluginWorkerHost.withCapTimeout).
+ // Same fail-safe parsing as downloadMaxBytes.
+ capTimeoutMs: (() => {
+ const n = parseInt(process.env.PLUGIN_CAP_TIMEOUT_MS ?? '', 10);
+ return Number.isFinite(n) && n > 0 ? n : 30000;
+ })(),
+ // Per-plugin bound on ctx.storage writes. Same fail-safe parsing as downloadMaxBytes.
+ storageMaxBytes: (() => {
+ const n = parseInt(process.env.PLUGIN_STORAGE_MAX_BYTES ?? '', 10);
+ return Number.isFinite(n) && n > 0 ? n : 50 * 1024 * 1024;
+ })(),
},
// Integration Fabric ingress configuration
diff --git a/src/core/plugins/conversation-send-facade.spec.ts b/src/core/plugins/conversation-send-facade.spec.ts
index 0f6845d67..36e5e42cf 100644
--- a/src/core/plugins/conversation-send-facade.spec.ts
+++ b/src/core/plugins/conversation-send-facade.spec.ts
@@ -147,4 +147,80 @@ describe('conversation.send facade', () => {
expect(sendText).toHaveBeenCalledWith('s', { chatId: 'c', text: 'https://cdn.example/v.mp4' });
expect(res).toEqual({ id: 't1' });
});
+
+ it('routes a location envelope to sendLocation, mapping text to the description', async () => {
+ const sendLocation = jest.fn().mockResolvedValue({ id: 'l1' });
+ const sendText = jest.fn();
+ const facade = buildConversationSendFacade({
+ manifest: manifest(['conversation:send']) as never,
+ assertPermission: () => undefined,
+ assertSessionActive: jest.fn(),
+ resolveChatId: () => Promise.resolve('[email protected]'),
+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),
+ sendText,
+ reply: jest.fn(),
+ sendLocation,
+ } as never);
+ const res = await facade.send({
+ type: 'location',
+ latitude: -6.2,
+ longitude: 106.816666,
+ text: 'Jakarta HQ',
+ sessionId: 's',
+ chatId: '[email protected]',
+ });
+ expect(sendLocation).toHaveBeenCalledWith('s', {
+ chatId: '[email protected]',
+ latitude: -6.2,
+ longitude: 106.816666,
+ description: 'Jakarta HQ',
+ });
+ expect(sendText).not.toHaveBeenCalled();
+ expect(res).toEqual({ id: 'l1' });
+ });
+
+ it('rejects a location envelope without valid coordinates — never degrades to an empty text', async () => {
+ const sendText = jest.fn();
+ const sendLocation = jest.fn();
+ const facade = buildConversationSendFacade({
+ manifest: manifest(['conversation:send']) as never,
+ assertPermission: () => undefined,
+ assertSessionActive: jest.fn(),
+ resolveChatId: () => Promise.resolve('[email protected]'),
+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),
+ sendText,
+ reply: jest.fn(),
+ sendLocation,
+ } as never);
+ // No coordinates at all.
+ await expect(facade.send({ type: 'location', sessionId: 's', chatId: 'c' })).rejects.toThrow(PluginCapabilityError);
+ // Out-of-range / non-finite coordinates.
+ await expect(
+ facade.send({ type: 'location', latitude: 91, longitude: 0, sessionId: 's', chatId: 'c' }),
+ ).rejects.toThrow(/latitude/);
+ await expect(
+ facade.send({ type: 'location', latitude: 0, longitude: NaN, sessionId: 's', chatId: 'c' }),
+ ).rejects.toThrow(PluginCapabilityError);
+ // The failure is loud; nothing is sent, least of all an empty text.
+ expect(sendText).not.toHaveBeenCalled();
+ expect(sendLocation).not.toHaveBeenCalled();
+ });
+
+ it('rejects replyTo on a location envelope — the engine location path cannot quote', async () => {
+ const sendLocation = jest.fn();
+ const facade = buildConversationSendFacade({
+ manifest: manifest(['conversation:send']) as never,
+ assertPermission: () => undefined,
+ assertSessionActive: jest.fn(),
+ resolveChatId: () => Promise.resolve('[email protected]'),
+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),
+ sendText: jest.fn(),
+ reply: jest.fn(),
+ sendLocation,
+ } as never);
+ await expect(
+ facade.send({ type: 'location', latitude: 1, longitude: 1, replyTo: 'Q1', sessionId: 's', chatId: 'c' }),
+ ).rejects.toThrow(PluginCapabilityError);
+ expect(sendLocation).not.toHaveBeenCalled();
+ });
});
diff --git a/src/core/plugins/conversation-send-facade.ts b/src/core/plugins/conversation-send-facade.ts
index 0a3695182..08a9085fb 100644
--- a/src/core/plugins/conversation-send-facade.ts
+++ b/src/core/plugins/conversation-send-facade.ts
@@ -26,6 +26,11 @@ export interface ConversationSendDeps {
sessionId: string,
opts: { chatId: string; url: string; type: ConversationMediaType; caption?: string },
) => Promise<unknown>;
+ // Location send. The loader binds this to MessageService.sendLocation; `text` maps to the description.
+ sendLocation: (
+ sessionId: string,
+ opts: { chatId: string; latitude: number; longitude: number; description?: string },
+ ) => Promise<unknown>;
}
/**
@@ -39,6 +44,10 @@ const MEDIA_TYPES: readonly ConversationMediaType[] = ['image', 'file', 'audio',
const isMediaType = (type: ConversationSendEnvelope['type']): type is ConversationMediaType =>
(MEDIA_TYPES as readonly string[]).includes(type);
+const isValidLatitude = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v) && v >= -90 && v <= 90;
+const isValidLongitude = (v: unknown): v is number =>
+ typeof v === 'number' && Number.isFinite(v) && v >= -180 && v <= 180;
+
const MESSAGE_HOOK_EVENTS = ['message:sending'];
export function buildConversationSendFacade(deps: ConversationSendDeps) {
@@ -50,6 +59,26 @@ export function buildConversationSendFacade(deps: ConversationSendDeps) {
deps.assertSessionActive(sessionId);
const chatId = env.chatId ?? (await deps.resolveChatId(env));
return deps.runGuarded(MESSAGE_HOOK_EVENTS, async () => {
+ // A location envelope is delivered as a native location pin. Without valid coordinates there
+ // is NOTHING to send — reject loudly instead of degrading to an empty text message.
+ if (env.type === 'location') {
+ // The engine location path cannot quote a message, so a location reply is not expressible.
+ // Reject rather than silently drop the quote (same rule as media).
+ if (env.replyTo) {
+ throw new PluginCapabilityError('conversation.send: replyTo is not supported for location messages');
+ }
+ if (!isValidLatitude(env.latitude) || !isValidLongitude(env.longitude)) {
+ throw new PluginCapabilityError(
+ 'conversation.send: type location requires latitude (-90..90) and longitude (-180..180)',
+ );
+ }
+ return deps.sendLocation(sessionId, {
+ chatId,
+ latitude: env.latitude,
+ longitude: env.longitude,
+ description: env.text,
+ });
+ }
// A media type carrying a mediaUrl is sent as native media. A media type WITHOUT a mediaUrl has
// nothing to send as media, so it falls through to the text/reply path — a plugin that puts the
// URL in `text` as a fallback still delivers a (text) message rather than erroring.
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
index c57af09ac..22228e5aa 100644
--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts
@@ -5,22 +5,35 @@ import { PluginStorageService } from './plugin-storage.service';
import { HookManager } from '../hooks';
import { IPlugin, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
import { PluginWorkerHost } from './sandbox/plugin-worker-host';
+import { PluginLogLevel } from './sandbox/protocol';
-type FakeHost = { load: jest.Mock; runLifecycle: jest.Mock; terminate: jest.Mock };
+type FakeHost = {
+ load: jest.Mock;
+ runLifecycle: jest.Mock;
+ terminate: jest.Mock;
+ dispatchHook: jest.Mock;
+ healthCheck: jest.Mock;
+};
/** Loader that returns fake worker hosts so routing is testable without spawning a real OS thread. */
class TestableLoader extends PluginLoaderService {
readonly hosts: FakeHost[] = [];
capturedOnHookSubscribe?: (event: string, priority?: number) => void;
+ capturedOnLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void;
protected createSandboxHost(
_capDispatcher?: (verb: string, args: unknown[]) => Promise<unknown>,
onHookSubscribe?: (event: string, priority?: number) => void,
+ _onWebhookSubscribe?: (route: string) => void,
+ onLog?: (level: PluginLogLevel, message: string, meta?: Record<string, unknown>) => void,
): PluginWorkerHost {
this.capturedOnHookSubscribe = onHookSubscribe;
+ this.capturedOnLog = onLog;
const host: FakeHost = {
load: jest.fn().mockResolvedValue(undefined),
runLifecycle: jest.fn().mockResolvedValue(undefined),
terminate: jest.fn().mockResolvedValue(undefined),
+ dispatchHook: jest.fn().mockResolvedValue({ continue: true }),
+ healthCheck: jest.fn().mockResolvedValue({ healthy: true }),
};
this.hosts.push(host);
return host as unknown as PluginWorkerHost;
@@ -157,3 +170,114 @@ describe('PluginLoaderService — sandbox tier routing', () => {
expect(pluginOf(loader).status).toBe(PluginStatus.ENABLED);
});
});
+
+describe('PluginLoaderService — sandbox hook error surfacing', () => {
+ type Handler = (hookCtx: { data: unknown; sessionId?: string; source: string }) => Promise<unknown>;
+
+ const loggerOf = (loader: TestableLoader): { warn: jest.Mock; log: jest.Mock } =>
+ (loader as unknown as { logger: { warn: jest.Mock; log: jest.Mock } }).logger;
+
+ /** Enable p1, subscribe it to `event`, and return the shim the loader registered for it. */
+ const setupShim = async (loader: TestableLoader, event: string): Promise<Handler> => {
+ seed(loader, { builtIn: false, instance: null });
+ const hookManager = (loader as unknown as { hookManager: HookManager }).hookManager;
+ const registerSpy = jest.spyOn(hookManager, 'register');
+ await loader.enablePlugin('p1');
+ loader.capturedOnHookSubscribe!(event);
+ const call = registerSpy.mock.calls.find(c => c[1] === event);
+ expect(call).toBeDefined();
+ return call![2];
+ };
+
+ it('logs a worker-reported hook error (rate-limited per event) and surfaces it in plugin health', async () => {
+ const loader = makeLoader();
+ const handler = await setupShim(loader, 'message:sent');
+ // The worker reports (not throws) the handler failure on its hook-result.
+ loader.hosts[0].dispatchHook.mockResolvedValue({ continue: true, error: 'boom' });
+ const warnSpy = jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined);
+
+ await handler({ data: {}, sessionId: 's1', source: 'Engine' });
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Sandboxed plugin p1 hook 'message:sent' handler failed: boom"),
+ expect.objectContaining({ action: 'sandbox_hook_error', pluginId: 'p1', event: 'message:sent' }),
+ );
+
+ // A second failure inside the rate-limit window is counted, not logged again.
+ await handler({ data: {}, sessionId: 's1', source: 'Engine' });
+ expect(warnSpy).toHaveBeenCalledTimes(1);
+
+ // The chain still fails open: the shim resolves continue:true for the hook manager.
+ await expect(handler({ data: {}, sessionId: 's1', source: 'Engine' })).resolves.toEqual({ continue: true });
+
+ // The health surface carries the last hook error without overriding the worker's own verdict.
+ const health = await loader.checkPluginHealth('p1');
+ expect(health.healthy).toBe(true);
+ expect(health.message).toContain("last hook error in 'message:sent'");
+ expect(health.message).toContain('boom');
+
+ // Disable clears the record: a fresh enable starts with a clean slate.
+ await loader.disablePlugin('p1');
+ const after = await loader.checkPluginHealth('p1');
+ expect(after.message ?? '').not.toContain('last hook error');
+ });
+
+ it('does not log or record anything when the worker reports no error', async () => {
+ const loader = makeLoader();
+ const handler = await setupShim(loader, 'message:sent');
+ loader.hosts[0].dispatchHook.mockResolvedValue({ continue: false, data: { n: 1 } });
+ const warnSpy = jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined);
+
+ await expect(handler({ data: {}, sessionId: 's1', source: 'Engine' })).resolves.toEqual({
+ continue: false,
+ data: { n: 1 },
+ });
+ expect(warnSpy).not.toHaveBeenCalled();
+ const health = await loader.checkPluginHealth('p1');
+ expect(health.message ?? '').not.toContain('last hook error');
+ });
+});
+
+describe('PluginLoaderService — sandbox log relay bounds', () => {
+ const loggerOf = (loader: TestableLoader): { warn: jest.Mock; log: jest.Mock } =>
+ (loader as unknown as { logger: { warn: jest.Mock; log: jest.Mock } }).logger;
+
+ it('relays up to the per-window cap, then drops the excess and reports the count at rollover', async () => {
+ jest.useFakeTimers();
+ try {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ await loader.enablePlugin('p1');
+ const logSpy = jest.spyOn(loggerOf(loader), 'log').mockImplementation(() => undefined);
+ const warnSpy = jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined);
+
+ const onLog = loader.capturedOnLog!;
+ for (let i = 0; i < 250; i++) onLog('log', `line ${i}`);
+ expect(logSpy).toHaveBeenCalledTimes(200); // the excess 50 are dropped, not relayed
+ expect(warnSpy).not.toHaveBeenCalled(); // the drop warn fires at the NEXT window rollover
+
+ jest.setSystemTime(Date.now() + 10000);
+ onLog('log', 'next window');
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining('Dropped 50 log messages from sandboxed plugin p1'),
+ expect.objectContaining({ action: 'sandbox_log_relay_dropped', pluginId: 'p1', dropped: 50 }),
+ );
+ expect(logSpy).toHaveBeenCalledTimes(201); // the rollover line relays normally
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('truncates an oversized worker log line before relaying it', async () => {
+ const loader = makeLoader();
+ seed(loader, { builtIn: false, instance: null });
+ await loader.enablePlugin('p1');
+ const logSpy = jest.spyOn(loggerOf(loader), 'log').mockImplementation(() => undefined);
+
+ loader.capturedOnLog!('log', 'x'.repeat(10000));
+
+ expect(logSpy).toHaveBeenCalledTimes(1);
+ const relayed = logSpy.mock.calls[0][0] as string;
+ expect(relayed).toContain('…[truncated]');
+ expect(relayed.length).toBe('[p1] '.length + 8192 + '…[truncated]'.length);
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 114450e00..3b6889eaa 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -72,6 +72,31 @@ const SANDBOX_LIFECYCLE_TIMEOUT_MS = 30000;
*/
const SANDBOX_MAX_INFLIGHT_CAPS = 32;
+/**
+ * Host-side budget for ONE worker-initiated capability call. A plugin whose calls hang would otherwise
+ * hold all SANDBOX_MAX_INFLIGHT_CAPS slots forever (self-DoS). On timeout the worker gets an error and
+ * the slot frees; the late-settling host work is only WARN-logged (see PluginWorkerHost.withCapTimeout —
+ * a bound, not an atomicity guarantee). Default; plugins.capTimeoutMs (PLUGIN_CAP_TIMEOUT_MS) overrides.
+ */
+const SANDBOX_CAP_TIMEOUT_MS = 30000;
+
+/**
+ * Rate limit for the structured sandboxed-hook error log: at most one line per event per window so a
+ * hook that throws on every message can't flood the host log. Suppressed occurrences are counted and
+ * ride the next emitted line.
+ */
+const SANDBOX_HOOK_ERROR_LOG_INTERVAL_MS = 60000;
+
+/**
+ * Worker log-relay bounds (per sandboxed plugin): at most this many lines per window are relayed;
+ * excess is dropped, counted, and surfaced as one warn per window. Longer lines are truncated. The
+ * worker is not a security boundary — these are robustness bounds against a chatty/buggy plugin
+ * flooding the host log, not isolation.
+ */
+const SANDBOX_LOG_MAX_PER_WINDOW = 200;
+const SANDBOX_LOG_WINDOW_MS = 10000;
+const SANDBOX_LOG_MAX_MESSAGE_LENGTH = 8192;
+
/**
* Host process.env keys an untrusted plugin worker is allowed to see. Everything else — secrets like
* API_MASTER_KEY, API_KEY_PEPPER, the DATABASE_/REDIS_ vars, DOCKER_HOST — is withheld. The worker is
@@ -189,6 +214,9 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
private readonly enabling = new Set<string>();
// Live worker host per enabled sandboxed (untrusted) plugin. Built-ins are not in here.
private readonly sandboxHosts = new Map<string, PluginWorkerHost>();
+ // Last hook-handler error each sandboxed plugin's worker reported, surfaced via checkPluginHealth so a
+ // hook that keeps throwing is visible to the operator. Cleared on disable (fresh enable = fresh slate).
+ private readonly lastSandboxHookError = new Map<string, { event: string; error: string; at: Date }>();
// Carries the firing event's sessionId across an in-process hook handler so ctx.config (a getter)
// resolves the per-session slice. Per async call tree, so concurrent sessions don't cross over.
private readonly hookSession = new AsyncLocalStorage<{ sessionId?: string }>();
@@ -641,6 +669,8 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
plugin.status = PluginStatus.DISABLED;
this.pluginStorage.setPluginStatus(pluginId, PluginStatus.DISABLED);
+ // A fresh enable starts with a clean hook-error slate (the state is per runtime, not persisted).
+ this.lastSandboxHookError.delete(pluginId);
this.logger.log(`Plugin disabled: ${plugin.manifest.name}`, {
pluginId,
@@ -810,6 +840,35 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
return plugin;
}
+ /**
+ * Surface a sandboxed plugin's hook-handler failure host-side: record it for the plugin's health
+ * surface and emit one structured warn per event per SANDBOX_HOOK_ERROR_LOG_INTERVAL_MS — a hook
+ * that throws on every message must be visible, but must not become a log-flood vector. Suppressed
+ * occurrences are counted and ride the next emitted line.
+ */
+ private recordSandboxHookError(
+ pluginId: string,
+ event: string,
+ error: string,
+ rateLimit: Map<string, { lastAt: number; suppressed: number }>,
+ ): void {
+ this.lastSandboxHookError.set(pluginId, { event, error, at: new Date() });
+ const now = Date.now();
+ const state = rateLimit.get(event);
+ if (state && now - state.lastAt < SANDBOX_HOOK_ERROR_LOG_INTERVAL_MS) {
+ state.suppressed++;
+ return;
+ }
+ const suppressed = state?.suppressed ?? 0;
+ rateLimit.set(event, { lastAt: now, suppressed: 0 });
+ this.logger.warn(`Sandboxed plugin ${pluginId} hook '${event}' handler failed: ${error}`, {
+ pluginId,
+ event,
+ action: 'sandbox_hook_error',
+ ...(suppressed > 0 ? { suppressed } : {}),
+ });
+ }
+
/**
* Run a plugin's healthCheck across both tiers. A sandboxed plugin's healthCheck lives in the worker
* (plugin.instance is null), so route to the live worker host (time-bounded); built-ins use the
@@ -818,7 +877,14 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
async checkPluginHealth(pluginId: string): Promise<{ healthy: boolean; message?: string }> {
const sandboxHost = this.sandboxHosts.get(pluginId);
if (sandboxHost) {
- return sandboxHost.healthCheck(SANDBOX_HEALTH_TIMEOUT_MS);
+ const result = await sandboxHost.healthCheck(SANDBOX_HEALTH_TIMEOUT_MS);
+ // Attach the last hook-handler error the worker reported: a plugin whose hook throws on every
+ // event can still answer healthCheck "healthy" while doing nothing useful. This is operator
+ // context, not a verdict override — the worker's own healthCheck stays authoritative.
+ const lastError = this.lastSandboxHookError.get(pluginId);
+ if (!lastError) return result;
+ const note = `last hook error in '${lastError.event}' at ${lastError.at.toISOString()}: ${lastError.error}`;
+ return { healthy: result.healthy, message: result.message ? `${result.message}; ${note}` : note };
}
const plugin = this.plugins.get(pluginId);
if (plugin?.instance?.healthCheck) {
@@ -1024,6 +1090,7 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
SANDBOX_MAX_INFLIGHT_CAPS,
onSearchProviderRegister,
onWorkerExit,
+ this.configService.get<number>('plugins.capTimeoutMs') ?? SANDBOX_CAP_TIMEOUT_MS,
);
}
@@ -1091,6 +1158,9 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
if (subscribedEvents.has(event)) 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(
pluginId,
event,
@@ -1145,7 +1215,12 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
action: 'sandbox_hook_timeout',
}),
})
- .then(result => ({ continue: result.continue, data: result.data }));
+ .then(result => {
+ // The worker reports (not throws) a hook-handler failure: surface it host-side instead
+ // of failing open in silence. The chain itself still proceeds fail-open.
+ if (result.error) this.recordSandboxHookError(pluginId, event, result.error, hookErrorLogState);
+ return { continue: result.continue, data: result.data };
+ });
},
priority,
);
@@ -1168,10 +1243,38 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
});
// Route the worker plugin's ctx.logger.* calls to the same per-plugin logger an in-process plugin
- // uses, so sandboxed plugins log identically (prefixed + structured) instead of bare stdout.
+ // uses, so sandboxed plugins log identically (prefixed + structured) instead of bare stdout. The
+ // relay is bounded: oversized lines are truncated and throughput is capped per window — a chatty
+ // or buggy plugin must not flood the host log. Dropped lines are counted and surfaced as one warn
+ // per window (never one line per drop, or the bound itself would be a flood vector). State is local
+ // to this enable call, so it resets on disable.
+ let logWindowStart = Date.now();
+ let logCount = 0;
+ let logDropped = 0;
const onLog = (level: PluginLogLevel, message: string, meta?: Record<string, unknown>): void => {
- if (level === 'error') context.logger.error(message, undefined, meta);
- else context.logger[level](message, meta);
+ const now = Date.now();
+ if (now - logWindowStart >= SANDBOX_LOG_WINDOW_MS) {
+ if (logDropped > 0) {
+ this.logger.warn(
+ `Dropped ${logDropped} log messages from sandboxed plugin ${pluginId} (log relay rate limit)`,
+ { pluginId, action: 'sandbox_log_relay_dropped', dropped: logDropped },
+ );
+ }
+ logWindowStart = now;
+ logCount = 0;
+ logDropped = 0;
+ }
+ logCount++;
+ if (logCount > SANDBOX_LOG_MAX_PER_WINDOW) {
+ logDropped++;
+ return;
+ }
+ const bounded =
+ typeof message === 'string' && message.length > SANDBOX_LOG_MAX_MESSAGE_LENGTH
+ ? `${message.slice(0, SANDBOX_LOG_MAX_MESSAGE_LENGTH)}…[truncated]`
+ : message;
+ if (level === 'error') context.logger.error(bounded, undefined, meta);
+ else context.logger[level](bounded, meta);
};
// When the worker declares itself a search provider (ctx.registerSearchProvider →
@@ -1412,6 +1515,7 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
sendText: (sessionId, opts) => this.getMessageService().sendText(sessionId, opts),
reply: (sessionId, opts) => this.getMessageService().reply(sessionId, opts),
sendMedia: (sessionId, opts) => dispatchConversationMedia(this.getMessageService(), sessionId, opts),
+ sendLocation: (sessionId, opts) => this.getMessageService().sendLocation(sessionId, opts),
} satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability,
handover: {
set: async (key, state) => {
diff --git a/src/core/plugins/plugin-storage.service.spec.ts b/src/core/plugins/plugin-storage.service.spec.ts
index 88abac963..dd1a1c212 100644
--- a/src/core/plugins/plugin-storage.service.spec.ts
+++ b/src/core/plugins/plugin-storage.service.spec.ts
@@ -202,3 +202,57 @@ describe('PluginStorageService.deletePluginData (uninstall storage cleanup)', ()
expect(fs.existsSync(path.join(outside, 'keep.txt'))).toBe(true);
});
});
+
+describe('PluginStorageService per-plugin storage quota', () => {
+ let dataDir: string;
+
+ beforeEach(() => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-pluginquota-'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(dataDir, { recursive: true, force: true });
+ });
+
+ const makeStorage = (maxBytes: number, pluginId = 'quota-plugin') => {
+ const configService = {
+ get: (k: string) => (k === 'dataDir' ? dataDir : k === 'plugins.storageMaxBytes' ? maxBytes : undefined),
+ } as unknown as ConfigService;
+ return new PluginStorageService(configService).createPluginStorage(pluginId);
+ };
+
+ it('rejects a single write larger than the quota and writes nothing', async () => {
+ const storage = makeStorage(1024);
+ await expect(storage.set('big', 'x'.repeat(2000))).rejects.toThrow(/storage quota exceeded/);
+ expect(await storage.list()).toEqual([]);
+ });
+
+ it('bounds the SUM of a plugin’s keys, not just each write', async () => {
+ const storage = makeStorage(1024);
+ await storage.set('a', 'x'.repeat(500)); // 502 bytes on disk (quoted JSON string)
+ await expect(storage.set('b', 'y'.repeat(800))).rejects.toThrow(/storage quota exceeded/);
+ // A smaller second key that still fits under the quota is fine.
+ await expect(storage.set('b', 'y'.repeat(300))).resolves.toBeUndefined();
+ });
+
+ it('does not double-count the key being overwritten', async () => {
+ const storage = makeStorage(1024);
+ await storage.set('a', 'x'.repeat(900)); // 902 bytes
+ // Replacing 'a' must not count its old bytes against the new write.
+ await expect(storage.set('a', 'z'.repeat(800))).resolves.toBeUndefined();
+ expect(await storage.get('a')).toBe('z'.repeat(800));
+ });
+
+ it('counts only the plugin’s own keys — a second plugin has its own quota', async () => {
+ const a = makeStorage(1024, 'plugin-a');
+ const b = makeStorage(1024, 'plugin-b');
+ await a.set('state', 'x'.repeat(900));
+ await expect(b.set('state', 'y'.repeat(900))).resolves.toBeUndefined();
+ });
+
+ it('applies the 50 MiB default when no quota is configured', async () => {
+ const configService = { get: (k: string) => (k === 'dataDir' ? dataDir : undefined) } as unknown as ConfigService;
+ const storage = new PluginStorageService(configService).createPluginStorage('default-quota');
+ await expect(storage.set('state', 'x'.repeat(1000))).resolves.toBeUndefined();
+ });
+});
diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.ts
index 24b8805b7..09851bb7f 100644
--- a/src/core/plugins/plugin-storage.service.ts
+++ b/src/core/plugins/plugin-storage.service.ts
@@ -31,6 +31,13 @@ function atomicWriteFileSync(filePath: string, data: string, options?: { mode?:
const ENCODED_KEY_PREFIX = 'key-';
+/**
+ * Default per-plugin bound on ctx.storage writes (plugins.storageMaxBytes / PLUGIN_STORAGE_MAX_BYTES
+ * overrides). The worker is not a security boundary, but an unbounded storage.set loop would still
+ * fill the host disk — this is a robustness quota, not isolation.
+ */
+const DEFAULT_MAX_PLUGIN_STORAGE_BYTES = 50 * 1024 * 1024;
+
function encodeStorageKey(key: string): string {
return (
ENCODED_KEY_PREFIX +
@@ -57,11 +64,14 @@ export class PluginStorageService {
private readonly logger = createLogger('PluginStorageService');
private readonly dataDir: string;
private readonly registryPath: string;
+ private readonly maxPluginStorageBytes: number;
private registry: Map<string, PluginRegistryEntry> = new Map();
constructor(private readonly configService: ConfigService) {
this.dataDir = this.configService.get<string>('dataDir') ?? './data';
this.registryPath = path.join(this.dataDir, 'plugins', 'registry.json');
+ this.maxPluginStorageBytes =
+ this.configService.get<number>('plugins.storageMaxBytes') ?? DEFAULT_MAX_PLUGIN_STORAGE_BYTES;
this.loadRegistry();
}
@@ -240,6 +250,34 @@ export class PluginStorageService {
}
}
+ /**
+ * Reject a write that would push the plugin's storage past maxPluginStorageBytes. Only the encoded
+ * `key-*.json` files count — they are the only files a plugin can create through this service (new
+ * writes always use the encoded name), and when code and state share a directory the plugin's own
+ * package files must not eat its quota. The file being overwritten is excluded from the current
+ * usage so replacing a large key does not count its bytes twice.
+ */
+ private assertStorageQuota(pluginDataDir: string, targetPath: string, incomingBytes: number, pluginId: string): void {
+ let used = 0;
+ for (const entry of fs.readdirSync(pluginDataDir)) {
+ if (!entry.startsWith(ENCODED_KEY_PREFIX) || !entry.endsWith('.json')) continue;
+ const full = path.join(pluginDataDir, entry);
+ if (full === targetPath) continue;
+ try {
+ used += fs.statSync(full).size;
+ } catch {
+ /* vanished between readdir and stat; ignore */
+ }
+ }
+ if (used + incomingBytes > this.maxPluginStorageBytes) {
+ throw new Error(
+ `Plugin ${pluginId} storage quota exceeded: this write would bring the plugin to ${
+ used + incomingBytes
+ } bytes (max ${this.maxPluginStorageBytes}). Delete unused keys or raise PLUGIN_STORAGE_MAX_BYTES.`,
+ );
+ }
+ }
+
createPluginStorage(pluginId: string): PluginStorage {
const pluginDataDir = path.join(this.dataDir, 'plugins', pluginId);
@@ -299,10 +337,12 @@ export class PluginStorageService {
return Promise.reject(new Error(`Unsafe plugin storage key: ${key}`));
}
try {
+ const payload = JSON.stringify(value, null, 2);
+ this.assertStorageQuota(pluginDataDir, filePath, Buffer.byteLength(payload, 'utf8'), pluginId);
// 0o600 (owner-only): a plugin-persisted secret must not land in a group/other-readable file.
// The mode on the temp write carries through the rename; chmod is a backstop if the target
// pre-existed (writeFileSync mode only applies on create). Mirrors saveRegistry's hardening.
- atomicWriteFileSync(filePath, JSON.stringify(value, null, 2), { mode: 0o600 });
+ atomicWriteFileSync(filePath, payload, { mode: 0o600 });
fs.chmodSync(filePath, 0o600);
// Keep any legacy file in place. Encoded-first reads and de-duplicated lists ensure it cannot
// shadow this write, while avoiding an unlink outside the service-owned key-* namespace.
diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.ts
index 9f4352e05..6850e0d5c 100644
--- a/src/core/plugins/plugin.interfaces.ts
+++ b/src/core/plugins/plugin.interfaces.ts
@@ -268,6 +268,10 @@ export interface ConversationSendEnvelope {
text?: string;
mediaUrl?: string;
replyTo?: string;
+ /** WGS84 coordinates; required for type 'location', ignored otherwise. `text` doubles as the
+ * location description. */
+ latitude?: number;
+ longitude?: number;
source?: { provider: string; externalConversationId: string };
}
diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
index 84737de63..26c2afd9d 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
@@ -194,6 +194,133 @@ describe('PluginWorkerHost', () => {
});
});
+ describe('capability call host timeout', () => {
+ // Microtask-only flush: these tests run under fake timers, where setImmediate is faked too.
+ const microFlush = async (): Promise<void> => {
+ for (let i = 0; i < 10; i++) await Promise.resolve();
+ };
+
+ it('times out a hung call: errors the worker, frees the slot, and warns (once) on late settle', async () => {
+ jest.useFakeTimers();
+ try {
+ const ch = new FakeChannel();
+ let settleHung: (v: unknown) => void = () => undefined;
+ const dispatcher = jest
+ .fn()
+ .mockImplementationOnce(() => new Promise(r => (settleHung = r))) // hangs past the timeout
+ .mockResolvedValue({ ok: true });
+ const onLog = jest.fn();
+ // maxInFlightCaps = 1 (7th arg) so the freed slot is observable; capTimeoutMs = 100 (10th arg).
+ new PluginWorkerHost(ch, dispatcher, undefined, undefined, onLog, undefined, 1, undefined, undefined, 100);
+
+ ch.reply({ kind: 'cap', id: 1, verb: 'messages.sendText', args: [] });
+ await microFlush();
+ expect(dispatcher).toHaveBeenCalledTimes(1);
+
+ jest.advanceTimersByTime(100);
+ await microFlush();
+
+ // The worker sees a timeout error for the hung call.
+ const timedOut = ch.sent.find(m => m.kind === 'cap-result' && m.id === 1) as
+ { ok: boolean; error?: string } | undefined;
+ expect(timedOut?.ok).toBe(false);
+ expect(timedOut?.error).toMatch(/timed out after 100ms/);
+
+ // The slot is freed: a fresh call dispatches immediately and resolves normally.
+ ch.reply({ kind: 'cap', id: 2, verb: 'messages.sendText', args: [] });
+ await microFlush();
+ expect(dispatcher).toHaveBeenCalledTimes(2);
+ expect(ch.sent.find(m => m.kind === 'cap-result' && m.id === 2)).toMatchObject({ ok: true });
+
+ // The hung work eventually settles: no second cap-result for id 1, only a WARN via onLog.
+ settleHung({ late: true });
+ await microFlush();
+ expect(ch.sent.filter(m => m.kind === 'cap-result' && m.id === 1)).toHaveLength(1);
+ expect(onLog).toHaveBeenCalledTimes(1);
+ expect(onLog).toHaveBeenCalledWith(
+ 'warn',
+ expect.stringMatching(/late result was discarded/),
+ expect.objectContaining({ action: 'sandbox_cap_late_settle', verb: 'messages.sendText' }),
+ );
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('warns (not crashes) when the hung work fails after the timeout', async () => {
+ jest.useFakeTimers();
+ try {
+ const ch = new FakeChannel();
+ let failHung: (e: unknown) => void = () => undefined;
+ const dispatcher = jest.fn().mockImplementationOnce(() => new Promise((_, rej) => (failHung = rej)));
+ const onLog = jest.fn();
+ new PluginWorkerHost(
+ ch,
+ dispatcher,
+ undefined,
+ undefined,
+ onLog,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ 100,
+ );
+
+ ch.reply({ kind: 'cap', id: 1, verb: 'engine.getContacts', args: [] });
+ await microFlush();
+ jest.advanceTimersByTime(100);
+ await microFlush();
+ expect(ch.sent.find(m => m.kind === 'cap-result' && m.id === 1)).toMatchObject({ ok: false });
+
+ failHung(new Error('engine blew up'));
+ await microFlush();
+ expect(onLog).toHaveBeenCalledWith(
+ 'warn',
+ expect.stringMatching(/failed after the 100ms host timeout: engine blew up/),
+ expect.objectContaining({ action: 'sandbox_cap_late_settle' }),
+ );
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('leaves a call that settles within the budget untouched (no timeout, no warn)', async () => {
+ jest.useFakeTimers();
+ try {
+ const ch = new FakeChannel();
+ const dispatcher = jest.fn().mockResolvedValue({ messageId: 'wamid' });
+ const onLog = jest.fn();
+ new PluginWorkerHost(
+ ch,
+ dispatcher,
+ undefined,
+ undefined,
+ onLog,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ 1000,
+ );
+
+ ch.reply({ kind: 'cap', id: 1, verb: 'messages.sendText', args: [] });
+ await microFlush();
+ expect(ch.sent.find(m => m.kind === 'cap-result' && m.id === 1)).toMatchObject({
+ ok: true,
+ result: { messageId: 'wamid' },
+ });
+
+ jest.advanceTimersByTime(5000); // budget long past — the timer must have been cleared
+ await microFlush();
+ expect(ch.sent.filter(m => m.kind === 'cap-result' && m.id === 1)).toHaveLength(1);
+ expect(onLog).not.toHaveBeenCalled();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+ });
+
describe('hook bridge', () => {
const flush = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
@@ -245,6 +372,17 @@ describe('PluginWorkerHost', () => {
jest.useRealTimers();
});
+ it('dispatchHook surfaces a worker-reported handler error on the resolved result', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.dispatchHook({ event: 'message:received', data: {}, source: 'Engine', timeoutMs: 1000 });
+ const sent = ch.sent.find(m => m.kind === 'hook') as Extract<HostToWorkerMessage, { kind: 'hook' }>;
+
+ ch.reply({ kind: 'hook-result', id: sent.id, continue: true, error: 'handler blew up' });
+ await expect(pending).resolves.toEqual({ continue: true, error: 'handler blew up' });
+ });
+
it('drains an in-flight hook immediately on worker exit (no stall for the full hook timeout)', async () => {
const ch = new FakeChannel();
const host = new PluginWorkerHost(ch);
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
index 89e2479df..6c7581be8 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -30,7 +30,10 @@ export class PluginWorkerHost {
>();
private readonly hookPending = new Map<
number,
- { resolve: (result: { continue: boolean; data?: unknown }) => void; timer: ReturnType<typeof setTimeout> }
+ {
+ resolve: (result: { continue: boolean; data?: unknown; error?: string }) => void;
+ timer: ReturnType<typeof setTimeout>;
+ }
>();
private readonly webhookPending = new Map<
number,
@@ -97,6 +100,11 @@ export class PluginWorkerHost {
// Called once after the worker exits (crash or terminate), after in-flight calls are drained, so the
// loader can release plugin-owned host resources (e.g. unregister a search provider the worker declared).
private readonly onExit?: (code: number, intentional: boolean) => void,
+ // Host-side budget for ONE capability call. A worker whose calls hang would otherwise hold its
+ // in-flight slots forever (self-DoS once maxInFlightCaps are all wedged). On timeout the worker gets
+ // an error cap-result and the slot frees; the underlying host-side work is NOT cancelled (see
+ // withCapTimeout). Absent/undefined => no per-call timeout (legacy behavior).
+ private readonly capTimeoutMs?: number,
) {
this.channel.onMessage(message => this.handleMessage(message));
this.channel.onExit(code => this.handleExit(code));
@@ -116,7 +124,9 @@ export class PluginWorkerHost {
/**
* 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
- * is never stalled by an untrusted plugin (and `onTimeout` flags it for the caller).
+ * is never stalled by an untrusted plugin (and `onTimeout` flags it for the caller). When the worker
+ * reports that one of its handlers threw, the resolved `error` carries the first failure so the
+ * caller can surface it — the chain still fails open.
*/
dispatchHook(options: {
event: string;
@@ -126,7 +136,7 @@ export class PluginWorkerHost {
config?: Record<string, unknown>;
timeoutMs: number;
onTimeout?: () => void;
- }): Promise<{ continue: boolean; data?: unknown }> {
+ }): Promise<{ continue: boolean; data?: unknown; error?: string }> {
// Fail fast on a dead worker: a post-crash dispatchHook (the hook shim still holds the stale host
// reference) would otherwise post to the dead worker and stall the chain for the full timeout before
// resolving. The fail-open { continue: true } matches what the per-call timeout + the in-flight
@@ -137,7 +147,7 @@ export class PluginWorkerHost {
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 => {
+ const settle = (result: { continue: boolean; data?: unknown; error?: string }): void => {
this.decInFlightHook(options.event);
resolve(result);
};
@@ -351,8 +361,9 @@ export class PluginWorkerHost {
if (!waiter) return;
this.hookPending.delete(message.id);
clearTimeout(waiter.timer);
- const result: { continue: boolean; data?: unknown } = { continue: message.continue };
+ const result: { continue: boolean; data?: unknown; error?: string } = { continue: message.continue };
if (message.data !== undefined) result.data = message.data;
+ if (message.error !== undefined) result.error = message.error;
waiter.resolve(result);
break;
}
@@ -415,8 +426,8 @@ export class PluginWorkerHost {
// 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();
+ const work = this.runWithHookGuard && inFlight.length > 0 ? this.runWithHookGuard(inFlight, run) : run();
+ const result = await this.withCapTimeout(message.verb, work);
this.channel.postMessage({ kind: 'cap-result', id: message.id, ok: true, result });
} catch (error) {
this.channel.postMessage({
@@ -430,6 +441,55 @@ export class PluginWorkerHost {
}
}
+ /**
+ * Bound one capability call host-side. On timeout the caller (the worker) gets an error cap-result
+ * and the in-flight slot frees, so a plugin whose calls hang can't wedge all maxInFlightCaps slots
+ * into a self-DoS. The underlying host-side work is NOT cancelled — host verbs hold no cancellation
+ * token — so when it eventually settles the outcome is only logged as a WARN and its result is
+ * discarded (never a second cap-result). This is a robustness bound, not an atomicity guarantee: a
+ * timed-out call may still complete its side effect late (e.g. a message send that lands after the
+ * caller already saw the timeout error).
+ */
+ private withCapTimeout(verb: string, work: Promise<unknown>): Promise<unknown> {
+ if (this.capTimeoutMs === undefined) return work;
+ const timeoutMs = this.capTimeoutMs;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ // Late settle: warn exactly once, whichever way the work ends. These handlers also keep a
+ // late rejection from surfacing as an unhandled promise rejection.
+ work.then(
+ () =>
+ this.onLog?.(
+ 'warn',
+ `capability '${verb}' settled after the ${timeoutMs}ms host timeout; its late result was discarded`,
+ { action: 'sandbox_cap_late_settle', verb },
+ ),
+ (error: unknown) =>
+ this.onLog?.(
+ 'warn',
+ `capability '${verb}' failed after the ${timeoutMs}ms host timeout: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ { action: 'sandbox_cap_late_settle', verb },
+ ),
+ );
+ reject(new Error(`capability '${verb}' timed out after ${timeoutMs}ms`));
+ }, timeoutMs);
+ work.then(
+ result => {
+ clearTimeout(timer);
+ resolve(result);
+ },
+ (error: unknown) => {
+ clearTimeout(timer);
+ // The worker sees the dispatcher's failure verbatim when it is an Error; wrap anything else
+ // (a hostile/buggy dispatcher rejecting with a non-Error must not break the wire shape).
+ reject(error instanceof Error ? error : new Error(String(error)));
+ },
+ );
+ });
+ }
+
private handleExit(code: number): void {
this.dead = true;
const error = new Error(`plugin worker exited unexpectedly (code ${code})`);
diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
index 6d1d97563..a8fe06a31 100644
--- a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
@@ -12,6 +12,7 @@ const HOOK_HANG_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-hang-pl
const RUNAWAY_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/runaway-plugin.cjs');
const CTX_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-aware-plugin.cjs');
const HOOK_CONFIG_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-config-plugin.cjs');
+const HOOK_ERROR_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-error-plugin.cjs');
const CTX_LIFECYCLE_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-lifecycle-plugin.cjs');
const SEARCH_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/search-plugin.cjs');
const UNLOAD_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/unload-plugin.cjs');
@@ -135,6 +136,24 @@ describe('plugin worker — real worker_threads round-trip (B1)', () => {
await expect(host.terminate()).resolves.toBeUndefined();
});
+ it('a throwing worker hook handler is reported back on the hook-result (not silently swallowed)', async () => {
+ const host = new PluginWorkerHost(makeChannel(), undefined, () => undefined);
+ await host.load(HOOK_ERROR_FIXTURE);
+ await host.runLifecycle('onEnable');
+ await flushAsync();
+
+ // The chain still fails open (continue:true) — but the worker's error crosses the wire so the
+ // host can log it and record it for the plugin's health surface. `data` round-trips untouched.
+ const result = await host.dispatchHook({
+ event: 'message:received',
+ data: {},
+ source: 'Engine',
+ timeoutMs: 5000,
+ });
+ expect(result).toEqual({ continue: true, data: {}, error: 'intentional hook failure' });
+ await host.terminate();
+ });
+
it('preserves a structured-clone-safe hook payload across the worker boundary', async () => {
const host = new PluginWorkerHost(makeChannel(), undefined, () => undefined);
await host.load(HOOK_FIXTURE); // its handler returns { ...data, seen: true }
diff --git a/src/core/plugins/sandbox/worker-hooks.spec.ts b/src/core/plugins/sandbox/worker-hooks.spec.ts
index bb3813975..03849e8b2 100644
--- a/src/core/plugins/sandbox/worker-hooks.spec.ts
+++ b/src/core/plugins/sandbox/worker-hooks.spec.ts
@@ -60,4 +60,28 @@ describe('WorkerHookRegistry', () => {
expect(sent.find(m => m.kind === 'hook-result')).toMatchObject({ continue: true });
});
+
+ it('reports a throwing handler to the host on the hook-result (later handlers still run)', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+ reg.register('e', () => Promise.reject(new Error('boom')), 10);
+ reg.register('e', () => Promise.resolve({ continue: true, data: { n: 2 } }), 20);
+
+ await reg.handleHook({ kind: 'hook', id: 1, event: 'e', data: { x: 1 }, source: 's' });
+
+ // The error rides the result so the host can surface it; the chain's fail-open shape is unchanged.
+ expect(sent.find(m => m.kind === 'hook-result')).toMatchObject({ continue: true, data: { n: 2 }, error: 'boom' });
+ });
+
+ it('reports only the FIRST handler error and stringifies non-Error throws', async () => {
+ const { sent, post } = collect();
+ const reg = new WorkerHookRegistry(post);
+ // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors -- a non-Error rejection is exactly the case under test (it must be stringified, not crash the wire)
+ reg.register('e', () => Promise.reject('string failure'), 10);
+ reg.register('e', () => Promise.reject(new Error('second')), 20);
+
+ await reg.handleHook({ kind: 'hook', id: 1, event: 'e', data: {}, source: 's' });
+
+ expect(sent.find(m => m.kind === 'hook-result')).toMatchObject({ continue: true, error: 'string failure' });
+ });
});
diff --git a/src/core/plugins/sandbox/worker-hooks.ts b/src/core/plugins/sandbox/worker-hooks.ts
index 48d69df11..12a867e3c 100644
--- a/src/core/plugins/sandbox/worker-hooks.ts
+++ b/src/core/plugins/sandbox/worker-hooks.ts
@@ -27,7 +27,9 @@ export type WorkerHookHandler = (ctx: WorkerHookContext) => Promise<WorkerHookRe
* Worker-side hook handling. A sandboxed plugin registers handlers here (via ctx.registerHook). The
* registry subscribes the host to each event the first time it sees a handler for it, and on a `hook`
* message runs the plugin's handlers in priority order — threading data, stopping on continue:false,
- * and swallowing a handler error so one bad handler can't break the chain.
+ * and swallowing a handler error so one bad handler can't break the chain. A swallowed error is NOT
+ * silent: the first failure rides the hook-result back to the host, which logs it and records it for
+ * the plugin's health surface.
*/
export class WorkerHookRegistry {
private readonly handlers = new Map<string, { handler: WorkerHookHandler; priority: number }[]>();
@@ -61,6 +63,7 @@ export class WorkerHookRegistry {
const list = this.handlers.get(message.event) ?? [];
let data = message.data;
let shouldContinue = true;
+ let firstError: string | undefined;
for (const { handler } of list) {
try {
const result = await handler({
@@ -75,10 +78,20 @@ export class WorkerHookRegistry {
shouldContinue = false;
break;
}
- } catch {
- // A handler error must not break the chain (mirrors the host hook manager).
+ } catch (error) {
+ // A handler error must not break the chain (mirrors the host hook manager). Report the FIRST
+ // failure to the host so a throwing hook is visible to the operator instead of failing open
+ // in silence; later handlers still run.
+ firstError ??= error instanceof Error ? error.message : String(error);
}
}
- this.post({ kind: 'hook-result', id: message.id, continue: shouldContinue, data });
+ const result: Extract<WorkerToHostMessage, { kind: 'hook-result' }> = {
+ kind: 'hook-result',
+ id: message.id,
+ continue: shouldContinue,
+ data,
+ };
+ if (firstError !== undefined) result.error = firstError;
+ this.post(result);
}
}
diff --git a/src/modules/search/providers/plugin-search-provider.spec.ts b/src/modules/search/providers/plugin-search-provider.spec.ts
index 72268fb0e..cc6861b09 100644
--- a/src/modules/search/providers/plugin-search-provider.spec.ts
+++ b/src/modules/search/providers/plugin-search-provider.spec.ts
@@ -1,4 +1,4 @@
-import { ServiceUnavailableException } from '@nestjs/common';
+import { BadGatewayException, ServiceUnavailableException } from '@nestjs/common';
import { MessageDirection } from '../../message/entities/message.entity';
import { PluginSearchProvider } from './plugin-search-provider';
import type { PluginSearchTransport } from './plugin-search-provider';
@@ -126,4 +126,60 @@ describe('PluginSearchProvider', () => {
expect(res.hits.map(h => h.sessionId)).toEqual(['s1', 'sX']);
expect(res.total).toBe(2);
});
+
+ describe('result shape validation (untrusted wire payload)', () => {
+ const providerReturning = (results: unknown): PluginSearchProvider =>
+ new PluginSearchProvider(
+ 'p',
+ 'P',
+ fakeTransport({ dispatchSearch: jest.fn().mockResolvedValue({ ok: true, results }) }),
+ 1000,
+ );
+
+ it('rejects a fabricated negative total with a 502 — never a fabricated 200', async () => {
+ await expect(
+ providerReturning({ hits: [], total: -5, tookMs: 1, provider: 'plugin:p' }).search({ q: 'x' }),
+ ).rejects.toBeInstanceOf(BadGatewayException);
+ });
+
+ it('rejects a non-numeric total (a string like "500" would silently break pagination)', async () => {
+ await expect(
+ providerReturning({ hits: [], total: '500', tookMs: 1, provider: 'plugin:p' }).search({ q: 'x' }),
+ ).rejects.toMatchObject({ status: 502 });
+ });
+
+ it('rejects non-array hits with a 502 instead of crashing the re-filter into a 500', async () => {
+ await expect(
+ providerReturning({ hits: 'nope', total: 0, tookMs: 1, provider: 'plugin:p' }).search({
+ q: 'x',
+ sessionIds: ['s1'],
+ }),
+ ).rejects.toBeInstanceOf(BadGatewayException);
+ });
+
+ it('rejects a hit missing required SearchHit fields', async () => {
+ await expect(
+ providerReturning({ hits: [{ messageId: 'm1' }], total: 1, tookMs: 1, provider: 'plugin:p' }).search({
+ q: 'x',
+ }),
+ ).rejects.toMatchObject({ status: 502 });
+ });
+
+ it('rejects a non-object results payload', async () => {
+ await expect(providerReturning(null).search({ q: 'x' })).rejects.toBeInstanceOf(BadGatewayException);
+ await expect(providerReturning('garbage').search({ q: 'x' })).rejects.toBeInstanceOf(BadGatewayException);
+ await expect(providerReturning([1, 2]).search({ q: 'x' })).rejects.toBeInstanceOf(BadGatewayException);
+ });
+
+ it('passes a valid payload with extra fields through untouched (a legit provider never breaks)', async () => {
+ const results = {
+ hits: [{ ...mkHit({}), extraField: { nested: true } }],
+ total: 1,
+ tookMs: 2,
+ provider: 'plugin:p',
+ cursor: 'next-page',
+ };
+ await expect(providerReturning(results).search({ q: 'x' })).resolves.toBe(results);
+ });
+ });
});
diff --git a/src/modules/search/providers/plugin-search-provider.ts b/src/modules/search/providers/plugin-search-provider.ts
index f241b2782..f8352166a 100644
--- a/src/modules/search/providers/plugin-search-provider.ts
+++ b/src/modules/search/providers/plugin-search-provider.ts
@@ -1,4 +1,4 @@
-import { ServiceUnavailableException } from '@nestjs/common';
+import { BadGatewayException, ServiceUnavailableException } from '@nestjs/common';
import type { SearchProvider, SearchQuery, SearchResults, SearchHealth } from '../search.types';
/**
@@ -14,6 +14,54 @@ export interface PluginSearchTransport {
healthCheck(timeoutMs: number): Promise<{ healthy: boolean; message?: string }>;
}
+/** Required string fields of a SearchHit (score stays optional), mirrored for runtime checks. */
+const SEARCH_HIT_STRING_FIELDS = [
+ 'messageId',
+ 'waMessageId',
+ 'sessionId',
+ 'chatId',
+ 'body',
+ 'snippet',
+ 'type',
+ 'direction',
+ 'from',
+] as const;
+
+/**
+ * Validate a SearchResults payload that crossed the worker IPC boundary, returning a description of the
+ * first violation or null when the shape is sound. The worker is not a security boundary and the wire
+ * payload is untrusted: a plugin bug (or hostile worker) can post anything as `results` — a fabricated
+ * `total`, a non-array `hits` (which would 500 the re-filter below), or hits missing the fields the
+ * dashboard renders. Rules mirror the declared SearchResults contract; extra fields are tolerated so an
+ * additive legit provider is never broken.
+ */
+export function validatePluginSearchResults(results: unknown): string | null {
+ if (!results || typeof results !== 'object' || Array.isArray(results)) return 'results must be an object';
+ const r = results as Record<string, unknown>;
+ if (!Array.isArray(r.hits)) return 'results.hits must be an array';
+ if (typeof r.total !== 'number' || !Number.isFinite(r.total) || r.total < 0) {
+ return 'results.total must be a finite number >= 0';
+ }
+ if (typeof r.tookMs !== 'number' || !Number.isFinite(r.tookMs) || r.tookMs < 0) {
+ return 'results.tookMs must be a finite number >= 0';
+ }
+ if (typeof r.provider !== 'string' || r.provider.length === 0) return 'results.provider must be a non-empty string';
+ for (const [index, hit] of (r.hits as unknown[]).entries()) {
+ if (!hit || typeof hit !== 'object' || Array.isArray(hit)) return `results.hits[${index}] must be an object`;
+ const h = hit as Record<string, unknown>;
+ for (const field of SEARCH_HIT_STRING_FIELDS) {
+ if (typeof h[field] !== 'string') return `results.hits[${index}].${field} must be a string`;
+ }
+ if (typeof h.timestamp !== 'number' || !Number.isFinite(h.timestamp)) {
+ return `results.hits[${index}].timestamp must be a finite number`;
+ }
+ if (h.score !== undefined && (typeof h.score !== 'number' || !Number.isFinite(h.score))) {
+ return `results.hits[${index}].score must be a finite number when present`;
+ }
+ }
+ return null;
+}
+
/**
* A SearchProvider backed by a sandboxed plugin's worker. The host routes a query to the worker via the
* search RPC (dispatchSearch); the plugin runs its own backend logic (Meilisearch, Elasticsearch, etc.)
@@ -35,6 +83,10 @@ export class PluginSearchProvider implements SearchProvider {
async search(query: SearchQuery): Promise<SearchResults> {
const reply = await this.transport.dispatchSearch({ query, timeoutMs: this.timeoutMs });
if (!reply.ok) throw new ServiceUnavailableException(reply.error);
+ // The result shape is untrusted wire data: reject an invalid payload with an honest 502 (bad
+ // upstream) instead of fabricating a 200 — or crashing the re-filter below into a 500.
+ const invalid = validatePluginSearchResults(reply.results);
+ if (invalid) throw new BadGatewayException(`Search provider ${this.id} returned invalid results: ${invalid}`);
// Defense-in-depth: the plugin is expected to honor sessionIds, but re-filter host-side so a plugin
// bug or leak can never surface a hit outside the caller's allowed session scope — mirroring the
// SQL-enforced scoping the built-in provider gets for free. The guard mirrors the built-in
diff --git a/test/fixtures/sandbox/hook-error-plugin.cjs b/test/fixtures/sandbox/hook-error-plugin.cjs
new file mode 100644
index 000000000..ac8236e80
--- /dev/null
+++ b/test/fixtures/sandbox/hook-error-plugin.cjs
@@ -0,0 +1,9 @@
+// Sandbox fixture: registers a message:received hook whose handler always throws, so the integration
+// test can assert the failure rides the hook-result back to the host instead of vanishing.
+module.exports = class HookErrorPlugin {
+ async onEnable(ctx) {
+ ctx.registerHook('message:received', async () => {
+ throw new Error('intentional hook failure');
+ });
+ }
+};