Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): keep a malformed worker message from crashing the host
Yudhi Armyndharis77cf9f202078
diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.tsindex d864b02c7..057a6fa01 100644--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts@@ -478,6 +478,17 @@ describe('PluginLoaderService — sandbox log relay bounds', () => {expect(warnSpy).toHaveBeenCalledTimes(1);});+ it('relays an unknown worker log level as log instead of throwing', async () => {+ // Plugin code can post to parentPort directly, so the level is untrusted: `logger.info` does not exist.+ const loader = makeLoader();+ seed(loader, { builtIn: false, instance: null });+ await loader.enablePlugin('p1');+ const logSpy = jest.spyOn(loggerOf(loader), 'log').mockImplementation(() => undefined);++ expect(() => loader.capturedOnLog!('info' as PluginLogLevel, 'hello')).not.toThrow();+ expect(logSpy).toHaveBeenCalledWith('[p1] hello', { pluginId: 'p1' });+ });+it('truncates an oversized worker log line before relaying it', 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.tsindex a3fafd592..a332193f3 100644--- a/src/core/plugins/plugin-sandbox-bridge.ts+++ b/src/core/plugins/plugin-sandbox-bridge.ts@@ -585,8 +585,11 @@ export class PluginSandboxBridge {typeof message === 'string' && message.length > SANDBOX_LOG_MAX_MESSAGE_LENGTH? `${message.slice(0, SANDBOX_LOG_MAX_MESSAGE_LENGTH)}…[truncated]`: message;+ // The level comes off the wire unchecked (plugin code can post to parentPort directly), and the+ // plugin logger has no method for anything outside PluginLogLevel.if (level === 'error') context.logger.error(bounded, undefined, meta);- else context.logger[level](bounded, meta);+ else if (level === 'debug' || level === 'warn') context.logger[level](bounded, meta);+ else context.logger.log(bounded, meta);};}diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.tsindex 23d72c5fd..00da84a69 100644--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts@@ -39,6 +39,24 @@ class FakeChannel implements PluginWorkerChannel {const lastLifecycle = (ch: FakeChannel) => ch.last() as Extract<HostToWorkerMessage, { kind: 'lifecycle' }>;describe('PluginWorkerHost', () => {+ it('drops a malformed worker message instead of throwing out of the channel listener', async () => {+ // Plugin code can post to parentPort directly; a throw here would be an uncaught exception in the host.+ const ch = new FakeChannel();+ const onLog = jest.fn(() => {+ throw new TypeError('logger[level] is not a function');+ });+ const host = new PluginWorkerHost(ch, undefined, undefined, undefined, onLog);+ const p = host.load('/p/index.js');++ expect(() => ch.reply(null as unknown as WorkerToHostMessage)).not.toThrow();+ expect(() => ch.reply({ kind: 'log', level: 'log', message: 'x' })).not.toThrow();+ expect(onLog).toHaveBeenCalledTimes(1);++ // The host keeps serving the worker afterwards.+ ch.reply({ kind: 'ready' });+ await expect(p).resolves.toBeUndefined();+ });+it('posts a load message and resolves load() when the worker reports ready', 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.tsindex ec2d8bc6c..3635136d9 100644--- a/src/core/plugins/sandbox/plugin-worker-host.ts+++ b/src/core/plugins/sandbox/plugin-worker-host.ts@@ -6,6 +6,9 @@ import {PluginLogLevel,} from './protocol';import type { SearchQuery, SearchResults } from '../../../modules/search/search.types';+import { createLogger } from '../../../common/services/logger.service';++const logger = createLogger('PluginWorkerHost');/*** Capability verbs whose host-side work IS an outbound message send. A media send (the URL@@ -388,6 +391,20 @@ export class PluginWorkerHost {}private handleMessage(message: WorkerToHostMessage): void {+ // Plugin code can post to parentPort directly, so a message is untrusted input. Anything that throws+ // here escapes the channel's listener as an uncaught exception and takes the whole host down.+ if (typeof message !== 'object' || message === null) return;+ try {+ this.routeMessage(message);+ } catch (error) {+ logger.warn(+ `Dropped a malformed sandbox worker message: ${error instanceof Error ? error.message : String(error)}`,+ { action: 'sandbox_worker_message_dropped' },+ );+ }+ }++ private routeMessage(message: WorkerToHostMessage): void {// Only answers to host requests count as progress: a synchronous loop can still post log, cap or// subscribe messages, but it cannot finish a dispatch.if (this.probe && PROGRESS_KINDS.has(message.kind)) this.armProbe(this.probe.id);