Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): four worker-thread sandbox follow-up gaps (#430)

Yudhi Armyndharis3c524c56e977
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 5450a4010..888eaad9c 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -246,3 +246,84 @@ describe('PluginLoaderService — uninstall', () => {
await expect(loader.uninstallPlugin('core-engine')).rejects.toThrow(/built-in/i);
});
});
+
+describe('PluginLoaderService — enable concurrency', () => {
+ let tmpDir: string;
+ let loader: PluginLoaderService;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-enable-'));
+ const config = { get: (k: string) => (k === 'dataDir' ? tmpDir : undefined) } as unknown as ConfigService;
+ loader = new PluginLoaderService(
+ config,
+ new HookManager(),
+ new PluginStorageService(config),
+ {} as unknown as ModuleRef,
+ );
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ it('rejects a racing second enable instead of double-running onEnable', async () => {
+ let enableCount = 0;
+ const instance = {
+ onEnable: async (): Promise<void> => {
+ enableCount++;
+ await new Promise(resolve => setTimeout(resolve, 25)); // keep the first enable in flight
+ },
+ } as unknown as IPlugin;
+ loader.registerBuiltInPlugin(
+ { id: 'race-plg', name: 'Race', version: '1.0.0', type: PluginType.EXTENSION, main: 'index.js' },
+ instance,
+ );
+
+ const results = await Promise.allSettled([loader.enablePlugin('race-plg'), loader.enablePlugin('race-plg')]);
+
+ // The first claims the lock and runs onEnable once; the second is rejected before any await.
+ expect(enableCount).toBe(1);
+ const rejected = results.filter((r): r is PromiseRejectedResult => r.status === 'rejected');
+ expect(rejected).toHaveLength(1);
+ expect(String(rejected[0].reason)).toMatch(/already being enabled/i);
+ expect(loader.getPlugin('race-plg')?.status).toBe(PluginStatus.ENABLED);
+ });
+});
+
+describe('PluginLoaderService — graceful shutdown (onModuleDestroy)', () => {
+ let tmpDir: string;
+ let loader: PluginLoaderService;
+
+ const ext = (id: string): PluginManifest => ({
+ id,
+ name: id,
+ version: '1.0.0',
+ type: PluginType.EXTENSION,
+ main: 'index.js',
+ });
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-shutdown-'));
+ const config = { get: (k: string) => (k === 'dataDir' ? tmpDir : undefined) } as unknown as ConfigService;
+ loader = new PluginLoaderService(
+ config,
+ new HookManager(),
+ new PluginStorageService(config),
+ {} as unknown as ModuleRef,
+ );
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ it('runs onDisable for every enabled plugin on shutdown, best-effort past a failure', async () => {
+ const okDisable = jest.fn(() => Promise.resolve());
+ loader.registerBuiltInPlugin(ext('bad-plg'), {
+ onDisable: () => Promise.reject(new Error('flush failed')),
+ });
+ loader.registerBuiltInPlugin(ext('ok-plg'), { onDisable: okDisable });
+ await loader.enablePlugin('bad-plg');
+ await loader.enablePlugin('ok-plg');
+
+ await expect(loader.onModuleDestroy()).resolves.toBeUndefined();
+
+ // The failing plugin's onDisable error didn't block the other from being disabled.
+ expect(okDisable).toHaveBeenCalledTimes(1);
+ expect(loader.getPlugin('ok-plg')?.status).toBe(PluginStatus.DISABLED);
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 194b39475..816a88988 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, OnModuleInit } from '@nestjs/common';
+import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ModuleRef } from '@nestjs/core';
import * as fs from 'fs';
@@ -31,6 +31,8 @@ import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.in
const SANDBOX_MAX_OLD_GEN_MB = 256;
/** Time budget for a sandboxed plugin's hook handler before the chain proceeds without it. */
const SANDBOX_HOOK_TIMEOUT_MS = 5000;
+/** A sandboxed plugin's healthCheck must answer within this, else it's reported unhealthy (not hung). */
+const SANDBOX_HEALTH_TIMEOUT_MS = 5000;
/**
* Resolve a plugin's `main` entry to an absolute path, asserting it stays inside
@@ -47,9 +49,11 @@ export function resolvePluginMainPath(pluginsDir: string, pluginId: string, main
}
@Injectable()
-export class PluginLoaderService implements OnModuleInit {
+export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {
private readonly logger = createLogger('PluginLoaderService');
private readonly plugins = new Map<string, PluginInstance>();
+ /** Plugin ids whose enable() is in flight — a synchronous lock so concurrent enables can't double-run. */
+ 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>();
private readonly pluginsDir: string;
@@ -81,6 +85,27 @@ export class PluginLoaderService implements OnModuleInit {
});
}
+ /**
+ * Graceful shutdown (SIGTERM → app.close()): run onDisable for every enabled plugin so it can flush
+ * buffers, close connections, and persist state. Previously onDisable only ran via the REST disable
+ * and uninstall paths, so a normal restart/deploy/scale-down skipped it and stateful plugins lost
+ * in-flight work. Best-effort and sequential: one plugin's failure must not block the others.
+ */
+ async onModuleDestroy(): Promise<void> {
+ const enabled = this.getAllPlugins().filter(p => p.status === PluginStatus.ENABLED);
+ for (const plugin of enabled) {
+ try {
+ await this.disablePlugin(plugin.manifest.id);
+ } catch (error) {
+ this.logger.error(
+ `Failed to disable plugin ${plugin.manifest.id} during shutdown`,
+ error instanceof Error ? error.message : String(error),
+ { pluginId: plugin.manifest.id, action: 'plugin_shutdown_disable_failed' },
+ );
+ }
+ }
+ }
+
private loadBuiltInPlugins(): void {
// Built-in plugins are registered programmatically
// This will be used by Phase 4 to register engine plugins
@@ -209,6 +234,15 @@ export class PluginLoaderService implements OnModuleInit {
}
}
+ // Concurrency guard: status flips to ENABLED only AFTER the awaits below, so two concurrent enable
+ // calls would both pass the check above, both run onEnable, and both register the plugin's hooks
+ // (duplicate side effects). Claim the enable synchronously here so a racing caller is rejected
+ // before any await; released in finally.
+ if (this.enabling.has(pluginId)) {
+ throw new Error(`Plugin ${pluginId} is already being enabled`);
+ }
+ this.enabling.add(pluginId);
+
try {
if (plugin.builtIn === false) {
await this.enableSandboxed(pluginId, plugin);
@@ -234,6 +268,8 @@ export class PluginLoaderService implements OnModuleInit {
this.pluginStorage.setPluginStatus(pluginId, PluginStatus.ERROR);
throw error;
+ } finally {
+ this.enabling.delete(pluginId);
}
}
@@ -349,10 +385,17 @@ export class PluginLoaderService implements OnModuleInit {
// Persist config
this.pluginStorage.setPluginConfig(pluginId, plugin.config);
- // Notify plugin of config change (async, fire and forget)
- if (plugin.instance?.onConfigChange && plugin.status === PluginStatus.ENABLED) {
- const context = this.createPluginContext(plugin);
- void plugin.instance.onConfigChange(context, plugin.config);
+ // Notify the running plugin of the config change (fire and forget). A sandboxed plugin's
+ // onConfigChange lives in the worker (plugin.instance is null), so route it through the live worker
+ // host so it refreshes ctx.config too; built-ins go through the in-process instance.
+ if (plugin.status === PluginStatus.ENABLED) {
+ const sandboxHost = this.sandboxHosts.get(pluginId);
+ if (sandboxHost) {
+ sandboxHost.sendConfigChange(plugin.config);
+ } else if (plugin.instance?.onConfigChange) {
+ const context = this.createPluginContext(plugin);
+ void plugin.instance.onConfigChange(context, plugin.config);
+ }
}
this.logger.debug(`Plugin config updated: ${pluginId}`, {
@@ -361,6 +404,23 @@ export class PluginLoaderService implements OnModuleInit {
});
}
+ /**
+ * 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
+ * in-process instance. Returns the default "healthy" when the plugin implements no health check.
+ */
+ 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 plugin = this.plugins.get(pluginId);
+ if (plugin?.instance?.healthCheck) {
+ return plugin.instance.healthCheck();
+ }
+ return { healthy: true, message: 'Plugin does not implement health check' };
+ }
+
/**
* Resolve MessageService at call time via a lazy require so plugin-loader creates NO top-level
* module-load edge to message.service. A static import closes the cycle
diff --git a/src/core/plugins/plugin-storage.service.spec.ts b/src/core/plugins/plugin-storage.service.spec.ts
index 0d0e24d07..5e22b5a74 100644
--- a/src/core/plugins/plugin-storage.service.spec.ts
+++ b/src/core/plugins/plugin-storage.service.spec.ts
@@ -1,3 +1,7 @@
+// Spread the real fs so every method passes through, but as configurable props the test can spy on
+// (the bare `import * as fs` namespace is non-configurable, so jest.spyOn can't redefine its methods).
+jest.mock('fs', () => ({ __esModule: true, ...jest.requireActual<typeof import('fs')>('fs') }));
+
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
@@ -30,6 +34,29 @@ describe('PluginStorageService sandboxed per-plugin storage containment', () =>
expect(await storage.get('state')).toBeNull();
});
+ it('is atomic: a write that fails mid-way leaves the previous file intact (no partial overwrite)', async () => {
+ await storage.set('state', { good: true });
+ // Simulate a crash after the temp file is written but before the rename — the target must keep its
+ // old value, never a truncated/partial one. (A bare writeFileSync would corrupt it here.)
+ const spy = jest.spyOn(fs, 'renameSync').mockImplementationOnce(() => {
+ throw new Error('simulated crash before rename');
+ });
+ await expect(storage.set('state', { bad: true })).rejects.toThrow();
+ spy.mockRestore();
+ expect(await storage.get('state')).toEqual({ good: true });
+ // And no temp file is left behind.
+ const tmps: string[] = [];
+ const walk = (d: string): void => {
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
+ const p = path.join(d, e.name);
+ if (e.isDirectory()) walk(p);
+ else if (e.name.includes('.tmp')) tmps.push(p);
+ }
+ };
+ walk(dataDir);
+ expect(tmps).toEqual([]);
+ });
+
it('preserves JID-style keys containing : @ . -', async () => {
await storage.set('group:sess-1:[email protected]', { announced: true });
expect(await storage.get('group:sess-1:[email protected]')).toEqual({ announced: true });
diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.ts
index e0f90b75a..684f32c94 100644
--- a/src/core/plugins/plugin-storage.service.ts
+++ b/src/core/plugins/plugin-storage.service.ts
@@ -6,6 +6,29 @@ import { createLogger } from '../../common/services/logger.service';
import { isPathWithin } from '../../common/utils/path-safety';
import { PluginStatus, PluginStorage, PluginRegistryEntry } from './plugin.interfaces';
+/** Unique-per-write counter so concurrent writes to the same key don't collide on the temp file. */
+let tmpWriteSeq = 0;
+
+/**
+ * Write to a sibling temp file then atomically rename it into place. POSIX rename is atomic on the
+ * same filesystem, so a crash (SIGKILL/OOM) mid-write can never leave a truncated/corrupt target —
+ * a reader sees either the old complete file or the new complete file, never a partial one.
+ */
+function atomicWriteFileSync(filePath: string, data: string, options?: { mode?: number }): void {
+ const tmp = `${filePath}.${process.pid}.${tmpWriteSeq++}.tmp`;
+ try {
+ fs.writeFileSync(tmp, data, options);
+ fs.renameSync(tmp, filePath);
+ } catch (err) {
+ try {
+ fs.rmSync(tmp, { force: true });
+ } catch {
+ /* best-effort temp cleanup */
+ }
+ throw err;
+ }
+}
+
@Injectable()
export class PluginStorageService {
private readonly logger = createLogger('PluginStorageService');
@@ -46,7 +69,7 @@ export class PluginStorageService {
const entries = Array.from(this.registry.values());
// Owner-only: plugin config can hold secrets (e.g. an API key). writeFileSync's mode only
// applies on CREATE, so chmod an already-existing, looser file too (best-effort).
- fs.writeFileSync(this.registryPath, JSON.stringify(entries, null, 2), { mode: 0o600 });
+ atomicWriteFileSync(this.registryPath, JSON.stringify(entries, null, 2), { mode: 0o600 });
try {
fs.chmodSync(this.registryPath, 0o600);
} catch {
@@ -162,7 +185,7 @@ export class PluginStorageService {
return Promise.reject(new Error(`Unsafe plugin storage key (escapes sandbox): ${key}`));
}
try {
- fs.writeFileSync(filePath, JSON.stringify(value, null, 2));
+ atomicWriteFileSync(filePath, JSON.stringify(value, null, 2));
return Promise.resolve();
} catch (error) {
logger.error(`Failed to write plugin data: ${pluginId}/${key}`, String(error));
diff --git a/src/core/plugins/sandbox/plugin-worker-host.spec.ts b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
index e4ac9bff6..0d3f4d751 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.spec.ts
@@ -249,4 +249,49 @@ describe('PluginWorkerHost', () => {
expect(onLog).toHaveBeenCalledWith('warn', 'heads up', { x: 1 });
});
});
+
+ describe('config change + health check', () => {
+ it('sendConfigChange posts a config-change message to the worker', () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ host.sendConfigChange({ apiKey: 'rotated' });
+
+ expect(ch.last()).toEqual({ kind: 'config-change', config: { apiKey: 'rotated' } });
+ });
+
+ it('healthCheck round-trips and resolves on the worker result', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.healthCheck(1000);
+ const sent = ch.last() as Extract<HostToWorkerMessage, { kind: 'health-check' }>;
+ expect(sent.kind).toBe('health-check');
+
+ ch.reply({ kind: 'health-result', id: sent.id, healthy: false, message: 'missing credentials' });
+ await expect(pending).resolves.toEqual({ healthy: false, message: 'missing credentials' });
+ });
+
+ it('healthCheck resolves unhealthy on timeout so a wedged plugin never hangs the endpoint', async () => {
+ jest.useFakeTimers();
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+
+ const pending = host.healthCheck(100);
+ jest.advanceTimersByTime(100);
+
+ const result = await pending;
+ expect(result.healthy).toBe(false);
+ expect(result.message).toMatch(/timed out/i);
+ jest.useRealTimers();
+ });
+
+ it('healthCheck resolves unhealthy when the worker has exited', async () => {
+ const ch = new FakeChannel();
+ const host = new PluginWorkerHost(ch);
+ ch.crash(1);
+
+ await expect(host.healthCheck(1000)).resolves.toMatchObject({ healthy: false });
+ });
+ });
});
diff --git a/src/core/plugins/sandbox/plugin-worker-host.ts b/src/core/plugins/sandbox/plugin-worker-host.ts
index e05f71fce..d897ce608 100644
--- a/src/core/plugins/sandbox/plugin-worker-host.ts
+++ b/src/core/plugins/sandbox/plugin-worker-host.ts
@@ -24,6 +24,10 @@ export class PluginWorkerHost {
number,
{ resolve: (result: { continue: boolean; data?: unknown }) => void; timer: ReturnType<typeof setTimeout> }
>();
+ private readonly healthPending = new Map<
+ number,
+ { resolve: (result: { healthy: boolean; message?: string }) => void; timer: ReturnType<typeof setTimeout> }
+ >();
constructor(
private readonly channel: PluginWorkerChannel,
@@ -92,6 +96,29 @@ export class PluginWorkerHost {
});
}
+ /** Push a config update to the worker so it refreshes ctx.config and runs onConfigChange. Fire-and-forget. */
+ sendConfigChange(config: Record<string, unknown>): void {
+ if (this.dead) return;
+ this.channel.postMessage({ kind: 'config-change', config });
+ }
+
+ /**
+ * Ask the worker plugin to run healthCheck(). Bounded by `timeoutMs`: a wedged plugin resolves to
+ * unhealthy rather than hanging the health endpoint.
+ */
+ healthCheck(timeoutMs: number): Promise<{ healthy: boolean; message?: string }> {
+ if (this.dead) return Promise.resolve({ healthy: false, message: 'plugin worker is no longer running' });
+ const id = this.nextId++;
+ return new Promise(resolve => {
+ const timer = setTimeout(() => {
+ this.healthPending.delete(id);
+ resolve({ healthy: false, message: 'health check timed out' });
+ }, timeoutMs);
+ this.healthPending.set(id, { resolve, timer });
+ this.channel.postMessage({ kind: 'health-check', id });
+ });
+ }
+
/** Tear the worker down. */
terminate(): Promise<void> {
return this.channel.terminate();
@@ -135,6 +162,14 @@ export class PluginWorkerHost {
waiter.resolve(result);
break;
}
+ case 'health-result': {
+ const waiter = this.healthPending.get(message.id);
+ if (!waiter) return;
+ this.healthPending.delete(message.id);
+ clearTimeout(waiter.timer);
+ waiter.resolve({ healthy: message.healthy, message: message.message });
+ break;
+ }
}
}
@@ -162,6 +197,11 @@ export class PluginWorkerHost {
this.drain(this.readyWaiters, w => w.reject(error));
this.pending.forEach(waiter => waiter.reject(error));
this.pending.clear();
+ this.healthPending.forEach(({ resolve, timer }) => {
+ clearTimeout(timer);
+ resolve({ healthy: false, message: 'plugin worker exited' });
+ });
+ this.healthPending.clear();
}
private drain<T>(waiters: T[], fn: (w: T) => void): void {
diff --git a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
index c5747c35e..e50e1ba19 100644
--- a/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
+++ b/src/core/plugins/sandbox/plugin-worker.integration.spec.ts
@@ -11,6 +11,7 @@ const HOOK_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-plugin.cjs')
const HOOK_HANG_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/hook-hang-plugin.cjs');
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 CTX_LIFECYCLE_FIXTURE = path.resolve(ROOT, 'test/fixtures/sandbox/ctx-lifecycle-plugin.cjs');
const flushAsync = (): Promise<void> => new Promise(resolve => setImmediate(resolve));
// Run the TS bootstrap inside the worker via ts-node. The base tsconfig is nodenext; we pin the
@@ -150,4 +151,20 @@ describe('plugin worker — real worker_threads round-trip (B1)', () => {
expect(logs).toContainEqual({ level: 'log', message: 'hello from ctx-demo', meta: { greeting: 'hi' } });
await host.terminate();
});
+
+ it('delivers healthCheck and onConfigChange to a sandboxed plugin (and refreshes ctx.config)', async () => {
+ const host = new PluginWorkerHost(makeChannel());
+ await host.load(CTX_LIFECYCLE_FIXTURE, { pluginId: 'ctx-lc', config: { a: 1 } });
+ await host.runLifecycle('onEnable');
+
+ // healthCheck reaches the worker plugin and returns ITS result (here it reports its current config).
+ await expect(host.healthCheck(3000)).resolves.toEqual({ healthy: true, message: JSON.stringify({ a: 1 }) });
+
+ // A config change refreshes ctx.config in the worker (and would invoke onConfigChange).
+ host.sendConfigChange({ a: 2 });
+ await flushAsync();
+ await expect(host.healthCheck(3000)).resolves.toEqual({ healthy: true, message: JSON.stringify({ a: 2 }) });
+
+ await host.terminate();
+ });
});
diff --git a/src/core/plugins/sandbox/protocol.ts b/src/core/plugins/sandbox/protocol.ts
index 87698cbe2..6766efb2f 100644
--- a/src/core/plugins/sandbox/protocol.ts
+++ b/src/core/plugins/sandbox/protocol.ts
@@ -26,7 +26,11 @@ export type HostToWorkerMessage =
| { kind: 'cap-result'; id: number; ok: true; result: unknown }
| { kind: 'cap-result'; id: number; ok: false; error: string }
// Dispatch a subscribed hook to the worker; it runs its handler(s) and replies with hook-result.
- | { kind: 'hook'; id: number; event: string; data: unknown; sessionId?: string; source: string };
+ | { kind: 'hook'; id: number; event: string; data: unknown; sessionId?: string; source: string }
+ // The plugin's config was updated: refresh ctx.config and invoke onConfigChange (fire-and-forget).
+ | { kind: 'config-change'; config: Record<string, unknown> }
+ // Ask the worker plugin to run its healthCheck(); it replies with health-result.
+ | { kind: 'health-check'; id: number };
export type WorkerToHostMessage =
| { kind: 'ready' }
@@ -41,6 +45,8 @@ export type WorkerToHostMessage =
| { kind: 'hook-result'; id: number; continue: boolean; data?: unknown; error?: string }
// The worker plugin's ctx.logger.* call, routed to the host's per-plugin logger.
| { kind: 'log'; level: PluginLogLevel; message: string; meta?: Record<string, unknown> }
+ // The worker plugin's healthCheck() result for a host health-check request.
+ | { kind: 'health-result'; id: number; healthy: boolean; message?: string }
| { kind: 'error'; error: string };
/**
diff --git a/src/core/plugins/sandbox/worker-bootstrap.ts b/src/core/plugins/sandbox/worker-bootstrap.ts
index ff13eddaf..ff69d83bf 100644
--- a/src/core/plugins/sandbox/worker-bootstrap.ts
+++ b/src/core/plugins/sandbox/worker-bootstrap.ts
@@ -15,6 +15,8 @@ interface LifecyclePlugin {
onEnable?(context: unknown): unknown;
onDisable?(context: unknown): unknown;
onUnload?(context: unknown): unknown;
+ onConfigChange?(context: unknown, config: Record<string, unknown>): unknown;
+ healthCheck?(): unknown;
}
const port = parentPort;
@@ -86,5 +88,27 @@ async function handle(message: HostToWorkerMessage): Promise<void> {
} catch (error) {
send({ kind: 'lifecycle-result', id: message.id, ok: false, error: errorMessage(error) });
}
+ return;
+ }
+
+ if (message.kind === 'config-change') {
+ // Refresh ctx.config so later reads see the new value, then notify the plugin (fire-and-forget —
+ // onConfigChange returns void, and an ack would just race the next operation).
+ if (context) context.config = message.config;
+ void Promise.resolve(plugin?.onConfigChange?.(context, message.config)).catch(error =>
+ logger.error('onConfigChange threw', error),
+ );
+ return;
+ }
+
+ if (message.kind === 'health-check') {
+ try {
+ const result = plugin?.healthCheck
+ ? ((await plugin.healthCheck()) as { healthy: boolean; message?: string })
+ : { healthy: true, message: 'Plugin does not implement health check' };
+ send({ kind: 'health-result', id: message.id, healthy: result.healthy, message: result.message });
+ } catch (error) {
+ send({ kind: 'health-result', id: message.id, healthy: false, message: errorMessage(error) });
+ }
}
}
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index 2418356c5..88aae1dd4 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -179,12 +179,11 @@ export class PluginsService {
throw new NotFoundException(`Plugin ${id} not found`);
}
- if (!plugin.instance?.healthCheck) {
- return { healthy: true, message: 'Plugin does not implement health check' };
- }
-
try {
- return await plugin.instance.healthCheck();
+ // Delegate to the loader so a sandboxed plugin's healthCheck (which runs in the worker, where
+ // plugin.instance is null) is reached too — the old plugin.instance check always returned the
+ // default "healthy" for sandboxed plugins, blinding health monitoring.
+ return await this.pluginLoader.checkPluginHealth(id);
} catch (error) {
return {
healthy: false,
diff --git a/test/fixtures/sandbox/ctx-lifecycle-plugin.cjs b/test/fixtures/sandbox/ctx-lifecycle-plugin.cjs
new file mode 100644
index 000000000..724602342
--- /dev/null
+++ b/test/fixtures/sandbox/ctx-lifecycle-plugin.cjs
@@ -0,0 +1,15 @@
+// Sandbox fixture: proves onConfigChange + healthCheck reach a sandboxed plugin. It stores ctx from
+// onEnable and reports its CURRENT ctx.config via healthCheck — so after a config change the health
+// message reflects the new config.
+module.exports = class CtxLifecyclePlugin {
+ async onEnable(ctx) {
+ this.ctx = ctx;
+ }
+ async onConfigChange(ctx, config) {
+ this.ctx = ctx;
+ this.changed = config;
+ }
+ async healthCheck() {
+ return { healthy: true, message: JSON.stringify(this.ctx ? this.ctx.config : null) };
+ }
+};