Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(plugins): split PluginLoaderService along its jobs

Yudhi Armyndharisb8c062a8b222
diff --git a/src/core/plugins/plugin-lifecycle.ts b/src/core/plugins/plugin-lifecycle.ts
new file mode 100644
index 000000000..5b8b9d250
--- /dev/null
+++ b/src/core/plugins/plugin-lifecycle.ts
@@ -0,0 +1,345 @@
+import { ConfigService } from '@nestjs/config';
+import { createLogger } from '../../common/services/logger.service';
+import { HookManager } from '../hooks';
+import { IPlugin, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
+import { PluginStorageService } from './plugin-storage.service';
+import { PluginHostServices } from './plugin-host-services';
+import { PluginCapabilityContext } from './plugin-capability-context';
+import { PluginSandboxBridge } from './plugin-sandbox-bridge';
+import { PluginWorkerHost } from './sandbox/plugin-worker-host';
+import { unregisterPluginSearchProvider } from './search-provider-registration.util';
+import { resolvePluginMainPath } from './plugin-paths';
+
+/**
+ * The runtime half of the plugin loader: everything that happens to a plugin AFTER the boot scan has
+ * registered it — enable/disable/unload (routing untrusted plugins into the sandbox bridge, trusted
+ * built-ins in-process), operator config and per-session activation writes, and programmatic
+ * built-in registration.
+ *
+ * Split out of PluginLoaderService so the loader reads as the public facade while the lifecycle
+ * state machine — status transitions, the enable concurrency lock, failure cleanup — is reviewed on
+ * its own. A plain class, not a Nest provider: the loader constructs it in its constructor (the same
+ * pattern as PluginSandboxBridge / PluginCapabilityContext), so the loader's public constructor
+ * signature — which specs build directly — is unchanged.
+ */
+export class PluginLifecycle {
+ /** Plugin ids whose enable() is in flight — a synchronous lock so concurrent enables can't double-run. */
+ private readonly enabling = new Set<string>();
+
+ constructor(
+ // The LOADER's logger, deliberately — lifecycle lines carry the PluginLoaderService tag, and
+ // that context is operator-visible. Creating a second logger here would silently retag every
+ // enable/disable log line the moment this moved.
+ private readonly logger: ReturnType<typeof createLogger>,
+ private readonly configService: ConfigService,
+ private readonly hookManager: HookManager,
+ private readonly pluginStorage: PluginStorageService,
+ /** Owns the capability surface handed to plugins — permissions, session scope, engine resolution. */
+ private readonly capabilities: PluginCapabilityContext,
+ /** Owns the sandboxed-worker IPC bridge — enable/teardown, hook/log relay, health + webhook dispatch. */
+ private readonly sandboxBridge: PluginSandboxBridge,
+ /** Resolves the host service ports; see PluginHostServices for why it is not constructor-injected. */
+ private readonly hostServices: PluginHostServices,
+ /** The scanner's registry-entry writer, for programmatic built-in registration. */
+ private readonly ensureRegistryEntry: (manifest: PluginManifest, builtIn: boolean) => void,
+ // The LOADER's registry + sandbox state, passed BY REFERENCE (see the class doc): mutations here
+ // are visible to the loader, the bridge, and to the specs that poke these Maps on the loader.
+ private readonly plugins: Map<string, PluginInstance>,
+ private readonly sandboxHosts: Map<string, PluginWorkerHost>,
+ private readonly lastSandboxHookError: Map<string, { event: string; error: string; at: Date }>,
+ private readonly pluginsDir: string,
+ ) {}
+
+ async enablePlugin(pluginId: string): Promise<void> {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ throw new Error(`Plugin ${pluginId} not found`);
+ }
+
+ if (plugin.status === PluginStatus.ENABLED) {
+ return; // Already enabled
+ }
+
+ // Engines are mutually exclusive and pinned to the deployment's engine.type config (the factory
+ // reads that, not plugin status). Enabling a second engine at runtime would show two "active"
+ // engines and desync the factory, so reject anything but the configured active engine.
+ if (plugin.manifest.type === PluginType.ENGINE) {
+ const activeEngine = this.configService.get<string>('engine.type') ?? 'whatsapp-web.js';
+ if (pluginId !== activeEngine) {
+ throw new Error(
+ `Engine "${pluginId}" is not the active engine ("${activeEngine}"). Set engine.type and restart to switch engines.`,
+ );
+ }
+ }
+
+ // 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.sandboxBridge.enableSandboxed(pluginId, plugin);
+ } else {
+ await this.enableInProcess(pluginId, plugin);
+ }
+
+ plugin.status = PluginStatus.ENABLED;
+ plugin.enabledAt = new Date();
+ plugin.error = undefined;
+
+ // Persist status
+ this.pluginStorage.setPluginStatus(pluginId, PluginStatus.ENABLED);
+
+ this.logger.log(`Plugin enabled: ${plugin.manifest.name}`, {
+ pluginId,
+ action: 'plugin_enabled',
+ });
+ } catch (error) {
+ plugin.status = PluginStatus.ERROR;
+ plugin.error = error instanceof Error ? error.message : String(error);
+
+ this.pluginStorage.setPluginStatus(pluginId, PluginStatus.ERROR);
+
+ // A plugin that subscribed hooks before its onLoad/onEnable threw would otherwise leave those
+ // registrations live: a later successful enable re-registers them, so each event then dispatches
+ // to the plugin once per failed attempt. Drop them here. Safe on this path only — an
+ // already-enabled plugin returns early above, so the catch only runs for an enable that never
+ // went live, which owns no hooks worth keeping. (Idempotent: no-ops when none were registered.)
+ this.hookManager.unregisterPlugin(pluginId);
+
+ throw error;
+ } finally {
+ this.enabling.delete(pluginId);
+ }
+ }
+
+ /**
+ * Disable an enabled plugin (best-effort force-teardown for sandboxed ones). `opts.unload` is set
+ * ONLY by the unload path (uninstall / in-place update): it additionally dispatches the plugin's
+ * onUnload hook. A plain disable (REST / shutdown teardown) deliberately does NOT fire onUnload —
+ * disable is reversible and its cleanup hook is onDisable, while onUnload means "removed from the
+ * runtime". (For a sandboxed plugin the worker thread does die on disable, but terminate() itself
+ * releases its timers/sockets; the hook contract stays: onUnload only on unload.)
+ */
+ async disablePlugin(pluginId: string, opts?: { unload?: boolean }): Promise<void> {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ throw new Error(`Plugin ${pluginId} not found`);
+ }
+
+ if (plugin.status !== PluginStatus.ENABLED) {
+ return; // Not enabled
+ }
+
+ try {
+ const host = this.sandboxHosts.get(pluginId);
+ if (host) {
+ await this.sandboxBridge.teardownSandboxed(pluginId, host, opts);
+ } else {
+ const context = this.capabilities.createPluginContext(plugin);
+ if (plugin.instance?.onDisable) {
+ await plugin.instance.onDisable(context);
+ }
+ }
+
+ // Unregister all hooks for this plugin
+ this.hookManager.unregisterPlugin(pluginId);
+ // Drop the plugin's search-provider entry (if any) so queries don't route to a terminated worker.
+ unregisterPluginSearchProvider(this.hostServices.getSearchRegistryPort(), pluginId);
+
+ 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,
+ action: 'plugin_disabled',
+ });
+ } catch (error) {
+ plugin.status = PluginStatus.ERROR;
+ plugin.error = error instanceof Error ? error.message : String(error);
+ throw error;
+ }
+ }
+
+ async unloadPlugin(pluginId: string): Promise<void> {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ throw new Error(`Plugin ${pluginId} not found`);
+ }
+
+ // Disable first if enabled. `unload: true` so a SANDBOXED plugin also gets its onUnload hook:
+ // disable terminates the worker thread, which would otherwise make onUnload unreachable. An
+ // in-process plugin's onUnload runs below instead (its instance survives disable). A sandboxed
+ // plugin that is already disabled has no live worker left to notify — its resources were
+ // released when the worker terminated, so there is nothing to clean up.
+ if (plugin.status === PluginStatus.ENABLED) {
+ await this.disablePlugin(pluginId, { unload: true });
+ }
+
+ // Call onUnload (in-process plugins; a sandboxed one received it above, before terminate)
+ if (plugin.instance?.onUnload) {
+ const context = this.capabilities.createPluginContext(plugin);
+ await plugin.instance.onUnload(context);
+ }
+
+ this.plugins.delete(pluginId);
+
+ this.logger.log(`Plugin unloaded: ${plugin.manifest.name}`, {
+ pluginId,
+ action: 'plugin_unloaded',
+ });
+ }
+
+ updatePluginConfig(pluginId: string, config: Record<string, unknown>): void {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ throw new Error(`Plugin ${pluginId} not found`);
+ }
+
+ plugin.config = { ...plugin.config, ...config };
+
+ // Persist config
+ this.pluginStorage.setPluginConfig(pluginId, 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.capabilities.createPluginContext(plugin);
+ void plugin.instance.onConfigChange(context, plugin.config);
+ }
+ }
+
+ this.logger.debug(`Plugin config updated: ${pluginId}`, {
+ pluginId,
+ action: 'plugin_config_updated',
+ });
+ }
+
+ /**
+ * Set the sessions a session-scoped plugin is activated for. `['*']` = all numbers (system-wide),
+ * an explicit list scopes it to those sessions, `[]` deactivates it everywhere. Takes effect on the
+ * next hook event (the gate reads plugin.activeSessions live) and survives a restart.
+ */
+ setPluginSessions(pluginId: string, sessions: string[]): PluginInstance {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ throw new Error(`Plugin ${pluginId} not found`);
+ }
+ if (plugin.manifest.sessionScoped === false) {
+ throw new Error(`Plugin ${pluginId} is global (not session-scoped) and cannot be activated per session`);
+ }
+
+ plugin.activeSessions = sessions;
+ this.pluginStorage.setPluginSessions(pluginId, sessions);
+
+ this.logger.log(`Plugin active sessions updated: ${pluginId}`, {
+ pluginId,
+ action: 'plugin_sessions_updated',
+ sessions,
+ });
+ return plugin;
+ }
+
+ /**
+ * Set (or clear) a plugin's per-session config override for `sessionId`. Hooks for that session then
+ * see the override shallow-merged over the base via ctx.config — applied on the next event
+ * (resolution reads plugin.sessionConfig live) and persisted across restart. An empty override
+ * removes it (the session falls back to the base). Global plugins have no per-session config.
+ */
+ setPluginSessionConfig(pluginId: string, sessionId: string, config: Record<string, unknown>): PluginInstance {
+ const plugin = this.plugins.get(pluginId);
+ if (!plugin) {
+ throw new Error(`Plugin ${pluginId} not found`);
+ }
+ if (plugin.manifest.sessionScoped === false) {
+ throw new Error(`Plugin ${pluginId} is global (not session-scoped) and has no per-session config`);
+ }
+
+ const next = { ...(plugin.sessionConfig ?? {}) };
+ if (config && Object.keys(config).length > 0) {
+ next[sessionId] = config;
+ } else {
+ delete next[sessionId];
+ }
+ plugin.sessionConfig = next;
+ this.pluginStorage.setPluginSessionConfig(pluginId, next);
+
+ this.logger.debug(`Plugin session config updated: ${pluginId}`, {
+ pluginId,
+ action: 'plugin_session_config_updated',
+ sessionId,
+ });
+ return plugin;
+ }
+
+ /** Built-in (trusted) enable: require + run the lifecycle in-process with the live capability context. */
+ private async enableInProcess(pluginId: string, plugin: PluginInstance): Promise<void> {
+ const context = this.capabilities.createPluginContext(plugin);
+
+ if (!plugin.instance) {
+ // Containment guard: reject a manifest.main that escapes the plugin dir.
+ // The configured root, not the package dir: this tier runs only for built-ins
+ // (enablePlugin routes `builtIn === false` to the sandbox), and a built-in is registered
+ // programmatically with no on-disk package, so the two resolve identically here.
+ const mainPath = resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const pluginModule = require(mainPath) as { default?: new () => IPlugin };
+ if (pluginModule.default) {
+ plugin.instance = new pluginModule.default();
+ } else {
+ throw new Error(`Plugin ${pluginId} does not export a default class`);
+ }
+ }
+
+ if (plugin.instance.onLoad) {
+ await plugin.instance.onLoad(context);
+ }
+ if (plugin.instance.onEnable) {
+ await plugin.instance.onEnable(context);
+ }
+ }
+
+ registerBuiltInPlugin(manifest: PluginManifest, instance: IPlugin, config: Record<string, unknown> = {}): void {
+ // Merge: env-derived defaults stay live each boot (so a changed .env wins), while an operator's
+ // persisted overrides win for the keys they actually set. Engine config is wholly env-derived
+ // (no persisted overrides), so it is never frozen to a first-boot snapshot.
+ const effectiveConfig = { ...config, ...(this.pluginStorage.getPluginConfig(manifest.id) ?? {}) };
+
+ const pluginInstance: PluginInstance = {
+ manifest,
+ status: PluginStatus.INSTALLED,
+ config: effectiveConfig,
+ instance,
+ loadedAt: new Date(),
+ builtIn: true,
+ // Read persisted per-session activation + config back into the runtime, like loadPlugin —
+ // otherwise the delivery gate falls back to all-sessions/base-config after every restart for a
+ // session-scoped built-in the operator had restricted.
+ activeSessions: this.pluginStorage.getPluginSessions(manifest.id) ?? undefined,
+ sessionConfig: this.pluginStorage.getPluginSessionConfig(manifest.id) ?? undefined,
+ };
+
+ this.plugins.set(manifest.id, pluginInstance);
+
+ // Ensure a registry entry exists so later enable/disable/config writes persist.
+ this.ensureRegistryEntry(manifest, true);
+
+ this.logger.debug(`Built-in plugin registered: ${manifest.name}`, {
+ pluginId: manifest.id,
+ action: 'builtin_plugin_registered',
+ });
+ }
+}
diff --git a/src/core/plugins/plugin-loader-conversation-repair.spec.ts b/src/core/plugins/plugin-loader-conversation-repair.spec.ts
index e46d74d73..6e1cab89c 100644
--- a/src/core/plugins/plugin-loader-conversation-repair.spec.ts
+++ b/src/core/plugins/plugin-loader-conversation-repair.spec.ts
@@ -6,7 +6,7 @@ import { PluginStorageService } from './plugin-storage.service';
import { HookManager } from '../hooks';
import { PluginContext, PluginInstance, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
import { ConversationMappingConflict } from '../../modules/integration/conversation-mapping.service';
-import { PLUGIN_CONVERSATION_MAPPING_PORT, PLUGIN_MESSAGE_PORT, PLUGIN_SESSION_PORT } from './plugin-host-ports';
+import { PLUGIN_CONVERSATION_MAPPING_PORT, PLUGIN_SESSION_PORT } from './plugin-host-ports';
/**
* Stale-mapping repair after a session is deleted and re-paired under a new id. The cross-session
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 0d3f46ae4..f590584aa 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -299,289 +299,6 @@ describe('PluginLoaderService — engine mutual exclusion', () => {
});
});
-describe('PluginLoaderService — uninstall', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let storage: PluginStorageService;
- let loader: PluginLoaderService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-uninst-'));
- pluginsDir = path.join(tmpDir, 'plugins');
- fs.mkdirSync(pluginsDir, { recursive: true });
- const config = {
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
- } as unknown as ConfigService;
- storage = new PluginStorageService(config);
- loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);
- });
- afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
-
- const writeUserPlugin = (id: string): string => {
- const dir = path.join(pluginsDir, id);
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(
- path.join(dir, 'manifest.json'),
- JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
- );
- fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
- return dir;
- };
-
- it('removes the plugin directory, registry entry, and runtime instance', async () => {
- const dir = writeUserPlugin('user-plg');
- loader.loadPlugin(dir);
- expect(storage.getPluginEntry('user-plg')).toBeDefined();
-
- await loader.uninstallPlugin('user-plg');
-
- expect(fs.existsSync(dir)).toBe(false);
- expect(storage.getPluginEntry('user-plg')).toBeUndefined();
- expect(loader.getPlugin('user-plg')).toBeUndefined();
- });
-
- it('refuses to uninstall a built-in plugin', async () => {
- loader.registerBuiltInPlugin(
- { id: 'core-engine', name: 'Core', version: '1.0.0', type: PluginType.ENGINE, main: 'x.js' },
- {},
- );
- await expect(loader.uninstallPlugin('core-engine')).rejects.toThrow(/built-in/i);
- });
-
- it('rejects a plugin that declares ingress routes but omits the webhook:ingress permission', () => {
- // loadPlugin must run validateIngressManifest, so a malformed ingress declaration fails to load
- // rather than silently loading and becoming provisionable.
- const dir = path.join(pluginsDir, 'bad-ingress');
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(
- path.join(dir, 'manifest.json'),
- JSON.stringify({
- id: 'bad-ingress',
- name: 'Bad Ingress',
- version: '1.0.0',
- type: 'extension',
- main: 'index.js',
- ingress: [{ route: 'events', signature: { headerName: 'X-Sig', scheme: 'hmac-sha256' } }],
- // permissions intentionally omitted → validateIngressManifest must reject
- }),
- );
- fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
- expect(() => loader.loadPlugin(dir)).toThrow(/webhook:ingress/i);
- });
-});
-
-describe('PluginLoaderService — skips dot-prefixed directories on load (crash-leftover .bak)', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let loader: PluginLoaderService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-dotskip-'));
- pluginsDir = path.join(tmpDir, 'plugins');
- fs.mkdirSync(pluginsDir, { recursive: true });
- const config = {
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : 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 }));
-
- const writePlugin = (dirName: string, id: string): void => {
- const dir = path.join(pluginsDir, dirName);
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(
- path.join(dir, 'manifest.json'),
- JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
- );
- fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
- };
-
- it('does not scan a crash-leftover .<id>.bak directory (no duplicate-id load race)', () => {
- writePlugin('svc-plg', 'svc-plg');
- writePlugin('.svc-plg.bak', 'svc-plg'); // a leftover update backup carrying the SAME manifest id
-
- const loadSpy = jest.spyOn(loader, 'loadPlugin');
- loader.onModuleInit();
-
- const scanned = loadSpy.mock.calls.map(c => c[0]);
- expect(scanned).toContain(path.join(pluginsDir, 'svc-plg'));
- expect(scanned).not.toContain(path.join(pluginsDir, '.svc-plg.bak'));
- });
-});
-
-describe('PluginLoaderService — prunes registry ghosts of removed built-ins', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let loader: PluginLoaderService;
- let storage: PluginStorageService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-ghosts-'));
- pluginsDir = path.join(tmpDir, 'plugins');
- fs.mkdirSync(pluginsDir, { recursive: true });
- const config = {
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
- } as unknown as ConfigService;
- storage = new PluginStorageService(config);
- loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);
- });
- afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
-
- const seedGhost = (id: string): void => {
- // A leftover directory with no manifest (code deleted) + a stale registry entry still claiming
- // the plugin is installed — the ghost state upgrades from <=0.6 are in.
- fs.mkdirSync(path.join(pluginsDir, id), { recursive: true });
- storage.setPluginEntry({
- id,
- type: 'extension',
- name: id,
- version: '1.0.0',
- status: 'installed',
- config: {},
- builtIn: true,
- installedAt: new Date(),
- updatedAt: new Date(),
- } as never);
- };
-
- it('prunes registry entries of legacy removed built-ins (auto-reply, translation) with no manifest', () => {
- seedGhost('auto-reply');
- seedGhost('translation');
-
- loader.onModuleInit();
-
- expect(storage.getPluginEntry('auto-reply')).toBeUndefined();
- expect(storage.getPluginEntry('translation')).toBeUndefined();
- });
-
- it('keeps a manifest-less NON-legacy plugin entry (config survives an unreadable dir)', () => {
- seedGhost('some-other-plugin');
-
- loader.onModuleInit();
-
- expect(storage.getPluginEntry('some-other-plugin')).toBeDefined();
- });
-});
-
-describe('PluginLoaderService — boot reconciles the registry entry of a plugin it drops', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let storage: PluginStorageService;
-
- const config = () =>
- ({
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
- }) as unknown as ConfigService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-drop-'));
- pluginsDir = path.join(tmpDir, 'plugins');
- fs.mkdirSync(pluginsDir, { recursive: true });
- storage = new PluginStorageService(config());
- });
- afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
-
- const makeLoader = (): PluginLoaderService =>
- new PluginLoaderService(config(), new HookManager(), storage, {} as unknown as ModuleRef);
-
- const writePlugin = (id: string, manifest: Record<string, unknown>): void => {
- const dir = path.join(pluginsDir, id);
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest));
- fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
- };
-
- it('marks the persisted entry ERROR when boot-time manifest validation drops a previously-installed plugin', () => {
- // Boot 1: a valid hand-placed plugin loads and gets its registry entry.
- writePlugin('hand-placed', {
- id: 'hand-placed',
- name: 'Hand',
- version: '1.0.0',
- type: 'extension',
- main: 'index.js',
- });
- makeLoader().onModuleInit();
- expect(storage.getPluginEntry('hand-placed')?.status).toBe(PluginStatus.INSTALLED);
- // The operator's config + standing enable decision live in that entry.
- storage.setPluginConfig('hand-placed', { apiKey: 'keep-me' });
- storage.setPluginEnabledByOperator('hand-placed', true);
-
- // Boot 2: the manifest was hand-edited into something the installer would have rejected
- // (missing required field) — the plugin is dropped from the runtime...
- writePlugin('hand-placed', { id: 'hand-placed', name: 'Hand', type: 'extension', main: 'index.js' });
- const loader2 = makeLoader();
- loader2.onModuleInit();
- expect(loader2.getPlugin('hand-placed')).toBeUndefined();
-
- // ...and the registry no longer claims it installed. The entry itself (config,
- // enabledByOperator) survives, so fixing the manifest and rebooting re-enables it.
- const entry = storage.getPluginEntry('hand-placed');
- expect(entry?.status).toBe(PluginStatus.ERROR);
- expect(entry?.config).toEqual({ apiKey: 'keep-me' });
- expect(entry?.enabledByOperator).toBe(true);
- });
-
- it('a hand-placed plugin that fails validation without a registry entry simply does not load', () => {
- writePlugin('never-installed', { id: 'never-installed', name: 'Nope', type: 'extension', main: 'index.js' });
-
- const loader = makeLoader();
- loader.onModuleInit();
-
- expect(loader.getPlugin('never-installed')).toBeUndefined();
- // No entry existed, so the ERROR reconciliation is a no-op — none is invented either.
- expect(storage.getPluginEntry('never-installed')).toBeUndefined();
- });
-});
-
-describe('PluginLoaderService — loadPlugin seeds configSchema defaults', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let loader: PluginLoaderService;
- let storage: PluginStorageService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-seed-'));
- pluginsDir = path.join(tmpDir, 'plugins');
- fs.mkdirSync(pluginsDir, { recursive: true });
- const config = {
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
- } as unknown as ConfigService;
- storage = new PluginStorageService(config);
- loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);
- });
- afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
-
- it('seeds defaults into the runtime instance and the persisted registry entry at load', () => {
- const dir = path.join(pluginsDir, 'seeded-plg');
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(
- path.join(dir, 'manifest.json'),
- JSON.stringify({
- id: 'seeded-plg',
- name: 'seeded-plg',
- version: '1.0.0',
- type: 'extension',
- main: 'index.js',
- configSchema: {
- type: 'object',
- properties: { timezone: { type: 'string', default: 'UTC' } },
- },
- }),
- );
- fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
-
- loader.onModuleInit();
-
- expect(loader.getPlugin('seeded-plg')?.config).toEqual({ timezone: 'UTC' });
- expect(storage.getPluginEntry('seeded-plg')?.config).toEqual({ timezone: 'UTC' });
- });
-});
-
describe('PluginLoaderService — enable concurrency', () => {
let tmpDir: string;
let loader: PluginLoaderService;
@@ -1009,157 +726,6 @@ describe('PluginLoaderService — search-provider worker-crash fallback', () =>
});
});
-describe('PluginLoaderService — boot-time manifest validation parity with install', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let loader: PluginLoaderService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-bootval-'));
- pluginsDir = path.join(tmpDir, 'plugins');
- fs.mkdirSync(pluginsDir, { recursive: true });
- const config = {
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : 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 }));
-
- const writePlugin = (id: string, manifest: unknown, withMain = true): string => {
- const dir = path.join(pluginsDir, id);
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(
- path.join(dir, 'manifest.json'),
- typeof manifest === 'string' ? manifest : JSON.stringify(manifest),
- );
- if (withMain) fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
- return dir;
- };
- const baseManifest = (id: string): Record<string, unknown> => ({
- id,
- name: id,
- version: '1.0.0',
- type: 'extension',
- main: 'index.js',
- });
-
- it('rejects the same invalid manifests install rejects (fields, id, reserved, type)', () => {
- // Missing a required field.
- const noName = baseManifest('no-name');
- delete noName.name;
- expect(() => loader.loadPlugin(writePlugin('no-name', noName))).toThrow(/required field: name/i);
- // A non-string required field (truthy — passed the old bare falsy check).
- expect(() => loader.loadPlugin(writePlugin('num-main', { ...baseManifest('num-main'), main: 123 }))).toThrow(
- /invalid required field/i,
- );
- // Unsafe id.
- expect(() => loader.loadPlugin(writePlugin('bad id', { ...baseManifest('bad id'), id: 'bad id' }))).toThrow(
- /invalid plugin id/i,
- );
- // Reserved built-in id (would shadow the baileys engine).
- expect(() => loader.loadPlugin(writePlugin('baileys', baseManifest('baileys')))).toThrow(/reserved/i);
- // A non-extension tier (engines are built-in, never directory-loadable).
- expect(() => loader.loadPlugin(writePlugin('my-eng', { ...baseManifest('my-eng'), type: 'engine' }))).toThrow(
- /not installable/i,
- );
- // A non-object manifest document.
- expect(() => loader.loadPlugin(writePlugin('arr-plg', '[]'))).toThrow(/must be a JSON object/i);
- });
-
- it('rejects a manifest whose main escapes the plugin directory', () => {
- const dir = writePlugin('trav-plg', { ...baseManifest('trav-plg'), main: '../other/evil.js' });
- expect(() => loader.loadPlugin(dir)).toThrow(/escapes the plugin directory/i);
- });
-
- it('rejects a manifest whose main file is missing from the directory', () => {
- const dir = writePlugin('gone-main', { ...baseManifest('gone-main'), main: 'gone.js' });
- expect(() => loader.loadPlugin(dir)).toThrow(/main file not found/i);
- });
-});
-
-describe('PluginLoaderService — interrupted-update recovery at boot', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let loader: PluginLoaderService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-uprec-'));
- pluginsDir = path.join(tmpDir, 'plugins');
- fs.mkdirSync(pluginsDir, { recursive: true });
- const config = {
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : 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 }));
-
- const writePluginTree = (dirName: string, id: string, version = '1.0.0'): void => {
- const dir = path.join(pluginsDir, dirName);
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(
- path.join(dir, 'manifest.json'),
- JSON.stringify({ id, name: id, version, type: 'extension', main: 'index.js' }),
- );
- fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
- };
-
- it('restores the backup as the live dir when a crash mid-swap lost the live dir', () => {
- // Crash between `rename(live → backup)` and `rename(staging → live)`: the live dir is gone, the
- // backup holds the previous version, and staging never landed.
- writePluginTree('.svc-plg.bak', 'svc-plg');
- writePluginTree('.svc-plg.new', 'svc-plg', '2.0.0');
-
- loader.onModuleInit();
-
- // The previous version is back as the live dir and loads normally — the plugin no longer
- // silently vanishes while its registry entry still claims it is installed.
- expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');
- expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'))).toBe(true);
- expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);
- expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);
- });
-
- it('drops a stale backup when the live dir exists (crash after the swap completed)', () => {
- writePluginTree('svc-plg', 'svc-plg', '2.0.0'); // the swapped-in new version
- writePluginTree('.svc-plg.bak', 'svc-plg'); // leftover backup of the old one
-
- loader.onModuleInit();
-
- expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('2.0.0');
- expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);
- });
-
- it('drops a stale staging tree (crash before the swap ever started)', () => {
- writePluginTree('svc-plg', 'svc-plg');
- writePluginTree('.svc-plg.new', 'svc-plg', '2.0.0');
-
- loader.onModuleInit();
-
- expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');
- expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);
- });
-
- it('leaves an unrelated dot-prefixed directory alone', () => {
- writePluginTree('svc-plg', 'svc-plg');
- fs.mkdirSync(path.join(pluginsDir, '.gitkeep.d'), { recursive: true });
-
- loader.onModuleInit();
-
- expect(fs.existsSync(path.join(pluginsDir, '.gitkeep.d'))).toBe(true);
- expect(loader.getPlugin('svc-plg')).toBeDefined();
- });
-});
-
describe('PluginLoaderService — onUnload dispatch', () => {
let tmpDir: string;
let pluginsDir: string;
@@ -1262,59 +828,6 @@ describe('PluginLoaderService — onUnload dispatch', () => {
});
});
-describe('PluginLoaderService — uninstall cleans up split-dir plugin storage', () => {
- let tmpDir: string;
- let pluginsDir: string;
- let dataDir: string;
- let loader: PluginLoaderService;
- let storage: PluginStorageService;
-
- beforeEach(() => {
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-splitstore-'));
- // Split-dir deployment: the package dir and the ctx.storage data dir are NOT the same tree.
- pluginsDir = path.join(tmpDir, 'plugins');
- dataDir = path.join(tmpDir, 'data');
- fs.mkdirSync(pluginsDir, { recursive: true });
- const config = {
- get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? dataDir : undefined),
- } as unknown as ConfigService;
- storage = new PluginStorageService(config);
- loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);
- });
- afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
-
- const writeUserPlugin = (id: string): string => {
- const dir = path.join(pluginsDir, id);
- fs.mkdirSync(dir, { recursive: true });
- fs.writeFileSync(
- path.join(dir, 'manifest.json'),
- JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
- );
- fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
- return dir;
- };
-
- it('removes the plugin’s storage dir on uninstall, and only that plugin’s', async () => {
- const dir = writeUserPlugin('user-plg');
- writeUserPlugin('other-plg');
- loader.loadPlugin(dir);
- loader.loadPlugin(path.join(pluginsDir, 'other-plg'));
- // Persist real ctx.storage state for both plugins (split-dir: under <dataDir>/plugins/<id>).
- await storage.createPluginStorage('user-plg').set('token', { secret: 'abc' });
- await storage.createPluginStorage('other-plg').set('token', { secret: 'xyz' });
- const userStorageDir = path.join(dataDir, 'plugins', 'user-plg');
- const otherStorageDir = path.join(dataDir, 'plugins', 'other-plg');
- expect(fs.existsSync(userStorageDir)).toBe(true);
-
- await loader.uninstallPlugin('user-plg');
-
- expect(fs.existsSync(dir)).toBe(false); // package dir (unchanged behavior)
- expect(fs.existsSync(userStorageDir)).toBe(false); // split-dir storage is now cleaned too
- expect(fs.existsSync(otherStorageDir)).toBe(true); // another plugin's storage is untouched
- expect(await storage.createPluginStorage('other-plg').get('token')).toEqual({ secret: 'xyz' });
- });
-});
-
/**
* Where the loader looks for plugin code at boot.
*
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index ec8eea2aa..a5702b5fc 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -2,34 +2,40 @@ import { Injectable, OnApplicationBootstrap, OnModuleInit, OnModuleDestroy, Opti
import { ConfigService } from '@nestjs/config';
import { ModuleRef } from '@nestjs/core';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
-import * as fs from 'fs';
import * as path from 'path';
import { DEFAULT_PLUGINS_DIR } from '../../config/configuration';
import { createLogger } from '../../common/services/logger.service';
import { HookManager } from '../hooks';
import {
- PluginManifest,
+ IPlugin,
PluginInstance,
+ PluginManifest,
PluginRegistryEntry,
PluginStatus,
- IPlugin,
PluginType,
- validateIngressManifest,
- warnUnauthenticatedIngressRoutes,
- warnUnsignedTimestampRoutes,
} from './plugin.interfaces';
-import { validatePluginManifest } from './plugin-manifest';
import { PluginStorageService } from './plugin-storage.service';
-import { seedConfigDefaults } from './config-defaults.util';
import { PluginHostServices } from './plugin-host-services';
import { PluginCapabilityContext } from './plugin-capability-context';
import { PluginSandboxBridge } from './plugin-sandbox-bridge';
+import { PluginPackageScanner } from './plugin-package-scanner';
+import { PluginLifecycle } from './plugin-lifecycle';
+import { PluginUninstaller } from './plugin-uninstaller';
import { PluginWorkerHost } from './sandbox/plugin-worker-host';
import { WorkerThreadChannel } from './sandbox/worker-thread-channel';
import { PluginLogLevel } from './sandbox/protocol';
-import { unregisterPluginSearchProvider } from './search-provider-registration.util';
+import { resolvePluginMainPath } from './plugin-paths';
import type { IngressJobData } from '../../modules/queue/processors/ingress.processor';
+// The shared path/containment helpers stay re-exported from this module: the feature-side installer
+// (PluginsService) and the specs import them from here / from the core barrel.
+export {
+ resolvePluginMainPath,
+ resolvePluginEntryPath,
+ pluginUpdateStagingDirName,
+ pluginUpdateBackupDirName,
+} from './plugin-paths';
+
/** Default per-plugin heap cap for the sandbox worker; an OOM terminates the worker, not the host. */
const SANDBOX_MAX_OLD_GEN_MB = 256;
@@ -54,43 +60,6 @@ const SANDBOX_CAP_TIMEOUT_MS = 30000;
*/
const SANDBOX_ENV_ALLOWLIST = ['NODE_ENV', 'NODE_EXTRA_CA_CERTS', 'TZ'] as const;
-/**
- * Resolve a plugin's `main` entry to an absolute path, asserting it stays inside
- * <pluginsDir>/<pluginId>. `main` comes from a user-supplied manifest, so a
- * value like '../../etc/passwd' (or an absolute path) must be rejected BEFORE require().
- */
-export function resolvePluginMainPath(pluginsDir: string, pluginId: string, main: string): string {
- const base = path.resolve(pluginsDir, pluginId);
- const mainPath = path.resolve(base, main);
- if (mainPath !== base && !mainPath.startsWith(base + path.sep)) {
- throw new Error(`Plugin ${pluginId} main path escapes the plugin directory`);
- }
- return mainPath;
-}
-
-/**
- * The same containment guard, anchored to a plugin's own package directory rather than to the
- * configured plugins root. Callers that hold a loaded plugin's `packageDir` use this: the package
- * may sit in the legacy directory, in which case resolving against `plugins.dir` names a file that
- * does not exist.
- */
-export function resolvePluginEntryPath(packageDir: string, entry: string): string {
- return resolvePluginMainPath(path.dirname(packageDir), path.basename(packageDir), entry);
-}
-
-/**
- * Sibling directory names an in-place plugin update stages into / backs up to (see
- * PluginsService.updatePackageInner). Dot-prefixed so the boot directory scan skips them, and placed
- * inside the plugins dir so the swap renames stay on one filesystem (EXDEV-safe). The loader's
- * boot-time reconciler (recoverInterruptedUpdates) keys off these exact names.
- */
-export function pluginUpdateStagingDirName(pluginId: string): string {
- return `.${pluginId}.new`;
-}
-export function pluginUpdateBackupDirName(pluginId: string): string {
- return `.${pluginId}.bak`;
-}
-
/**
* Build the minimal, allowlisted env for an untrusted plugin worker so it never inherits host secrets.
* Only {@link SANDBOX_ENV_ALLOWLIST} keys are forwarded (unset keys are omitted, not emitted as
@@ -105,41 +74,29 @@ export function buildSandboxWorkerEnv(source: NodeJS.ProcessEnv = process.env):
return env;
}
-// Plugin ids whose bundled-extension code was permanently removed (v0.7 — superseded by the
-// marketplace chat-flow / group-translate; also reserved in plugin-installer). A leftover
-// directory without a manifest marks them as deleted on disk, so the stale registry entry (which
-// still reports them installed/enabled) is pruned on boot. Scoped to these known ids so a
-// temporarily-unreadable plugin dir (e.g. an unmounted volume) never loses its persisted config.
-const LEGACY_REMOVED_PLUGIN_IDS = new Set(['auto-reply', 'translation']);
-
/**
- * Whether `dir` holds at least one loadable plugin package — a non-dot subdirectory with a manifest.
- * Existence of the directory, or of subdirectories in it, proves nothing: <dataDir>/plugins is also
- * where the registry and every plugin's ctx.storage live, so it is routinely full of directories that
- * hold only `key-*.json` state. Unreadable or missing counts as "no packages": this only ever decides
- * whether to scan a fallback location, never whether to delete anything.
+ * The public facade of the plugin runtime. Every consumer — the REST surface, the installer, the
+ * engine factory, the ingress pipeline — keeps calling this class; the jobs behind the surface are
+ * collocated collaborators constructed below, each owning one job and sharing the loader's registry
+ * Maps BY REFERENCE (so the specs that poke them on the loader and the collaborators see one map):
+ *
+ * - {@link PluginPackageScanner} — boot scan/registry: find packages on disk, validate manifests,
+ * recover interrupted updates, keep the persisted registry entries honest.
+ * - {@link PluginLifecycle} — enable/disable/unload, config + per-session activation writes,
+ * programmatic built-in registration.
+ * - {@link PluginUninstaller} — full removal of an installed user plugin.
+ * - {@link PluginCapabilityContext} — the capability surface handed to plugins.
+ * - {@link PluginSandboxBridge} — the sandboxed-worker IPC bridge (spawn/teardown, relay, health,
+ * ingress dispatch). The loader keeps only the protected worker-host factory seam the bridge
+ * calls back through, so spec subclasses can still inject fakes.
+ *
+ * What remains HERE is the facade itself: the Nest lifecycle hooks, the registry reads, and the
+ * delegation to each collaborator.
*/
-function hasPluginPackages(dir: string): boolean {
- try {
- return fs
- .readdirSync(dir, { withFileTypes: true })
- .some(
- entry =>
- entry.isDirectory() &&
- !entry.name.startsWith('.') &&
- fs.existsSync(path.join(dir, entry.name, 'manifest.json')),
- );
- } catch {
- return false;
- }
-}
-
@Injectable()
export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap, 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>();
// Last hook-handler error each sandboxed plugin's worker reported, surfaced via checkPluginHealth so a
@@ -154,12 +111,18 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
* directory explicitly, and null for a ConfigService that carries no app config (unit tests).
*/
private readonly legacyPluginsDir: string | null;
- /** Resolves host services at call time; see PluginHostServices for why it is not constructor-injected. */
+ /** Resolves the host service ports at call time; see PluginHostServices for why it is not ctor-injected. */
private readonly hostServices: PluginHostServices;
/** Owns the capability surface handed to plugins — permissions, session scope, engine resolution. */
private readonly capabilities: PluginCapabilityContext;
/** Owns the sandboxed-worker IPC bridge — enable/teardown, hook/log relay, health + webhook dispatch. */
private readonly sandboxBridge: PluginSandboxBridge;
+ /** Owns the boot scan/registry job — package discovery, manifest validation, crash recovery. */
+ private readonly scanner: PluginPackageScanner;
+ /** Owns the runtime job — enable/disable/unload, config + session activation writes, built-in registration. */
+ private readonly lifecycle: PluginLifecycle;
+ /** Owns the removal job — uninstall of an installed user plugin. */
+ private readonly uninstaller: PluginUninstaller;
constructor(
private readonly configService: ConfigService,
@@ -219,69 +182,40 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
onSearchProviderRegister,
onWorkerExit,
),
- // Exported above (specs import it from this module); passed so the bridge never imports back.
+ // Exported from this module (specs import it here); passed so the bridge never imports back.
resolvePluginMainPath,
);
+ this.scanner = new PluginPackageScanner(
+ this.logger,
+ this.configService,
+ this.pluginStorage,
+ this.pluginsDir,
+ this.legacyPluginsDir,
+ // Shared BY REFERENCE, like the bridge's maps: the loader's registry reads below and the
+ // scanner's writes are one and the same map.
+ this.plugins,
+ );
+ this.lifecycle = new PluginLifecycle(
+ this.logger,
+ this.configService,
+ this.hookManager,
+ this.pluginStorage,
+ this.capabilities,
+ this.sandboxBridge,
+ this.hostServices,
+ (manifest, builtIn) => this.scanner.ensureRegistryEntry(manifest, builtIn),
+ this.plugins,
+ this.sandboxHosts,
+ this.lastSandboxHookError,
+ this.pluginsDir,
+ );
+ this.uninstaller = new PluginUninstaller(this.logger, this.plugins, this.pluginStorage, this.pluginsDir, pluginId =>
+ this.lifecycle.unloadPlugin(pluginId),
+ );
}
onModuleInit(): void {
- // Load built-in plugins first (synchronous registration)
- this.loadBuiltInPlugins();
-
- // Then load user plugins if directory exists
- if (fs.existsSync(this.pluginsDir)) {
- this.loadPluginsFromDirectory(this.pluginsDir);
- }
-
- // COMPATIBILITY PATH — hosts that installed plugins before the package dir moved under <dataDir>.
- // Their code sits in the old ./plugins, which was self-consistent while the loader and the
- // installer both used that default, so changing the default must not take those plugins away.
- // Scanned in ADDITION to the configured dir rather than instead of it, so a host part-way through
- // migrating keeps both halves; the configured copy loads first and wins any duplicate id. Never
- // runs when PLUGINS_DIR is set (legacyDir is null then). Keyed on finding a real plugin package,
- // not on the directory existing: <dataDir>/plugins/<id> doubles as the plugin's ctx.storage dir,
- // so directories with no code in them are routine.
- if (this.legacyPluginsDir && hasPluginPackages(this.legacyPluginsDir)) {
- this.logger.warn(
- `Loading plugins from the legacy directory ${this.legacyPluginsDir}: the default moved to ` +
- `${this.pluginsDir}, where the plugin registry and every new install already are. Move them ` +
- `(mv ${this.legacyPluginsDir}/* ${this.pluginsDir}/) or keep the old location by setting ` +
- `PLUGINS_DIR=${this.legacyPluginsDir}. In Docker this matters: a directory outside the data ` +
- `volume is destroyed on the next container recreate.`,
- { action: 'plugins_legacy_dir', legacyDir: this.legacyPluginsDir, pluginsDir: this.pluginsDir },
- );
- this.loadPluginsFromDirectory(this.legacyPluginsDir);
- }
-
- this.logger.log(`Loaded ${this.plugins.size} plugins`, {
- action: 'plugins_loaded',
- count: this.plugins.size,
- });
-
- this.warnOnRegistryEntriesWithoutCode();
- }
-
- /**
- * Report installed plugins the registry knows about but the scan did not find. Without this, the
- * two halves of an install drifting apart is invisible: the boot logs "Loaded 0 plugins" — exactly
- * what a host with nothing installed logs — while the dashboard, which reads the registry, lists
- * every plugin as installed and enabled. Naming the directory that was actually scanned is what
- * makes the divergence self-diagnosing.
- *
- * Built-ins are excluded: they are registered programmatically at bootstrap (after this runs) and
- * never have a package directory at all.
- */
- private warnOnRegistryEntriesWithoutCode(): void {
- const orphaned = this.pluginStorage.getAllEntries().filter(e => !e.builtIn && !this.plugins.has(e.id));
- if (orphaned.length === 0) return;
-
- const missingDir = fs.existsSync(this.pluginsDir) ? '' : ' (that directory does not exist)';
- this.logger.warn(
- `The plugin registry lists ${orphaned.length} installed plugin(s) with no loaded code in ` +
- `${this.pluginsDir}${missingDir}: ${orphaned.map(e => e.id).join(', ')}. Their config and stored ` +
- `data are intact — reinstall them, or set PLUGINS_DIR to the directory that holds their code.`,
- { action: 'plugin_registry_without_code', count: orphaned.length, pluginsDir: this.pluginsDir },
- );
+ this.scanner.scanAtBoot();
}
/**
@@ -336,282 +270,6 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
}
}
- private loadBuiltInPlugins(): void {
- // Built-in plugins are registered programmatically
- // This will be used by Phase 4 to register engine plugins
- this.logger.debug('Built-in plugins loading point (Phase 4)', {
- action: 'builtin_plugins_init',
- });
- }
-
- private loadPluginsFromDirectory(dir: string): void {
- // Reconcile any interrupted-update leftovers BEFORE scanning, so a crash mid-swap can't make a
- // plugin silently vanish while its registry entry still claims it is installed.
- this.recoverInterruptedUpdates(dir);
-
- const entries = fs.readdirSync(dir, { withFileTypes: true });
-
- for (const entry of entries) {
- // Skip non-directories and dot-prefixed dirs (e.g. a crash-leftover `.<id>.bak` update backup or
- // `.<id>.new` staging tree), so a half-finished update can't be re-loaded as a duplicate-id
- // plugin on the next boot. recoverInterruptedUpdates has already reconciled them by this point.
- if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
-
- // Already loaded by an earlier scan. Only reachable through the legacy-directory compatibility
- // scan, where the same package can sit in both trees: the copy in the configured dir wins, and
- // re-loading it would throw "already loaded" — which the catch below would persist as ERROR on
- // a perfectly healthy plugin.
- if (this.plugins.has(entry.name)) {
- this.logger.debug(`Skipped ${entry.name} in ${dir}: already loaded from another plugin directory`, {
- pluginId: entry.name,
- action: 'plugin_duplicate_dir_skipped',
- });
- continue;
- }
-
- const pluginPath = path.join(dir, entry.name);
- const manifestPath = path.join(pluginPath, 'manifest.json');
-
- if (!fs.existsSync(manifestPath)) {
- if (LEGACY_REMOVED_PLUGIN_IDS.has(entry.name)) {
- this.logger.warn(
- `Skipped ${entry.name}: not a plugin (no manifest.json). Delete the directory to silence this, ` +
- `or add a manifest.json if it is meant to load.`,
- { pluginPath, action: 'manifest_missing' },
- );
- this.pluginStorage.deletePluginEntry(entry.name);
- this.logger.log(`Pruned stale registry entry for removed built-in plugin: ${entry.name}`, {
- action: 'registry_ghost_pruned',
- });
- continue;
- }
-
- // A manifest-less directory here means one of three different things, which used to log
- // identically: <dataDir>/plugins/<id> is BOTH the package dir and the plugin's ctx.storage
- // dir, so a built-in that persists anything owns a manifest-less directory on every healthy
- // boot, while an installed plugin whose code is gone (a container recreate that took the
- // image layer with it) leaves a directory that looks exactly the same — state still in it.
- // The registry is what tells them apart, so consult it rather than logging one wording for
- // the routine case, the data-loss case, and a directory an operator simply dropped in here.
- const registryEntry = this.pluginStorage.getPluginEntry(entry.name);
- if (registryEntry?.builtIn) {
- this.logger.debug(`Skipped ${entry.name}: built-in plugin storage, not a package directory`, {
- pluginPath,
- pluginId: entry.name,
- action: 'builtin_storage_dir_skipped',
- });
- } else if (registryEntry) {
- this.logger.warn(
- `Plugin ${entry.name} is installed but its code is missing from ${pluginPath} (no manifest.json) ` +
- `while its stored data is still there. Reinstall it — its config and stored data are kept. ` +
- `Plugin code kept outside the data volume does not survive a container recreate.`,
- { pluginPath, pluginId: entry.name, action: 'plugin_code_missing' },
- );
- } else {
- // Operators do drop unrelated directories in here, and this fires on every boot for each one.
- // The old bare "missing manifest.json" wording read like an internal fault — #981's reporter
- // pasted it into an unrelated session bug as evidence. Say what was skipped and what to do.
- this.logger.warn(
- `Skipped ${entry.name}: not a plugin (no manifest.json). Delete the directory to silence this, ` +
- `or add a manifest.json if it is meant to load.`,
- { pluginPath, action: 'manifest_missing' },
- );
- }
- continue;
- }
-
- try {
- this.loadPlugin(pluginPath);
- } catch (error) {
- this.logger.error(
- `Failed to load plugin ${entry.name}`,
- error instanceof Error ? error.message : String(error),
- { pluginPath, action: 'plugin_load_failed' },
- );
- // The runtime just dropped this plugin, but a registry entry from a previous successful
- // load still claims it installed/enabled — reconcile the persisted state to ERROR so the
- // mismatch surfaces instead of silently persisting. The entry itself (operator config,
- // enabledByOperator) is preserved: fix the manifest/main and the next boot loads and
- // re-enables it (ensureRegistryEntry resets the status on a successful load). No-op when
- // no entry exists (a hand-placed dir that never loaded).
- this.pluginStorage.setPluginStatus(entry.name, PluginStatus.ERROR);
- }
- }
- }
-
- /**
- * Crash recovery for in-place updates (see PluginsService.updatePackageInner). An update stages the
- * new tree at `.<id>.new`, then swaps with two renames (live → `.<id>.bak`, staging → live). Both
- * siblings are dot-prefixed, so the scan above skips them — but without reconciliation a crash
- * BETWEEN the renames loses the live dir and the plugin silently vanishes from the runtime while
- * its registry entry still claims it is installed. Reconcile before scanning:
- * - live dir missing + `.<id>.bak` present → the swap was interrupted: restore the backup as the
- * live dir (the previous version comes back; the update never touched the registry entry or the
- * operator's config, so nothing else needs repairing).
- * - live dir present + `.<id>.bak` present → the swap completed but the process died before the
- * backup cleanup: drop the backup.
- * - `.<id>.new` present → staging from an interrupted/failed update; the live install (if any)
- * was never swapped: drop it.
- * Best-effort: a reconciliation failure is logged and left for the next boot rather than aborting
- * plugin loading entirely.
- */
- private recoverInterruptedUpdates(dir: string): void {
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
- if (!entry.isDirectory()) continue;
- const match = /^\.(.+)\.(?:bak|new)$/.exec(entry.name);
- if (!match) continue;
- const pluginId = match[1];
- const leftover = path.join(dir, entry.name);
- const liveDir = path.join(dir, pluginId);
- try {
- if (entry.name === pluginUpdateStagingDirName(pluginId)) {
- fs.rmSync(leftover, { recursive: true, force: true });
- this.logger.warn(`Dropped stale update staging for plugin ${pluginId}`, {
- pluginId,
- action: 'plugin_update_staging_pruned',
- });
- } else if (!fs.existsSync(liveDir)) {
- fs.renameSync(leftover, liveDir);
- this.logger.warn(
- `Restored plugin ${pluginId} from its update backup — a previous update was interrupted mid-swap`,
- { pluginId, action: 'plugin_update_backup_restored' },
- );
- } else {
- fs.rmSync(leftover, { recursive: true, force: true });
- this.logger.warn(`Dropped stale update backup for plugin ${pluginId}`, {
- pluginId,
- action: 'plugin_update_backup_pruned',
- });
- }
- } catch (error) {
- this.logger.error(
- `Failed to reconcile the interrupted-update leftover ${entry.name}`,
- error instanceof Error ? error.message : String(error),
- { pluginId, action: 'plugin_update_recovery_failed' },
- );
- }
- }
- }
-
- loadPlugin(pluginPath: string): PluginInstance {
- const manifestPath = path.join(pluginPath, 'manifest.json');
- const manifestContent = fs.readFileSync(manifestPath, 'utf-8');
- const manifest = JSON.parse(manifestContent) as unknown;
-
- // Boot-time validation is the SAME validation install runs (parsePluginPackage): a hand-placed
- // or crash-leftover directory must satisfy the install contract too — plain-object shape,
- // required string fields, id format + reserved ids, extension-only type, and a `main` that
- // cannot escape the plugin dir. Otherwise a manifest the installer would have rejected loads
- // anyway and only fails (or worse, runs unexpected code) at enable time.
- validatePluginManifest(manifest);
-
- // Anchor `main` inside THIS on-disk directory: the lexical check above is forward-slash only,
- // so a platform-separator escape (e.g. Windows-style `..\x`) would slip past it — resolve and
- // re-check containment here. Parity with install's in-archive check: the entry must exist as a
- // file, or the plugin loads "successfully" and only blows up when someone enables it.
- const mainPath = resolvePluginMainPath(path.dirname(pluginPath), path.basename(pluginPath), manifest.main);
- if (!fs.existsSync(mainPath) || !fs.statSync(mainPath).isFile()) {
- throw new Error(`Plugin ${manifest.id}: main file not found in the plugin directory: ${manifest.main}`);
- }
-
- // Reject a malformed ingress declaration (SDK-major mismatch, missing webhook:ingress permission,
- // duplicate/empty routes, non-positive toleranceSec) at load time instead of letting it silently
- // load and become provisionable. No-op for plugins that declare no ingress. A route declaring
- // signature.scheme 'none' is rejected unless the operator opted in via ALLOW_UNSIGNED_INGRESS=true.
- validateIngressManifest(manifest, this.configService.get<boolean>('ingress.allowUnsigned', false));
-
- // Surface a loud warning for any ingress route that skips signature verification — a scheme:'none'
- // route is a fully-unauthenticated public endpoint that can trigger WhatsApp sends. Only reachable
- // when the operator opted in (otherwise validateIngressManifest above rejected it); the warning
- // reminds them to front the URL with a network/reverse-proxy ACL.
- warnUnauthenticatedIngressRoutes(manifest, this.logger);
-
- // Same loud-warning treatment for an hmac route whose declared timestamp is not bound into the
- // signature: freshness is enforced, but an unsigned timestamp lets a replay mint a fresh one.
- warnUnsignedTimestampRoutes(manifest, this.logger);
-
- // Check if plugin already loaded
- if (this.plugins.has(manifest.id)) {
- throw new Error(`Plugin ${manifest.id} is already loaded`);
- }
-
- // Load any persisted config + per-session activation + per-session config so an operator's choices
- // survive a restart.
- const storedConfig = this.pluginStorage.getPluginConfig(manifest.id) ?? {};
- const storedSessions = this.pluginStorage.getPluginSessions(manifest.id) ?? undefined;
- const storedSessionConfig = this.pluginStorage.getPluginSessionConfig(manifest.id) ?? undefined;
-
- const pluginInstance: PluginInstance = {
- manifest,
- status: PluginStatus.INSTALLED,
- // Seed schema-declared defaults under the stored config, so a defaulted field is never
- // missing when the plugin later runs (explicit values are never overwritten).
- config: seedConfigDefaults(manifest.configSchema, storedConfig),
- instance: null,
- loadedAt: new Date(),
- builtIn: false,
- activeSessions: storedSessions,
- sessionConfig: storedSessionConfig,
- // The directory this package was actually found in, which is not necessarily
- // <plugins.dir>/<id> — the legacy directory is scanned too. Recorded here because this is the
- // only point that knows it; every later write against the package reads it back.
- packageDir: path.resolve(pluginPath),
- };
-
- this.plugins.set(manifest.id, pluginInstance);
-
- // Ensure a registry entry exists so later enable/disable/config writes persist.
- this.ensureRegistryEntry(manifest, false);
-
- this.logger.log(`Plugin loaded: ${manifest.name} v${manifest.version}`, {
- pluginId: manifest.id,
- type: manifest.type,
- action: 'plugin_loaded',
- });
-
- return pluginInstance;
- }
-
- /**
- * Ensure a freshly-loaded plugin has a persisted registry entry, so later enable/disable/config
- * writes (which only update an EXISTING entry) actually persist instead of silently no-op'ing.
- * Creates a complete INSTALLED entry when none exists; an existing entry's persisted status/config
- * is left untouched. Best-effort (saveRegistry swallows fs errors, so a disk failure never turns a
- * load into a 500). Does NOT enable or run the plugin — boot never auto-executes plugin code.
- */
- private ensureRegistryEntry(manifest: PluginManifest, builtIn: boolean): void {
- // Reconcile the persisted entry with the freshly-loaded runtime: loading never runs the plugin, so
- // the entry's status is (re)set to INSTALLED to match the runtime. Enabling is a separate step that
- // runs the lifecycle — at bootstrap for a plugin the operator had enabled (see
- // onApplicationBootstrap), or on an explicit ADMIN action. The operator's persisted config and
- // enable decision are preserved so settings/secrets and the decision itself survive. Best-effort:
- // saveRegistry swallows fs errors, so a disk failure never turns a load into a 500.
- const existing = this.pluginStorage.getPluginEntry(manifest.id);
- // The operator's standing enable decision (#856). `status` below is deliberately reset, so intent
- // has to live in its own field or a restart loses it. A pre-#856 row has no such field: adopt it
- // from a status of ENABLED, which can only have been written by an explicit enable since the last
- // boot (every boot rewrites the status to INSTALLED), so it is a faithful record of the intent.
- const enabledByOperator = existing?.enabledByOperator ?? existing?.status === PluginStatus.ENABLED;
- this.pluginStorage.setPluginEntry({
- id: manifest.id,
- type: manifest.type,
- name: manifest.name,
- version: manifest.version,
- status: PluginStatus.INSTALLED,
- // The operator's persisted config survives, with schema-declared defaults seeded under it so
- // the persisted entry matches the seeded runtime config (see loadPlugin).
- config: seedConfigDefaults(manifest.configSchema, existing?.config ?? {}),
- builtIn,
- installedAt: existing?.installedAt ?? new Date(),
- updatedAt: new Date(),
- // setPluginEntry REPLACES the entry, so the operator's per-session activation + config must be
- // carried over or every boot wipes them from disk (lost after the second restart).
- activeSessions: existing?.activeSessions,
- sessionConfig: existing?.sessionConfig,
- enabledByOperator,
- });
- }
-
/**
* Record that the operator wants this plugin on (or off), so bootstrap can restore it (#856).
*
@@ -633,152 +291,20 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
return this.pluginStorage.getPluginEntry(pluginId);
}
- async enablePlugin(pluginId: string): Promise<void> {
- const plugin = this.plugins.get(pluginId);
- if (!plugin) {
- throw new Error(`Plugin ${pluginId} not found`);
- }
-
- if (plugin.status === PluginStatus.ENABLED) {
- return; // Already enabled
- }
-
- // Engines are mutually exclusive and pinned to the deployment's engine.type config (the factory
- // reads that, not plugin status). Enabling a second engine at runtime would show two "active"
- // engines and desync the factory, so reject anything but the configured active engine.
- if (plugin.manifest.type === PluginType.ENGINE) {
- const activeEngine = this.configService.get<string>('engine.type') ?? 'whatsapp-web.js';
- if (pluginId !== activeEngine) {
- throw new Error(
- `Engine "${pluginId}" is not the active engine ("${activeEngine}"). Set engine.type and restart to switch engines.`,
- );
- }
- }
-
- // 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.sandboxBridge.enableSandboxed(pluginId, plugin);
- } else {
- await this.enableInProcess(pluginId, plugin);
- }
-
- plugin.status = PluginStatus.ENABLED;
- plugin.enabledAt = new Date();
- plugin.error = undefined;
-
- // Persist status
- this.pluginStorage.setPluginStatus(pluginId, PluginStatus.ENABLED);
-
- this.logger.log(`Plugin enabled: ${plugin.manifest.name}`, {
- pluginId,
- action: 'plugin_enabled',
- });
- } catch (error) {
- plugin.status = PluginStatus.ERROR;
- plugin.error = error instanceof Error ? error.message : String(error);
-
- this.pluginStorage.setPluginStatus(pluginId, PluginStatus.ERROR);
-
- // A plugin that subscribed hooks before its onLoad/onEnable threw would otherwise leave those
- // registrations live: a later successful enable re-registers them, so each event then dispatches
- // to the plugin once per failed attempt. Drop them here. Safe on this path only — an
- // already-enabled plugin returns early above, so the catch only runs for an enable that never
- // went live, which owns no hooks worth keeping. (Idempotent: no-ops when none were registered.)
- this.hookManager.unregisterPlugin(pluginId);
-
- throw error;
- } finally {
- this.enabling.delete(pluginId);
- }
+ loadPlugin(pluginPath: string): PluginInstance {
+ return this.scanner.loadPlugin(pluginPath);
}
- /**
- * Disable an enabled plugin (best-effort force-teardown for sandboxed ones). `opts.unload` is set
- * ONLY by the unload path (uninstall / in-place update): it additionally dispatches the plugin's
- * onUnload hook. A plain disable (REST / shutdown teardown) deliberately does NOT fire onUnload —
- * disable is reversible and its cleanup hook is onDisable, while onUnload means "removed from the
- * runtime". (For a sandboxed plugin the worker thread does die on disable, but terminate() itself
- * releases its timers/sockets; the hook contract stays: onUnload only on unload.)
- */
- async disablePlugin(pluginId: string, opts?: { unload?: boolean }): Promise<void> {
- const plugin = this.plugins.get(pluginId);
- if (!plugin) {
- throw new Error(`Plugin ${pluginId} not found`);
- }
-
- if (plugin.status !== PluginStatus.ENABLED) {
- return; // Not enabled
- }
-
- try {
- const host = this.sandboxHosts.get(pluginId);
- if (host) {
- await this.sandboxBridge.teardownSandboxed(pluginId, host, opts);
- } else {
- const context = this.capabilities.createPluginContext(plugin);
- if (plugin.instance?.onDisable) {
- await plugin.instance.onDisable(context);
- }
- }
-
- // Unregister all hooks for this plugin
- this.hookManager.unregisterPlugin(pluginId);
- // Drop the plugin's search-provider entry (if any) so queries don't route to a terminated worker.
- unregisterPluginSearchProvider(this.hostServices.getSearchRegistryPort(), pluginId);
-
- 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,
- action: 'plugin_disabled',
- });
- } catch (error) {
- plugin.status = PluginStatus.ERROR;
- plugin.error = error instanceof Error ? error.message : String(error);
- throw error;
- }
+ enablePlugin(pluginId: string): Promise<void> {
+ return this.lifecycle.enablePlugin(pluginId);
}
- async unloadPlugin(pluginId: string): Promise<void> {
- const plugin = this.plugins.get(pluginId);
- if (!plugin) {
- throw new Error(`Plugin ${pluginId} not found`);
- }
-
- // Disable first if enabled. `unload: true` so a SANDBOXED plugin also gets its onUnload hook:
- // disable terminates the worker thread, which would otherwise make onUnload unreachable. An
- // in-process plugin's onUnload runs below instead (its instance survives disable). A sandboxed
- // plugin that is already disabled has no live worker left to notify — its resources were
- // released when the worker terminated, so there is nothing to clean up.
- if (plugin.status === PluginStatus.ENABLED) {
- await this.disablePlugin(pluginId, { unload: true });
- }
-
- // Call onUnload (in-process plugins; a sandboxed one received it above, before terminate)
- if (plugin.instance?.onUnload) {
- const context = this.capabilities.createPluginContext(plugin);
- await plugin.instance.onUnload(context);
- }
-
- this.plugins.delete(pluginId);
+ disablePlugin(pluginId: string, opts?: { unload?: boolean }): Promise<void> {
+ return this.lifecycle.disablePlugin(pluginId, opts);
+ }
- this.logger.log(`Plugin unloaded: ${plugin.manifest.name}`, {
- pluginId,
- action: 'plugin_unloaded',
- });
+ unloadPlugin(pluginId: string): Promise<void> {
+ return this.lifecycle.unloadPlugin(pluginId);
}
/** Absolute path of the directory user plugins are loaded from (used by install/uninstall). */
@@ -798,140 +324,25 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
return this.plugins.get(pluginId)?.packageDir ?? path.join(this.pluginsDir, pluginId);
}
- /** <plugins.dir>/<id> for an id with no loaded package, or null if the id escapes that root. */
- private resolveUninstallDir(pluginId: string): string | null {
- const base = path.resolve(this.pluginsDir);
- const dir = path.resolve(base, pluginId);
- return dir !== base && dir.startsWith(base + path.sep) ? dir : null;
- }
-
/** Whether a plugin is a first-party built-in (engine / bundled extension) vs an installed user plugin. */
isBuiltIn(pluginId: string): boolean {
return this.pluginStorage.getPluginEntry(pluginId)?.builtIn ?? false;
}
- /**
- * Fully remove an installed user plugin: disable + unload from the runtime, drop its persisted
- * registry entry, and delete its directory from disk. Built-ins (engines, bundled extensions) are
- * registered programmatically with no on-disk dir and must never be removable.
- */
- async uninstallPlugin(pluginId: string): Promise<void> {
- if (this.pluginStorage.getPluginEntry(pluginId)?.builtIn) {
- throw new Error(`Cannot uninstall built-in plugin ${pluginId}`);
- }
-
- // Read the package location BEFORE unloading: unloadPlugin drops the runtime record that holds
- // it, and for a plugin loaded from the legacy directory the configured root is the wrong tree —
- // deleting there removes the ctx.storage directory and leaves the code, so the plugin comes
- // back on the next boot having reported a successful uninstall.
- const recordedDir = this.plugins.get(pluginId)?.packageDir ?? null;
-
- if (this.plugins.has(pluginId)) {
- await this.unloadPlugin(pluginId);
- }
- this.pluginStorage.deletePluginEntry(pluginId);
-
- // A recorded directory came from the boot scan and is already contained. Without one the id is
- // the only input, so it stays behind the traversal guard against the configured root.
- const dir = recordedDir ?? this.resolveUninstallDir(pluginId);
- if (dir && fs.existsSync(dir)) {
- fs.rmSync(dir, { recursive: true, force: true });
- }
-
- // Drop the plugin's ctx.storage data dir. Under shipped defaults it lives INSIDE the package
- // dir (already gone above), but a split-dir deployment (PLUGINS_DIR outside the data dir) would
- // otherwise leak <dataDir>/plugins/<id> — persisted secrets included — on every uninstall.
- // Best-effort, and strictly that one plugin's directory.
- this.pluginStorage.deletePluginData(pluginId);
-
- this.logger.log(`Plugin uninstalled: ${pluginId}`, { pluginId, action: 'plugin_uninstalled' });
+ uninstallPlugin(pluginId: string): Promise<void> {
+ return this.uninstaller.uninstallPlugin(pluginId);
}
updatePluginConfig(pluginId: string, config: Record<string, unknown>): void {
- const plugin = this.plugins.get(pluginId);
- if (!plugin) {
- throw new Error(`Plugin ${pluginId} not found`);
- }
-
- plugin.config = { ...plugin.config, ...config };
-
- // Persist config
- this.pluginStorage.setPluginConfig(pluginId, 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.capabilities.createPluginContext(plugin);
- void plugin.instance.onConfigChange(context, plugin.config);
- }
- }
-
- this.logger.debug(`Plugin config updated: ${pluginId}`, {
- pluginId,
- action: 'plugin_config_updated',
- });
+ this.lifecycle.updatePluginConfig(pluginId, config);
}
- /**
- * Set the sessions a session-scoped plugin is activated for. `['*']` = all numbers (system-wide),
- * an explicit list scopes it to those sessions, `[]` deactivates it everywhere. Takes effect on the
- * next hook event (the gate reads plugin.activeSessions live) and survives a restart.
- */
setPluginSessions(pluginId: string, sessions: string[]): PluginInstance {
- const plugin = this.plugins.get(pluginId);
- if (!plugin) {
- throw new Error(`Plugin ${pluginId} not found`);
- }
- if (plugin.manifest.sessionScoped === false) {
- throw new Error(`Plugin ${pluginId} is global (not session-scoped) and cannot be activated per session`);
- }
-
- plugin.activeSessions = sessions;
- this.pluginStorage.setPluginSessions(pluginId, sessions);
-
- this.logger.log(`Plugin active sessions updated: ${pluginId}`, {
- pluginId,
- action: 'plugin_sessions_updated',
- sessions,
- });
- return plugin;
+ return this.lifecycle.setPluginSessions(pluginId, sessions);
}
- /**
- * Set (or clear) a plugin's per-session config override for `sessionId`. Hooks for that session then
- * see the override shallow-merged over the base via ctx.config — applied on the next event
- * (resolution reads plugin.sessionConfig live) and persisted across restart. An empty override
- * removes it (the session falls back to the base). Global plugins have no per-session config.
- */
setPluginSessionConfig(pluginId: string, sessionId: string, config: Record<string, unknown>): PluginInstance {
- const plugin = this.plugins.get(pluginId);
- if (!plugin) {
- throw new Error(`Plugin ${pluginId} not found`);
- }
- if (plugin.manifest.sessionScoped === false) {
- throw new Error(`Plugin ${pluginId} is global (not session-scoped) and has no per-session config`);
- }
-
- const next = { ...(plugin.sessionConfig ?? {}) };
- if (config && Object.keys(config).length > 0) {
- next[sessionId] = config;
- } else {
- delete next[sessionId];
- }
- plugin.sessionConfig = next;
- this.pluginStorage.setPluginSessionConfig(pluginId, next);
-
- this.logger.debug(`Plugin session config updated: ${pluginId}`, {
- pluginId,
- action: 'plugin_session_config_updated',
- sessionId,
- });
- return plugin;
+ return this.lifecycle.setPluginSessionConfig(pluginId, sessionId, config);
}
/** Health across both tiers; the sandbox-routing implementation lives in PluginSandboxBridge. */
@@ -980,33 +391,6 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
);
}
- /** Built-in (trusted) enable: require + run the lifecycle in-process with the live capability context. */
- private async enableInProcess(pluginId: string, plugin: PluginInstance): Promise<void> {
- const context = this.capabilities.createPluginContext(plugin);
-
- if (!plugin.instance) {
- // Containment guard: reject a manifest.main that escapes the plugin dir.
- // The configured root, not getPluginPackageDir: this tier runs only for built-ins
- // (enablePlugin routes `builtIn === false` to the sandbox), and a built-in is registered
- // programmatically with no on-disk package, so the two resolve identically here.
- const mainPath = resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);
- // eslint-disable-next-line @typescript-eslint/no-require-imports
- const pluginModule = require(mainPath) as { default?: new () => IPlugin };
- if (pluginModule.default) {
- plugin.instance = new pluginModule.default();
- } else {
- throw new Error(`Plugin ${pluginId} does not export a default class`);
- }
- }
-
- if (plugin.instance.onLoad) {
- await plugin.instance.onLoad(context);
- }
- if (plugin.instance.onEnable) {
- await plugin.instance.onEnable(context);
- }
- }
-
getPlugin(pluginId: string): PluginInstance | undefined {
return this.plugins.get(pluginId);
}
@@ -1028,38 +412,7 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
return plugin?.status === PluginStatus.ENABLED;
}
- // ============================================================================
- // Built-in Plugin Registration (for Phase 4)
- // ============================================================================
-
registerBuiltInPlugin(manifest: PluginManifest, instance: IPlugin, config: Record<string, unknown> = {}): void {
- // Merge: env-derived defaults stay live each boot (so a changed .env wins), while an operator's
- // persisted overrides win for the keys they actually set. Engine config is wholly env-derived
- // (no persisted overrides), so it is never frozen to a first-boot snapshot.
- const effectiveConfig = { ...config, ...(this.pluginStorage.getPluginConfig(manifest.id) ?? {}) };
-
- const pluginInstance: PluginInstance = {
- manifest,
- status: PluginStatus.INSTALLED,
- config: effectiveConfig,
- instance,
- loadedAt: new Date(),
- builtIn: true,
- // Read persisted per-session activation + config back into the runtime, like loadPlugin —
- // otherwise the delivery gate falls back to all-sessions/base-config after every restart for a
- // session-scoped built-in the operator had restricted.
- activeSessions: this.pluginStorage.getPluginSessions(manifest.id) ?? undefined,
- sessionConfig: this.pluginStorage.getPluginSessionConfig(manifest.id) ?? undefined,
- };
-
- this.plugins.set(manifest.id, pluginInstance);
-
- // Ensure a registry entry exists so later enable/disable/config writes persist.
- this.ensureRegistryEntry(manifest, true);
-
- this.logger.debug(`Built-in plugin registered: ${manifest.name}`, {
- pluginId: manifest.id,
- action: 'builtin_plugin_registered',
- });
+ this.lifecycle.registerBuiltInPlugin(manifest, instance, config);
}
}
diff --git a/src/core/plugins/plugin-package-scanner.spec.ts b/src/core/plugins/plugin-package-scanner.spec.ts
new file mode 100644
index 000000000..500993cf2
--- /dev/null
+++ b/src/core/plugins/plugin-package-scanner.spec.ts
@@ -0,0 +1,385 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { ConfigService } from '@nestjs/config';
+import { createLogger } from '../../common/services/logger.service';
+import { PluginStorageService } from './plugin-storage.service';
+import { PluginPackageScanner } from './plugin-package-scanner';
+import { PluginInstance, PluginStatus } from './plugin.interfaces';
+
+/**
+ * The boot-scan job, on the collaborator that owns it since the loader split. Construction only is
+ * adapted from the loader-level specs these tests moved from — every assertion is unchanged: the
+ * scanner shares the loader's registry Map by reference, so reads on `plugins` are the same reads
+ * `loader.getPlugin` used to make.
+ */
+const bootScanner = (config: ConfigService, storage: PluginStorageService, pluginsDir: string) => {
+ const plugins = new Map<string, PluginInstance>();
+ const scanner = new PluginPackageScanner(
+ createLogger('PluginLoaderService'),
+ config,
+ storage,
+ pluginsDir,
+ null,
+ plugins,
+ );
+ return { scanner, plugins };
+};
+
+describe('PluginPackageScanner — skips dot-prefixed directories on load (crash-leftover .bak)', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let scanner: PluginPackageScanner;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-dotskip-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ ({ scanner } = bootScanner(config, new PluginStorageService(config), pluginsDir));
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writePlugin = (dirName: string, id: string): void => {
+ const dir = path.join(pluginsDir, dirName);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ };
+
+ it('does not scan a crash-leftover .<id>.bak directory (no duplicate-id load race)', () => {
+ writePlugin('svc-plg', 'svc-plg');
+ writePlugin('.svc-plg.bak', 'svc-plg'); // a leftover update backup carrying the SAME manifest id
+
+ const loadSpy = jest.spyOn(scanner, 'loadPlugin');
+ scanner.scanAtBoot();
+
+ const scanned = loadSpy.mock.calls.map(c => c[0]);
+ expect(scanned).toContain(path.join(pluginsDir, 'svc-plg'));
+ expect(scanned).not.toContain(path.join(pluginsDir, '.svc-plg.bak'));
+ });
+});
+
+describe('PluginPackageScanner — prunes registry ghosts of removed built-ins', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let scanner: PluginPackageScanner;
+ let storage: PluginStorageService;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-ghosts-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ storage = new PluginStorageService(config);
+ ({ scanner } = bootScanner(config, storage, pluginsDir));
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const seedGhost = (id: string): void => {
+ // A leftover directory with no manifest (code deleted) + a stale registry entry still claiming
+ // the plugin is installed — the ghost state upgrades from <=0.6 are in.
+ fs.mkdirSync(path.join(pluginsDir, id), { recursive: true });
+ storage.setPluginEntry({
+ id,
+ type: 'extension',
+ name: id,
+ version: '1.0.0',
+ status: 'installed',
+ config: {},
+ builtIn: true,
+ installedAt: new Date(),
+ updatedAt: new Date(),
+ } as never);
+ };
+
+ it('prunes registry entries of legacy removed built-ins (auto-reply, translation) with no manifest', () => {
+ seedGhost('auto-reply');
+ seedGhost('translation');
+
+ scanner.scanAtBoot();
+
+ expect(storage.getPluginEntry('auto-reply')).toBeUndefined();
+ expect(storage.getPluginEntry('translation')).toBeUndefined();
+ });
+
+ it('keeps a manifest-less NON-legacy plugin entry (config survives an unreadable dir)', () => {
+ seedGhost('some-other-plugin');
+
+ scanner.scanAtBoot();
+
+ expect(storage.getPluginEntry('some-other-plugin')).toBeDefined();
+ });
+});
+
+describe('PluginPackageScanner — boot reconciles the registry entry of a plugin it drops', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let storage: PluginStorageService;
+
+ const config = () =>
+ ({
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ }) as unknown as ConfigService;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-drop-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ storage = new PluginStorageService(config());
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writePlugin = (id: string, manifest: Record<string, unknown>): void => {
+ const dir = path.join(pluginsDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'manifest.json'), JSON.stringify(manifest));
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ };
+
+ it('marks the persisted entry ERROR when boot-time manifest validation drops a previously-installed plugin', () => {
+ // Boot 1: a valid hand-placed plugin loads and gets its registry entry.
+ writePlugin('hand-placed', {
+ id: 'hand-placed',
+ name: 'Hand',
+ version: '1.0.0',
+ type: 'extension',
+ main: 'index.js',
+ });
+ bootScanner(config(), storage, pluginsDir).scanner.scanAtBoot();
+ expect(storage.getPluginEntry('hand-placed')?.status).toBe(PluginStatus.INSTALLED);
+ // The operator's config + standing enable decision live in that entry.
+ storage.setPluginConfig('hand-placed', { apiKey: 'keep-me' });
+ storage.setPluginEnabledByOperator('hand-placed', true);
+
+ // Boot 2: the manifest was hand-edited into something the installer would have rejected
+ // (missing required field) — the plugin is dropped from the runtime...
+ writePlugin('hand-placed', { id: 'hand-placed', name: 'Hand', type: 'extension', main: 'index.js' });
+ const second = bootScanner(config(), storage, pluginsDir);
+ second.scanner.scanAtBoot();
+ expect(second.plugins.get('hand-placed')).toBeUndefined();
+
+ // ...and the registry no longer claims it installed. The entry itself (config,
+ // enabledByOperator) survives, so fixing the manifest and rebooting re-enables it.
+ const entry = storage.getPluginEntry('hand-placed');
+ expect(entry?.status).toBe(PluginStatus.ERROR);
+ expect(entry?.config).toEqual({ apiKey: 'keep-me' });
+ expect(entry?.enabledByOperator).toBe(true);
+ });
+
+ it('a hand-placed plugin that fails validation without a registry entry simply does not load', () => {
+ writePlugin('never-installed', { id: 'never-installed', name: 'Nope', type: 'extension', main: 'index.js' });
+
+ const { scanner, plugins } = bootScanner(config(), storage, pluginsDir);
+ scanner.scanAtBoot();
+
+ expect(plugins.get('never-installed')).toBeUndefined();
+ // No entry existed, so the ERROR reconciliation is a no-op — none is invented either.
+ expect(storage.getPluginEntry('never-installed')).toBeUndefined();
+ });
+});
+
+describe('PluginPackageScanner — loadPlugin seeds configSchema defaults', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let scanner: PluginPackageScanner;
+ let storage: PluginStorageService;
+ let plugins: Map<string, PluginInstance>;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-seed-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ storage = new PluginStorageService(config);
+ ({ scanner, plugins } = bootScanner(config, storage, pluginsDir));
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ it('seeds defaults into the runtime instance and the persisted registry entry at load', () => {
+ const dir = path.join(pluginsDir, 'seeded-plg');
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ JSON.stringify({
+ id: 'seeded-plg',
+ name: 'seeded-plg',
+ version: '1.0.0',
+ type: 'extension',
+ main: 'index.js',
+ configSchema: {
+ type: 'object',
+ properties: { timezone: { type: 'string', default: 'UTC' } },
+ },
+ }),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+
+ scanner.scanAtBoot();
+
+ expect(plugins.get('seeded-plg')?.config).toEqual({ timezone: 'UTC' });
+ expect(storage.getPluginEntry('seeded-plg')?.config).toEqual({ timezone: 'UTC' });
+ });
+});
+
+describe('PluginPackageScanner — boot-time manifest validation parity with install', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let scanner: PluginPackageScanner;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-bootval-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ ({ scanner } = bootScanner(config, new PluginStorageService(config), pluginsDir));
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writePlugin = (id: string, manifest: unknown, withMain = true): string => {
+ const dir = path.join(pluginsDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ typeof manifest === 'string' ? manifest : JSON.stringify(manifest),
+ );
+ if (withMain) fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ return dir;
+ };
+ const baseManifest = (id: string): Record<string, unknown> => ({
+ id,
+ name: id,
+ version: '1.0.0',
+ type: 'extension',
+ main: 'index.js',
+ });
+
+ it('rejects the same invalid manifests install rejects (fields, id, reserved, type)', () => {
+ // Missing a required field.
+ const noName = baseManifest('no-name');
+ delete noName.name;
+ expect(() => scanner.loadPlugin(writePlugin('no-name', noName))).toThrow(/required field: name/i);
+ // A non-string required field (truthy — passed the old bare falsy check).
+ expect(() => scanner.loadPlugin(writePlugin('num-main', { ...baseManifest('num-main'), main: 123 }))).toThrow(
+ /invalid required field/i,
+ );
+ // Unsafe id.
+ expect(() => scanner.loadPlugin(writePlugin('bad id', { ...baseManifest('bad id'), id: 'bad id' }))).toThrow(
+ /invalid plugin id/i,
+ );
+ // Reserved built-in id (would shadow the baileys engine).
+ expect(() => scanner.loadPlugin(writePlugin('baileys', baseManifest('baileys')))).toThrow(/reserved/i);
+ // A non-extension tier (engines are built-in, never directory-loadable).
+ expect(() => scanner.loadPlugin(writePlugin('my-eng', { ...baseManifest('my-eng'), type: 'engine' }))).toThrow(
+ /not installable/i,
+ );
+ // A non-object manifest document.
+ expect(() => scanner.loadPlugin(writePlugin('arr-plg', '[]'))).toThrow(/must be a JSON object/i);
+ });
+
+ it('rejects a manifest whose main escapes the plugin directory', () => {
+ const dir = writePlugin('trav-plg', { ...baseManifest('trav-plg'), main: '../other/evil.js' });
+ expect(() => scanner.loadPlugin(dir)).toThrow(/escapes the plugin directory/i);
+ });
+
+ it('rejects a manifest whose main file is missing from the directory', () => {
+ const dir = writePlugin('gone-main', { ...baseManifest('gone-main'), main: 'gone.js' });
+ expect(() => scanner.loadPlugin(dir)).toThrow(/main file not found/i);
+ });
+
+ it('rejects a plugin that declares ingress routes but omits the webhook:ingress permission', () => {
+ // loadPlugin must run validateIngressManifest, so a malformed ingress declaration fails to load
+ // rather than silently loading and becoming provisionable.
+ const dir = writePlugin('bad-ingress', {
+ ...baseManifest('bad-ingress'),
+ ingress: [{ route: 'events', signature: { headerName: 'X-Sig', scheme: 'hmac-sha256' } }],
+ // permissions intentionally omitted → validateIngressManifest must reject
+ });
+ expect(() => scanner.loadPlugin(dir)).toThrow(/webhook:ingress/i);
+ });
+});
+
+describe('PluginPackageScanner — interrupted-update recovery at boot', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let scanner: PluginPackageScanner;
+ let plugins: Map<string, PluginInstance>;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-uprec-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ ({ scanner, plugins } = bootScanner(config, new PluginStorageService(config), pluginsDir));
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writePluginTree = (dirName: string, id: string, version = '1.0.0'): void => {
+ const dir = path.join(pluginsDir, dirName);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ JSON.stringify({ id, name: id, version, type: 'extension', main: 'index.js' }),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ };
+
+ it('restores the backup as the live dir when a crash mid-swap lost the live dir', () => {
+ // Crash between `rename(live → backup)` and `rename(staging → live)`: the live dir is gone, the
+ // backup holds the previous version, and staging never landed.
+ writePluginTree('.svc-plg.bak', 'svc-plg');
+ writePluginTree('.svc-plg.new', 'svc-plg', '2.0.0');
+
+ scanner.scanAtBoot();
+
+ // The previous version is back as the live dir and loads normally — the plugin no longer
+ // silently vanishes while its registry entry still claims it is installed.
+ expect(plugins.get('svc-plg')?.manifest.version).toBe('1.0.0');
+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'))).toBe(true);
+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);
+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);
+ });
+
+ it('drops a stale backup when the live dir exists (crash after the swap completed)', () => {
+ writePluginTree('svc-plg', 'svc-plg', '2.0.0'); // the swapped-in new version
+ writePluginTree('.svc-plg.bak', 'svc-plg'); // leftover backup of the old one
+
+ scanner.scanAtBoot();
+
+ expect(plugins.get('svc-plg')?.manifest.version).toBe('2.0.0');
+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.bak'))).toBe(false);
+ });
+
+ it('drops a stale staging tree (crash before the swap ever started)', () => {
+ writePluginTree('svc-plg', 'svc-plg');
+ writePluginTree('.svc-plg.new', 'svc-plg', '2.0.0');
+
+ scanner.scanAtBoot();
+
+ expect(plugins.get('svc-plg')?.manifest.version).toBe('1.0.0');
+ expect(fs.existsSync(path.join(pluginsDir, '.svc-plg.new'))).toBe(false);
+ });
+
+ it('leaves an unrelated dot-prefixed directory alone', () => {
+ writePluginTree('svc-plg', 'svc-plg');
+ fs.mkdirSync(path.join(pluginsDir, '.gitkeep.d'), { recursive: true });
+
+ scanner.scanAtBoot();
+
+ expect(fs.existsSync(path.join(pluginsDir, '.gitkeep.d'))).toBe(true);
+ expect(plugins.get('svc-plg')).toBeDefined();
+ });
+});
diff --git a/src/core/plugins/plugin-package-scanner.ts b/src/core/plugins/plugin-package-scanner.ts
new file mode 100644
index 000000000..822a7af22
--- /dev/null
+++ b/src/core/plugins/plugin-package-scanner.ts
@@ -0,0 +1,419 @@
+import { ConfigService } from '@nestjs/config';
+import * as fs from 'fs';
+import * as path from 'path';
+import { createLogger } from '../../common/services/logger.service';
+import {
+ PluginInstance,
+ PluginManifest,
+ PluginStatus,
+ validateIngressManifest,
+ warnUnauthenticatedIngressRoutes,
+ warnUnsignedTimestampRoutes,
+} from './plugin.interfaces';
+import { validatePluginManifest } from './plugin-manifest';
+import { PluginStorageService } from './plugin-storage.service';
+import { seedConfigDefaults } from './config-defaults.util';
+import { resolvePluginMainPath, pluginUpdateStagingDirName } from './plugin-paths';
+
+// Plugin ids whose bundled-extension code was permanently removed (v0.7 — superseded by the
+// marketplace chat-flow / group-translate; also reserved in plugin-installer). A leftover
+// directory without a manifest marks them as deleted on disk, so the stale registry entry (which
+// still reports them installed/enabled) is pruned on boot. Scoped to these known ids so a
+// temporarily-unreadable plugin dir (e.g. an unmounted volume) never loses its persisted config.
+const LEGACY_REMOVED_PLUGIN_IDS = new Set(['auto-reply', 'translation']);
+
+/**
+ * Whether `dir` holds at least one loadable plugin package — a non-dot subdirectory with a manifest.
+ * Existence of the directory, or of subdirectories in it, proves nothing: <dataDir>/plugins is also
+ * where the registry and every plugin's ctx.storage live, so it is routinely full of directories that
+ * hold only `key-*.json` state. Unreadable or missing counts as "no packages": this only ever decides
+ * whether to scan a fallback location, never whether to delete anything.
+ */
+function hasPluginPackages(dir: string): boolean {
+ try {
+ return fs
+ .readdirSync(dir, { withFileTypes: true })
+ .some(
+ entry =>
+ entry.isDirectory() &&
+ !entry.name.startsWith('.') &&
+ fs.existsSync(path.join(dir, entry.name, 'manifest.json')),
+ );
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * The boot-scan half of the plugin runtime: find plugin packages on disk (the configured plugins dir
+ * plus the legacy compatibility tree), validate each manifest against the install contract, and
+ * populate the loader's plugin registry — the Map, passed by reference, that the loader, the sandbox
+ * bridge and the capability surface all read.
+ *
+ * Split out of PluginLoaderService so the loader reads as the public facade while disk discovery —
+ * crash recovery for interrupted updates, ghost pruning, registry reconciliation — is reviewed on its
+ * own. A plain class, not a Nest provider: the loader constructs it in its constructor (the same
+ * pattern as PluginSandboxBridge / PluginCapabilityContext), so the loader's public constructor
+ * signature — which specs build directly — is unchanged.
+ */
+export class PluginPackageScanner {
+ constructor(
+ // The LOADER's logger, deliberately — scan lines carry the PluginLoaderService tag, and that
+ // context is operator-visible. Creating a second logger here would silently retag every boot
+ // log line the moment this moved.
+ private readonly logger: ReturnType<typeof createLogger>,
+ private readonly configService: ConfigService,
+ private readonly pluginStorage: PluginStorageService,
+ private readonly pluginsDir: string,
+ /**
+ * The package dir OpenWA defaulted to before it moved under <dataDir>, scanned as a compatibility
+ * fallback; null when PLUGINS_DIR names a directory explicitly.
+ */
+ private readonly legacyPluginsDir: string | null,
+ // The LOADER's plugin registry, passed BY REFERENCE: mutations here are visible to the loader
+ // and to every collaborator that shares the same map.
+ private readonly plugins: Map<string, PluginInstance>,
+ ) {}
+
+ /**
+ * The loader's onModuleInit: load built-in plugins (programmatic registration point), then every
+ * user plugin package found on disk — the configured directory first, the legacy tree in addition —
+ * and report registry entries whose code the scan did not find.
+ */
+ scanAtBoot(): void {
+ // Load built-in plugins first (synchronous registration)
+ this.loadBuiltInPlugins();
+
+ // Then load user plugins if directory exists
+ if (fs.existsSync(this.pluginsDir)) {
+ this.loadPluginsFromDirectory(this.pluginsDir);
+ }
+
+ // COMPATIBILITY PATH — hosts that installed plugins before the package dir moved under <dataDir>.
+ // Their code sits in the old ./plugins, which was self-consistent while the loader and the
+ // installer both used that default, so changing the default must not take those plugins away.
+ // Scanned in ADDITION to the configured dir rather than instead of it, so a host part-way through
+ // migrating keeps both halves; the configured copy loads first and wins any duplicate id. Never
+ // runs when PLUGINS_DIR is set (legacyDir is null then). Keyed on finding a real plugin package,
+ // not on the directory existing: <dataDir>/plugins/<id> doubles as the plugin's ctx.storage dir,
+ // so directories with no code in them are routine.
+ if (this.legacyPluginsDir && hasPluginPackages(this.legacyPluginsDir)) {
+ this.logger.warn(
+ `Loading plugins from the legacy directory ${this.legacyPluginsDir}: the default moved to ` +
+ `${this.pluginsDir}, where the plugin registry and every new install already are. Move them ` +
+ `(mv ${this.legacyPluginsDir}/* ${this.pluginsDir}/) or keep the old location by setting ` +
+ `PLUGINS_DIR=${this.legacyPluginsDir}. In Docker this matters: a directory outside the data ` +
+ `volume is destroyed on the next container recreate.`,
+ { action: 'plugins_legacy_dir', legacyDir: this.legacyPluginsDir, pluginsDir: this.pluginsDir },
+ );
+ this.loadPluginsFromDirectory(this.legacyPluginsDir);
+ }
+
+ this.logger.log(`Loaded ${this.plugins.size} plugins`, {
+ action: 'plugins_loaded',
+ count: this.plugins.size,
+ });
+
+ this.warnOnRegistryEntriesWithoutCode();
+ }
+
+ /**
+ * Report installed plugins the registry knows about but the scan did not find. Without this, the
+ * two halves of an install drifting apart is invisible: the boot logs "Loaded 0 plugins" — exactly
+ * what a host with nothing installed logs — while the dashboard, which reads the registry, lists
+ * every plugin as installed and enabled. Naming the directory that was actually scanned is what
+ * makes the divergence self-diagnosing.
+ *
+ * Built-ins are excluded: they are registered programmatically at bootstrap (after this runs) and
+ * never have a package directory at all.
+ */
+ private warnOnRegistryEntriesWithoutCode(): void {
+ const orphaned = this.pluginStorage.getAllEntries().filter(e => !e.builtIn && !this.plugins.has(e.id));
+ if (orphaned.length === 0) return;
+
+ const missingDir = fs.existsSync(this.pluginsDir) ? '' : ' (that directory does not exist)';
+ this.logger.warn(
+ `The plugin registry lists ${orphaned.length} installed plugin(s) with no loaded code in ` +
+ `${this.pluginsDir}${missingDir}: ${orphaned.map(e => e.id).join(', ')}. Their config and stored ` +
+ `data are intact — reinstall them, or set PLUGINS_DIR to the directory that holds their code.`,
+ { action: 'plugin_registry_without_code', count: orphaned.length, pluginsDir: this.pluginsDir },
+ );
+ }
+
+ private loadBuiltInPlugins(): void {
+ // Built-in plugins are registered programmatically
+ // This will be used by Phase 4 to register engine plugins
+ this.logger.debug('Built-in plugins loading point (Phase 4)', {
+ action: 'builtin_plugins_init',
+ });
+ }
+
+ private loadPluginsFromDirectory(dir: string): void {
+ // Reconcile any interrupted-update leftovers BEFORE scanning, so a crash mid-swap can't make a
+ // plugin silently vanish while its registry entry still claims it is installed.
+ this.recoverInterruptedUpdates(dir);
+
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
+
+ for (const entry of entries) {
+ // Skip non-directories and dot-prefixed dirs (e.g. a crash-leftover `.<id>.bak` update backup or
+ // `.<id>.new` staging tree), so a half-finished update can't be re-loaded as a duplicate-id
+ // plugin on the next boot. recoverInterruptedUpdates has already reconciled them by this point.
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
+
+ // Already loaded by an earlier scan. Only reachable through the legacy-directory compatibility
+ // scan, where the same package can sit in both trees: the copy in the configured dir wins, and
+ // re-loading it would throw "already loaded" — which the catch below would persist as ERROR on
+ // a perfectly healthy plugin.
+ if (this.plugins.has(entry.name)) {
+ this.logger.debug(`Skipped ${entry.name} in ${dir}: already loaded from another plugin directory`, {
+ pluginId: entry.name,
+ action: 'plugin_duplicate_dir_skipped',
+ });
+ continue;
+ }
+
+ const pluginPath = path.join(dir, entry.name);
+ const manifestPath = path.join(pluginPath, 'manifest.json');
+
+ if (!fs.existsSync(manifestPath)) {
+ if (LEGACY_REMOVED_PLUGIN_IDS.has(entry.name)) {
+ this.logger.warn(
+ `Skipped ${entry.name}: not a plugin (no manifest.json). Delete the directory to silence this, ` +
+ `or add a manifest.json if it is meant to load.`,
+ { pluginPath, action: 'manifest_missing' },
+ );
+ this.pluginStorage.deletePluginEntry(entry.name);
+ this.logger.log(`Pruned stale registry entry for removed built-in plugin: ${entry.name}`, {
+ action: 'registry_ghost_pruned',
+ });
+ continue;
+ }
+
+ // A manifest-less directory here means one of three different things, which used to log
+ // identically: <dataDir>/plugins/<id> is BOTH the package dir and the plugin's ctx.storage
+ // dir, so a built-in that persists anything owns a manifest-less directory on every healthy
+ // boot, while an installed plugin whose code is gone (a container recreate that took the
+ // image layer with it) leaves a directory that looks exactly the same — state still in it.
+ // The registry is what tells them apart, so consult it rather than logging one wording for
+ // the routine case, the data-loss case, and a directory an operator simply dropped in here.
+ const registryEntry = this.pluginStorage.getPluginEntry(entry.name);
+ if (registryEntry?.builtIn) {
+ this.logger.debug(`Skipped ${entry.name}: built-in plugin storage, not a package directory`, {
+ pluginPath,
+ pluginId: entry.name,
+ action: 'builtin_storage_dir_skipped',
+ });
+ } else if (registryEntry) {
+ this.logger.warn(
+ `Plugin ${entry.name} is installed but its code is missing from ${pluginPath} (no manifest.json) ` +
+ `while its stored data is still there. Reinstall it — its config and stored data are kept. ` +
+ `Plugin code kept outside the data volume does not survive a container recreate.`,
+ { pluginPath, pluginId: entry.name, action: 'plugin_code_missing' },
+ );
+ } else {
+ // Operators do drop unrelated directories in here, and this fires on every boot for each one.
+ // The old bare "missing manifest.json" wording read like an internal fault — #981's reporter
+ // pasted it into an unrelated session bug as evidence. Say what was skipped and what to do.
+ this.logger.warn(
+ `Skipped ${entry.name}: not a plugin (no manifest.json). Delete the directory to silence this, ` +
+ `or add a manifest.json if it is meant to load.`,
+ { pluginPath, action: 'manifest_missing' },
+ );
+ }
+ continue;
+ }
+
+ try {
+ this.loadPlugin(pluginPath);
+ } catch (error) {
+ this.logger.error(
+ `Failed to load plugin ${entry.name}`,
+ error instanceof Error ? error.message : String(error),
+ { pluginPath, action: 'plugin_load_failed' },
+ );
+ // The runtime just dropped this plugin, but a registry entry from a previous successful
+ // load still claims it installed/enabled — reconcile the persisted state to ERROR so the
+ // mismatch surfaces instead of silently persisting. The entry itself (operator config,
+ // enabledByOperator) is preserved: fix the manifest/main and the next boot loads and
+ // re-enables it (ensureRegistryEntry resets the status on a successful load). No-op when
+ // no entry exists (a hand-placed dir that never loaded).
+ this.pluginStorage.setPluginStatus(entry.name, PluginStatus.ERROR);
+ }
+ }
+ }
+
+ /**
+ * Crash recovery for in-place updates (see PluginsService.updatePackageInner). An update stages the
+ * new tree at `.<id>.new`, then swaps with two renames (live → `.<id>.bak`, staging → live). Both
+ * siblings are dot-prefixed, so the scan above skips them — but without reconciliation a crash
+ * BETWEEN the renames loses the live dir and the plugin silently vanishes from the runtime while
+ * its registry entry still claims it is installed. Reconcile before scanning:
+ * - live dir missing + `.<id>.bak` present → the swap was interrupted: restore the backup as the
+ * live dir (the previous version comes back; the update never touched the registry entry or the
+ * operator's config, so nothing else needs repairing).
+ * - live dir present + `.<id>.bak` present → the swap completed but the process died before the
+ * backup cleanup: drop the backup.
+ * - `.<id>.new` present → staging from an interrupted/failed update; the live install (if any)
+ * was never swapped: drop it.
+ * Best-effort: a reconciliation failure is logged and left for the next boot rather than aborting
+ * plugin loading entirely.
+ */
+ private recoverInterruptedUpdates(dir: string): void {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ const match = /^\.(.+)\.(?:bak|new)$/.exec(entry.name);
+ if (!match) continue;
+ const pluginId = match[1];
+ const leftover = path.join(dir, entry.name);
+ const liveDir = path.join(dir, pluginId);
+ try {
+ if (entry.name === pluginUpdateStagingDirName(pluginId)) {
+ fs.rmSync(leftover, { recursive: true, force: true });
+ this.logger.warn(`Dropped stale update staging for plugin ${pluginId}`, {
+ pluginId,
+ action: 'plugin_update_staging_pruned',
+ });
+ } else if (!fs.existsSync(liveDir)) {
+ fs.renameSync(leftover, liveDir);
+ this.logger.warn(
+ `Restored plugin ${pluginId} from its update backup — a previous update was interrupted mid-swap`,
+ { pluginId, action: 'plugin_update_backup_restored' },
+ );
+ } else {
+ fs.rmSync(leftover, { recursive: true, force: true });
+ this.logger.warn(`Dropped stale update backup for plugin ${pluginId}`, {
+ pluginId,
+ action: 'plugin_update_backup_pruned',
+ });
+ }
+ } catch (error) {
+ this.logger.error(
+ `Failed to reconcile the interrupted-update leftover ${entry.name}`,
+ error instanceof Error ? error.message : String(error),
+ { pluginId, action: 'plugin_update_recovery_failed' },
+ );
+ }
+ }
+ }
+
+ loadPlugin(pluginPath: string): PluginInstance {
+ const manifestPath = path.join(pluginPath, 'manifest.json');
+ const manifestContent = fs.readFileSync(manifestPath, 'utf-8');
+ const manifest = JSON.parse(manifestContent) as unknown;
+
+ // Boot-time validation is the SAME validation install runs (parsePluginPackage): a hand-placed
+ // or crash-leftover directory must satisfy the install contract too — plain-object shape,
+ // required string fields, id format + reserved ids, extension-only type, and a `main` that
+ // cannot escape the plugin dir. Otherwise a manifest the installer would have rejected loads
+ // anyway and only fails (or worse, runs unexpected code) at enable time.
+ validatePluginManifest(manifest);
+
+ // Anchor `main` inside THIS on-disk directory: the lexical check above is forward-slash only,
+ // so a platform-separator escape (e.g. Windows-style `..\x`) would slip past it — resolve and
+ // re-check containment here. Parity with install's in-archive check: the entry must exist as a
+ // file, or the plugin loads "successfully" and only blows up when someone enables it.
+ const mainPath = resolvePluginMainPath(path.dirname(pluginPath), path.basename(pluginPath), manifest.main);
+ if (!fs.existsSync(mainPath) || !fs.statSync(mainPath).isFile()) {
+ throw new Error(`Plugin ${manifest.id}: main file not found in the plugin directory: ${manifest.main}`);
+ }
+
+ // Reject a malformed ingress declaration (SDK-major mismatch, missing webhook:ingress permission,
+ // duplicate/empty routes, non-positive toleranceSec) at load time instead of letting it silently
+ // load and become provisionable. No-op for plugins that declare no ingress. A route declaring
+ // signature.scheme 'none' is rejected unless the operator opted in via ALLOW_UNSIGNED_INGRESS=true.
+ validateIngressManifest(manifest, this.configService.get<boolean>('ingress.allowUnsigned', false));
+
+ // Surface a loud warning for any ingress route that skips signature verification — a scheme:'none'
+ // route is a fully-unauthenticated public endpoint that can trigger WhatsApp sends. Only reachable
+ // when the operator opted in (otherwise validateIngressManifest above rejected it); the warning
+ // reminds them to front the URL with a network/reverse-proxy ACL.
+ warnUnauthenticatedIngressRoutes(manifest, this.logger);
+
+ // Same loud-warning treatment for an hmac route whose declared timestamp is not bound into the
+ // signature: freshness is enforced, but an unsigned timestamp lets a replay mint a fresh one.
+ warnUnsignedTimestampRoutes(manifest, this.logger);
+
+ // Check if plugin already loaded
+ if (this.plugins.has(manifest.id)) {
+ throw new Error(`Plugin ${manifest.id} is already loaded`);
+ }
+
+ // Load any persisted config + per-session activation + per-session config so an operator's choices
+ // survive a restart.
+ const storedConfig = this.pluginStorage.getPluginConfig(manifest.id) ?? {};
+ const storedSessions = this.pluginStorage.getPluginSessions(manifest.id) ?? undefined;
+ const storedSessionConfig = this.pluginStorage.getPluginSessionConfig(manifest.id) ?? undefined;
+
+ const pluginInstance: PluginInstance = {
+ manifest,
+ status: PluginStatus.INSTALLED,
+ // Seed schema-declared defaults under the stored config, so a defaulted field is never
+ // missing when the plugin later runs (explicit values are never overwritten).
+ config: seedConfigDefaults(manifest.configSchema, storedConfig),
+ instance: null,
+ loadedAt: new Date(),
+ builtIn: false,
+ activeSessions: storedSessions,
+ sessionConfig: storedSessionConfig,
+ // The directory this package was actually found in, which is not necessarily
+ // <plugins.dir>/<id> — the legacy directory is scanned too. Recorded here because this is the
+ // only point that knows it; every later write against the package reads it back.
+ packageDir: path.resolve(pluginPath),
+ };
+
+ this.plugins.set(manifest.id, pluginInstance);
+
+ // Ensure a registry entry exists so later enable/disable/config writes persist.
+ this.ensureRegistryEntry(manifest, false);
+
+ this.logger.log(`Plugin loaded: ${manifest.name} v${manifest.version}`, {
+ pluginId: manifest.id,
+ type: manifest.type,
+ action: 'plugin_loaded',
+ });
+
+ return pluginInstance;
+ }
+
+ /**
+ * Ensure a freshly-loaded plugin has a persisted registry entry, so later enable/disable/config
+ * writes (which only update an EXISTING entry) actually persist instead of silently no-op'ing.
+ * Creates a complete INSTALLED entry when none exists; an existing entry's persisted status/config
+ * is left untouched. Best-effort (saveRegistry swallows fs errors, so a disk failure never turns a
+ * load into a 500). Does NOT enable or run the plugin — boot never auto-executes plugin code.
+ */
+ ensureRegistryEntry(manifest: PluginManifest, builtIn: boolean): void {
+ // Reconcile the persisted entry with the freshly-loaded runtime: loading never runs the plugin, so
+ // the entry's status is (re)set to INSTALLED to match the runtime. Enabling is a separate step that
+ // runs the lifecycle — at bootstrap for a plugin the operator had enabled (see
+ // PluginLoaderService.onApplicationBootstrap), or on an explicit ADMIN action. The operator's
+ // persisted config and enable decision are preserved so settings/secrets and the decision itself
+ // survive. Best-effort: saveRegistry swallows fs errors, so a disk failure never turns a load
+ // into a 500.
+ const existing = this.pluginStorage.getPluginEntry(manifest.id);
+ // The operator's standing enable decision (#856). `status` below is deliberately reset, so intent
+ // has to live in its own field or a restart loses it. A pre-#856 row has no such field: adopt it
+ // from a status of ENABLED, which can only have been written by an explicit enable since the last
+ // boot (every boot rewrites the status to INSTALLED), so it is a faithful record of the intent.
+ const enabledByOperator = existing?.enabledByOperator ?? existing?.status === PluginStatus.ENABLED;
+ this.pluginStorage.setPluginEntry({
+ id: manifest.id,
+ type: manifest.type,
+ name: manifest.name,
+ version: manifest.version,
+ status: PluginStatus.INSTALLED,
+ // The operator's persisted config survives, with schema-declared defaults seeded under it so
+ // the persisted entry matches the seeded runtime config (see loadPlugin).
+ config: seedConfigDefaults(manifest.configSchema, existing?.config ?? {}),
+ builtIn,
+ installedAt: existing?.installedAt ?? new Date(),
+ updatedAt: new Date(),
+ // setPluginEntry REPLACES the entry, so the operator's per-session activation + config must be
+ // carried over or every boot wipes them from disk (lost after the second restart).
+ activeSessions: existing?.activeSessions,
+ sessionConfig: existing?.sessionConfig,
+ enabledByOperator,
+ });
+ }
+}
diff --git a/src/core/plugins/plugin-paths.ts b/src/core/plugins/plugin-paths.ts
new file mode 100644
index 000000000..2fbfdbb0b
--- /dev/null
+++ b/src/core/plugins/plugin-paths.ts
@@ -0,0 +1,38 @@
+import * as path from 'path';
+
+/**
+ * Resolve a plugin's `main` entry to an absolute path, asserting it stays inside
+ * <pluginsDir>/<pluginId>. `main` comes from a user-supplied manifest, so a
+ * value like '../../etc/passwd' (or an absolute path) must be rejected BEFORE require().
+ */
+export function resolvePluginMainPath(pluginsDir: string, pluginId: string, main: string): string {
+ const base = path.resolve(pluginsDir, pluginId);
+ const mainPath = path.resolve(base, main);
+ if (mainPath !== base && !mainPath.startsWith(base + path.sep)) {
+ throw new Error(`Plugin ${pluginId} main path escapes the plugin directory`);
+ }
+ return mainPath;
+}
+
+/**
+ * The same containment guard, anchored to a plugin's own package directory rather than to the
+ * configured plugins root. Callers that hold a loaded plugin's `packageDir` use this: the package
+ * may sit in the legacy directory, in which case resolving against `plugins.dir` names a file that
+ * does not exist.
+ */
+export function resolvePluginEntryPath(packageDir: string, entry: string): string {
+ return resolvePluginMainPath(path.dirname(packageDir), path.basename(packageDir), entry);
+}
+
+/**
+ * Sibling directory names an in-place plugin update stages into / backs up to (see
+ * PluginsService.updatePackageInner). Dot-prefixed so the boot directory scan skips them, and placed
+ * inside the plugins dir so the swap renames stay on one filesystem (EXDEV-safe). The scanner's
+ * boot-time reconciler (recoverInterruptedUpdates) keys off these exact names.
+ */
+export function pluginUpdateStagingDirName(pluginId: string): string {
+ return `.${pluginId}.new`;
+}
+export function pluginUpdateBackupDirName(pluginId: string): string {
+ return `.${pluginId}.bak`;
+}
diff --git a/src/core/plugins/plugin-uninstaller.spec.ts b/src/core/plugins/plugin-uninstaller.spec.ts
new file mode 100644
index 000000000..f90567780
--- /dev/null
+++ b/src/core/plugins/plugin-uninstaller.spec.ts
@@ -0,0 +1,162 @@
+import * as fs from 'fs';
+import * as os from 'os';
+import * as path from 'path';
+import { ConfigService } from '@nestjs/config';
+import { createLogger } from '../../common/services/logger.service';
+import { PluginStorageService } from './plugin-storage.service';
+import { PluginUninstaller } from './plugin-uninstaller';
+import { PluginInstance, PluginStatus, PluginType } from './plugin.interfaces';
+
+/**
+ * The uninstall job, on the collaborator that owns it since the loader split. Construction only is
+ * adapted from the loader-level specs these tests moved from: instead of loading plugins through the
+ * boot scan, the shared registry Map and persisted entries are seeded directly — the inputs
+ * uninstallPlugin actually reads. The unload seam is the callback the lifecycle would provide; every
+ * assertion is unchanged.
+ */
+const makeUninstaller = (config: ConfigService, storage: PluginStorageService, pluginsDir: string) => {
+ const plugins = new Map<string, PluginInstance>();
+ const uninstaller = new PluginUninstaller(
+ createLogger('PluginLoaderService'),
+ plugins,
+ storage,
+ pluginsDir,
+ // The lifecycle's unload drops the runtime record; that is all uninstall needs from it.
+ pluginId => {
+ plugins.delete(pluginId);
+ return Promise.resolve();
+ },
+ );
+ return { uninstaller, plugins };
+};
+
+/** The registry record a boot-scan load would have left for an installed user plugin. */
+const loadedUserPlugin = (id: string, packageDir: string): PluginInstance => ({
+ manifest: { id, name: id, version: '1.0.0', type: PluginType.EXTENSION, main: 'index.js' },
+ status: PluginStatus.INSTALLED,
+ config: {},
+ instance: null,
+ loadedAt: new Date(),
+ builtIn: false,
+ packageDir,
+});
+
+const seedEntry = (storage: PluginStorageService, id: string, builtIn = false): void => {
+ storage.setPluginEntry({
+ id,
+ type: 'extension',
+ name: id,
+ version: '1.0.0',
+ status: 'installed',
+ config: {},
+ builtIn,
+ installedAt: new Date(),
+ updatedAt: new Date(),
+ } as never);
+};
+
+describe('PluginUninstaller — uninstall', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let storage: PluginStorageService;
+ let uninstaller: PluginUninstaller;
+ let plugins: Map<string, PluginInstance>;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-uninst-'));
+ pluginsDir = path.join(tmpDir, 'plugins');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),
+ } as unknown as ConfigService;
+ storage = new PluginStorageService(config);
+ ({ uninstaller, plugins } = makeUninstaller(config, storage, pluginsDir));
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writeUserPlugin = (id: string): string => {
+ const dir = path.join(pluginsDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ return dir;
+ };
+
+ it('removes the plugin directory, registry entry, and runtime instance', async () => {
+ const dir = writeUserPlugin('user-plg');
+ plugins.set('user-plg', loadedUserPlugin('user-plg', dir));
+ seedEntry(storage, 'user-plg');
+ expect(storage.getPluginEntry('user-plg')).toBeDefined();
+
+ await uninstaller.uninstallPlugin('user-plg');
+
+ expect(fs.existsSync(dir)).toBe(false);
+ expect(storage.getPluginEntry('user-plg')).toBeUndefined();
+ expect(plugins.get('user-plg')).toBeUndefined();
+ });
+
+ it('refuses to uninstall a built-in plugin', async () => {
+ plugins.set('core-engine', { ...loadedUserPlugin('core-engine', pluginsDir), builtIn: true });
+ seedEntry(storage, 'core-engine', true);
+ await expect(uninstaller.uninstallPlugin('core-engine')).rejects.toThrow(/built-in/i);
+ });
+});
+
+describe('PluginUninstaller — uninstall cleans up split-dir plugin storage', () => {
+ let tmpDir: string;
+ let pluginsDir: string;
+ let dataDir: string;
+ let uninstaller: PluginUninstaller;
+ let plugins: Map<string, PluginInstance>;
+ let storage: PluginStorageService;
+
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-splitstore-'));
+ // Split-dir deployment: the package dir and the ctx.storage data dir are NOT the same tree.
+ pluginsDir = path.join(tmpDir, 'plugins');
+ dataDir = path.join(tmpDir, 'data');
+ fs.mkdirSync(pluginsDir, { recursive: true });
+ const config = {
+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? dataDir : undefined),
+ } as unknown as ConfigService;
+ storage = new PluginStorageService(config);
+ ({ uninstaller, plugins } = makeUninstaller(config, storage, pluginsDir));
+ });
+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));
+
+ const writeUserPlugin = (id: string): string => {
+ const dir = path.join(pluginsDir, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(
+ path.join(dir, 'manifest.json'),
+ JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
+ );
+ fs.writeFileSync(path.join(dir, 'index.js'), 'module.exports = class {};');
+ return dir;
+ };
+
+ it('removes the plugin’s storage dir on uninstall, and only that plugin’s', async () => {
+ const dir = writeUserPlugin('user-plg');
+ writeUserPlugin('other-plg');
+ plugins.set('user-plg', loadedUserPlugin('user-plg', dir));
+ plugins.set('other-plg', loadedUserPlugin('other-plg', path.join(pluginsDir, 'other-plg')));
+ seedEntry(storage, 'user-plg');
+ seedEntry(storage, 'other-plg');
+ // Persist real ctx.storage state for both plugins (split-dir: under <dataDir>/plugins/<id>).
+ await storage.createPluginStorage('user-plg').set('token', { secret: 'abc' });
+ await storage.createPluginStorage('other-plg').set('token', { secret: 'xyz' });
+ const userStorageDir = path.join(dataDir, 'plugins', 'user-plg');
+ const otherStorageDir = path.join(dataDir, 'plugins', 'other-plg');
+ expect(fs.existsSync(userStorageDir)).toBe(true);
+
+ await uninstaller.uninstallPlugin('user-plg');
+
+ expect(fs.existsSync(dir)).toBe(false); // package dir (unchanged behavior)
+ expect(fs.existsSync(userStorageDir)).toBe(false); // split-dir storage is now cleaned too
+ expect(fs.existsSync(otherStorageDir)).toBe(true); // another plugin's storage is untouched
+ expect(await storage.createPluginStorage('other-plg').get('token')).toEqual({ secret: 'xyz' });
+ });
+});
diff --git a/src/core/plugins/plugin-uninstaller.ts b/src/core/plugins/plugin-uninstaller.ts
new file mode 100644
index 000000000..cfc74b7c5
--- /dev/null
+++ b/src/core/plugins/plugin-uninstaller.ts
@@ -0,0 +1,77 @@
+import * as fs from 'fs';
+import * as path from 'path';
+import { createLogger } from '../../common/services/logger.service';
+import { PluginInstance } from './plugin.interfaces';
+import { PluginStorageService } from './plugin-storage.service';
+
+/**
+ * The uninstall half of the plugin loader: fully remove an installed user plugin — disable + unload
+ * from the runtime, drop its persisted registry entry, and delete its directories from disk. Install,
+ * download and unpack live feature-side (modules/plugins); this is the runtime-owned removal they and
+ * the REST surface call through PluginLoaderService.
+ *
+ * Split out of PluginLoaderService so the loader reads as the public facade while the removal
+ * contract — package-dir provenance, the traversal guard, split-dir storage cleanup — is reviewed on
+ * its own. A plain class, not a Nest provider: the loader constructs it in its constructor (the same
+ * pattern as PluginSandboxBridge / PluginCapabilityContext), so the loader's public constructor
+ * signature — which specs build directly — is unchanged.
+ */
+export class PluginUninstaller {
+ constructor(
+ // The LOADER's logger, deliberately — uninstall lines carry the PluginLoaderService tag, and
+ // that context is operator-visible. Creating a second logger here would silently retag every
+ // uninstall log line the moment this moved.
+ private readonly logger: ReturnType<typeof createLogger>,
+ // The LOADER's plugin registry, passed BY REFERENCE (see the class doc): reads here see the same
+ // map the loader, the scanner and the bridge share.
+ private readonly plugins: Map<string, PluginInstance>,
+ private readonly pluginStorage: PluginStorageService,
+ private readonly pluginsDir: string,
+ /** The lifecycle's unload — passed as a callback so this file never imports the lifecycle back. */
+ private readonly unload: (pluginId: string) => Promise<void>,
+ ) {}
+
+ /** <plugins.dir>/<id> for an id with no loaded package, or null if the id escapes that root. */
+ private resolveUninstallDir(pluginId: string): string | null {
+ const base = path.resolve(this.pluginsDir);
+ const dir = path.resolve(base, pluginId);
+ return dir !== base && dir.startsWith(base + path.sep) ? dir : null;
+ }
+
+ /**
+ * Fully remove an installed user plugin: disable + unload from the runtime, drop its persisted
+ * registry entry, and delete its directory from disk. Built-ins (engines, bundled extensions) are
+ * registered programmatically with no on-disk dir and must never be removable.
+ */
+ async uninstallPlugin(pluginId: string): Promise<void> {
+ if (this.pluginStorage.getPluginEntry(pluginId)?.builtIn) {
+ throw new Error(`Cannot uninstall built-in plugin ${pluginId}`);
+ }
+
+ // Read the package location BEFORE unloading: unloadPlugin drops the runtime record that holds
+ // it, and for a plugin loaded from the legacy directory the configured root is the wrong tree —
+ // deleting there removes the ctx.storage directory and leaves the code, so the plugin comes
+ // back on the next boot having reported a successful uninstall.
+ const recordedDir = this.plugins.get(pluginId)?.packageDir ?? null;
+
+ if (this.plugins.has(pluginId)) {
+ await this.unload(pluginId);
+ }
+ this.pluginStorage.deletePluginEntry(pluginId);
+
+ // A recorded directory came from the boot scan and is already contained. Without one the id is
+ // the only input, so it stays behind the traversal guard against the configured root.
+ const dir = recordedDir ?? this.resolveUninstallDir(pluginId);
+ if (dir && fs.existsSync(dir)) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+
+ // Drop the plugin's ctx.storage data dir. Under shipped defaults it lives INSIDE the package
+ // dir (already gone above), but a split-dir deployment (PLUGINS_DIR outside the data dir) would
+ // otherwise leak <dataDir>/plugins/<id> — persisted secrets included — on every uninstall.
+ // Best-effort, and strictly that one plugin's directory.
+ this.pluginStorage.deletePluginData(pluginId);
+
+ this.logger.log(`Plugin uninstalled: ${pluginId}`, { pluginId, action: 'plugin_uninstalled' });
+ }
+}