Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(plugins): put installed plugin code in the same tree as the plugin registry (#1036)

Yudhi Armyndharis536796cc3251
diff --git a/.env.example b/.env.example
index 6f234895a..62ba89468 100644
--- a/.env.example
+++ b/.env.example
@@ -462,7 +462,11 @@ SEARCH_LIMIT_MAX=100 # hard cap on the `limit` query param
# =============================================================================
# PLUGINS
# =============================================================================
-PLUGINS_DIR=./data/plugins # Plugin directory
+# Where installed plugin packages live. This is also the default; it must stay inside the data
+# directory, because that is where the plugin registry and every plugin's persisted storage are —
+# plugin code kept elsewhere (e.g. in a container layer) is lost while its config and secrets
+# survive, leaving registry entries that point at code that no longer exists.
+PLUGINS_DIR=./data/plugins # Plugin directory (default: ./data/plugins)
# Cap on a plugin .zip downloaded by install-from-URL (matches the 5 MB upload limit). A non-positive
# or non-numeric value falls back to the default.
# PLUGIN_DOWNLOAD_MAX_BYTES=5242880 # default 5 MiB
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index cbbe159b5..bcd98264f 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -80,7 +80,8 @@ services:
- STORAGE_TYPE=${STORAGE_TYPE:-local}
- STORAGE_LOCAL_PATH=${STORAGE_LOCAL_PATH:-/app/data/media}
# Install plugins into the writable, persistent data volume (the root FS is read-only). Matches
- # docker-compose.yml; without this it falls back to ./plugins on the read-only root and install fails.
+ # docker-compose.yml and the application default; set explicitly so the path stays correct even
+ # if the volume moves.
- PLUGINS_DIR=${PLUGINS_DIR:-/app/data/plugins}
# Plugin install-from-URL redirect policy (ssrf-guard): off unless the exact string 'true'.
- PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS=${PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS:-false}
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index 68a4c8171..8b1776aec 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -153,8 +153,8 @@ services:
# The env var is API_MASTER_KEY (not API_KEY_MASTER); never hardcode a key — set a
# strong secret. Production refuses to boot with a placeholder/default.
- API_MASTER_KEY=
- # Without this, plugins fall back to ./plugins (outside the data volume) and are lost
- # when the container is replaced. The shipped compose sets it for the same reason.
+ # Pins the plugin directory onto the data volume. This is also the default, so the setting is
+ # belt-and-braces — it keeps working if the volume is mounted somewhere else.
- PLUGINS_DIR=/app/data/plugins
volumes:
- ./:/app
@@ -232,8 +232,8 @@ services:
- REDIS_HOST=${REDIS_HOST}
- REDIS_PORT=${REDIS_PORT}
- API_MASTER_KEY=${API_MASTER_KEY}
- # Without this, plugins fall back to ./plugins (outside the data volume) and are lost
- # when the container is replaced. The shipped compose sets it for the same reason.
+ # Pins the plugin directory onto the data volume. This is also the default, so the setting is
+ # belt-and-braces — it keeps working if the volume is mounted somewhere else.
- PLUGINS_DIR=/app/data/plugins
volumes:
# Session auth, the main (auth/audit) SQLite DB, media and plugins all live here — losing
diff --git a/docs/11-operational-runbooks.md b/docs/11-operational-runbooks.md
index bf4e2ef94..c850401cf 100644
--- a/docs/11-operational-runbooks.md
+++ b/docs/11-operational-runbooks.md
@@ -551,8 +551,9 @@ OPENWA_DATA_DIR=/srv/openwa/data \
> compose. Run the script where that volume is mounted — e.g. point `OPENWA_DATA_DIR`
> at the volume's mountpoint, or run it inside a container with `/app/data` mounted. When operating
> directly on the host mount, also set any path that does not use its default below `OPENWA_DATA_DIR`
-> (notably compose's colocated `PLUGINS_DIR`, and `MAIN_DATABASE_NAME` / `DATABASE_NAME` when the app
-> overrides them) to the corresponding host-visible path.
+> (`MAIN_DATABASE_NAME` / `DATABASE_NAME` when the app overrides them, and `PLUGINS_DIR` only if it
+> points somewhere outside the data directory — unset, it follows `OPENWA_DATA_DIR` like the app's own
+> default does) to the corresponding host-visible path.
**Verification:**
diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.md
index eadd07280..6b52a249a 100644
--- a/docs/19-plugin-architecture.md
+++ b/docs/19-plugin-architecture.md
@@ -485,7 +485,9 @@ also applies the per-session activation gate.
discovers, loads, and runs plugins.
**Discovery & load.** On `onModuleInit` it registers built-in plugins programmatically (the engine
-adapters; see §19.7), then scans the plugins directory (`plugins.dir`, default `./plugins`). For each
+adapters; see §19.7), then scans the plugins directory (`plugins.dir`, default `<dataDir>/plugins` — the same tree the
+registry and each plugin's `ctx.storage` live in, so code and persisted state stay together on one
+volume; `PLUGINS_DIR` overrides it). For each
sub-directory with a `manifest.json` it reads the manifest, validates the required fields
(`id`/`name`/`version`/`type`/`main`), and records an `INSTALLED` plugin plus a persisted registry
entry — **without running any plugin code**. Persisted config and per-session activation/config are
diff --git a/scripts/backup.sh b/scripts/backup.sh
index 2855d9385..33fe46cb3 100755
--- a/scripts/backup.sh
+++ b/scripts/backup.sh
@@ -53,7 +53,10 @@ DATA_DB="${DATABASE_NAME:-./data/openwa.sqlite}"
SESSIONS_DIR="${SESSION_DATA_PATH:-$DATA_DIR/sessions}"
BAILEYS_DIR="${BAILEYS_AUTH_DIR:-$DATA_DIR/baileys}"
MEDIA_DIR="${STORAGE_LOCAL_PATH:-$DATA_DIR/media}"
-PLUGIN_PACKAGES_DIR="${PLUGINS_DIR:-./plugins}"
+# Installed plugin code. The app defaults this to <dataDir>/plugins — the same tree as the
+# registry and each plugin's ctx.storage below — so an unset PLUGINS_DIR must resolve there
+# too, or the archive silently omits the plugin packages.
+PLUGIN_PACKAGES_DIR="${PLUGINS_DIR:-$DATA_DIR/plugins}"
PLUGIN_STATE_DIR="$DATA_DIR/plugins"
GENERATED_ENV="$DATA_DIR/.env.generated"
ADMIN_KEY_FILE="$DATA_DIR/.api-key"
diff --git a/scripts/restore.sh b/scripts/restore.sh
index 1ce67645f..dcfc4fe91 100755
--- a/scripts/restore.sh
+++ b/scripts/restore.sh
@@ -65,7 +65,10 @@ DATA_DB="${DATABASE_NAME:-./data/openwa.sqlite}"
SESSIONS_DIR="${SESSION_DATA_PATH:-$DATA_DIR/sessions}"
BAILEYS_DIR="${BAILEYS_AUTH_DIR:-$DATA_DIR/baileys}"
MEDIA_DIR="${STORAGE_LOCAL_PATH:-$DATA_DIR/media}"
-PLUGIN_PACKAGES_DIR="${PLUGINS_DIR:-./plugins}"
+# Installed plugin code. The app defaults this to <dataDir>/plugins — the same tree as the
+# registry and each plugin's ctx.storage below — so an unset PLUGINS_DIR must resolve there
+# too, or the archive silently omits the plugin packages.
+PLUGIN_PACKAGES_DIR="${PLUGINS_DIR:-$DATA_DIR/plugins}"
PLUGIN_STATE_DIR="$DATA_DIR/plugins"
RESTORE_TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
RESOLVED_CWD="$(pwd -P)"
diff --git a/src/config/configuration.spec.ts b/src/config/configuration.spec.ts
index 26953dda6..e62a4801f 100644
--- a/src/config/configuration.spec.ts
+++ b/src/config/configuration.spec.ts
@@ -1,4 +1,6 @@
+import * as path from 'path';
import configuration, {
+ DEFAULT_DATA_DIR,
PINNED_BROWSER_LOCALE,
resolveNonNegativeIntEnv,
withPinnedBrowserLocale,
@@ -104,6 +106,38 @@ describe('configuration — Postgres pool timeouts', () => {
});
});
+describe('configuration — plugins directory default', () => {
+ const orig = process.env.PLUGINS_DIR;
+ afterEach(() => {
+ if (orig === undefined) delete process.env.PLUGINS_DIR;
+ else process.env.PLUGINS_DIR = orig;
+ });
+
+ // The package dir and the registry are two halves of one install: PluginStorageService writes
+ // <dataDir>/plugins/registry.json, so a package dir defaulting anywhere else means the loader scans
+ // an empty tree while the registry still lists every plugin as installed — and, in Docker, an
+ // install lands in the container layer instead of on the data volume.
+ it('defaults plugins.dir to <dataDir>/plugins so plugin code and the registry share one tree', () => {
+ delete process.env.PLUGINS_DIR;
+ const cfg = configuration();
+ expect(cfg.dataDir).toBe(DEFAULT_DATA_DIR);
+ expect(cfg.plugins.dir).toBe(path.join(cfg.dataDir, 'plugins'));
+ });
+
+ it('exposes the historical ./plugins default as legacyDir so an existing install keeps loading', () => {
+ delete process.env.PLUGINS_DIR;
+ expect(configuration().plugins.legacyDir).toBe('./plugins');
+ });
+
+ it('lets an explicit PLUGINS_DIR win, and drops the legacy fallback with it', () => {
+ process.env.PLUGINS_DIR = '/srv/openwa-plugins';
+ const cfg = configuration();
+ expect(cfg.plugins.dir).toBe('/srv/openwa-plugins');
+ // An operator who named the directory has said where plugins live; nothing may second-guess it.
+ expect(cfg.plugins.legacyDir).toBeNull();
+ });
+});
+
describe('configuration — plugin download cap is fail-safe', () => {
const orig = process.env.PLUGIN_DOWNLOAD_MAX_BYTES;
afterEach(() => {
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index ee7a4f104..d486fec15 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -1,7 +1,35 @@
+import * as path from 'path';
import { computeFeatureFlags } from './feature-flags';
import { resolveInflightBodyBudgetBytes } from './inflight-body-budget';
import { readWsRateLimitConfig } from '../modules/events/ws-rate-limit';
+/**
+ * Root of the host's persistent state. Relative on purpose: the image sets WORKDIR /app and mounts
+ * the data volume at /app/data, so this resolves onto the volume without the config having to know
+ * whether it runs in a container.
+ *
+ * Exposed as the `dataDir` key because PluginStorageService already reads it — the key never existed,
+ * so `get('dataDir')` always fell through to its own literal while the plugin package dir defaulted
+ * from an unrelated string. Deriving both from one value is what keeps a plugin's code and its
+ * registry entry in the same tree.
+ *
+ * Deliberately NOT env-overridable: every other data path (DATABASE_NAME, MAIN_DATABASE_NAME,
+ * SESSION_DATA_PATH, BAILEYS_AUTH_DIR, STORAGE_LOCAL_PATH) carries its own override and none of them
+ * would follow a DATA_DIR knob, so such a knob would move part of the state while looking like it
+ * moved all of it.
+ */
+export const DEFAULT_DATA_DIR = './data';
+
+/** Where installed plugin packages live when PLUGINS_DIR is unset — the tree the registry is in. */
+export const DEFAULT_PLUGINS_DIR = path.join(DEFAULT_DATA_DIR, 'plugins');
+
+/**
+ * The plugin package dir OpenWA ≤ 0.12.1 defaulted to. A host that ran on that default has working
+ * plugin code sitting here, so the loader still scans it (and says so, loudly) when PLUGINS_DIR is
+ * unset — see PluginLoaderService.onModuleInit.
+ */
+export const LEGACY_PLUGINS_DIR = './plugins';
+
/**
* Shared parser for numeric env knobs whose 0 is a documented opt-out (unlimited / disabled).
* `Number('')` is 0, so a blank or whitespace-only value — exactly what a compose `${KEY:-}`
@@ -43,6 +71,10 @@ export function withPinnedBrowserLocale(args: string[]): string[] {
export default () => ({
port: parseInt(process.env.PORT || '2785', 10),
+ // Root of the persistent state tree (see DEFAULT_DATA_DIR). Read by PluginStorageService for the
+ // plugin registry and per-plugin storage; the other data paths keep their own env-specific keys.
+ dataDir: DEFAULT_DATA_DIR,
+
// HTTP server timeouts (Node http.Server). Pinned explicitly so they are operator-tunable and
// observable at boot rather than left at Node's implicit defaults. requestTimeout defaults to
// Node's 300s; keepAliveTimeout to 5s; headersTimeout to 65s (a second above keepAlive — Node
@@ -263,8 +295,19 @@ export default () => ({
// Plugin platform configuration
plugins: {
- // Where installed plugins live on disk (matches the plugin loader's default).
- dir: process.env.PLUGINS_DIR || './plugins',
+ // Where installed plugin packages live on disk. This MUST resolve to the same tree as the plugin
+ // registry (<dataDir>/plugins/registry.json, see PluginStorageService): a plugin's code and its
+ // registry entry — status, operator config, secrets, enabledByOperator — are two halves of one
+ // install. While the two defaults were independent, an unset PLUGINS_DIR put the code under
+ // ./plugins and the registry under ./data/plugins, so the loader scanned a directory that did not
+ // exist and reported "Loaded 0 plugins" while the registry still listed every plugin as installed;
+ // in Docker the install also landed in the ephemeral container layer instead of the /app/data
+ // volume, destroying the code on the next recreate while its config and secrets survived.
+ dir: process.env.PLUGINS_DIR || DEFAULT_PLUGINS_DIR,
+ // Compatibility only: the pre-fix default, scanned as a fallback so a host that installed plugins
+ // there keeps loading them. Null once PLUGINS_DIR is set — an operator who named the directory
+ // has said where plugins live, and nothing may second-guess that.
+ legacyDir: process.env.PLUGINS_DIR ? null : LEGACY_PLUGINS_DIR,
// Remote catalog of installable plugins (JSON array; the OpenWA-plugins repo's plugins.json).
// Fetched through the SSRF guard — add its host to SSRF_ALLOWED_HOSTS if it is not publicly resolvable.
catalogUrl:
diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.ts
index 935de2567..1b980b15e 100644
--- a/src/core/plugins/plugin-loader.service.spec.ts
+++ b/src/core/plugins/plugin-loader.service.spec.ts
@@ -122,6 +122,7 @@ import { ModuleRef } from '@nestjs/core';
import { HookManager } from '../hooks';
import { PluginStorageService } from './plugin-storage.service';
import { IPlugin, PluginContext, PluginManifest, PluginStatus, PluginType } from './plugin.interfaces';
+import configuration from '../../config/configuration';
import { SearchProviderRegistry } from '../../modules/search/search-provider.registry';
import { WorkerThreadChannel } from './sandbox/worker-thread-channel';
import { PluginWorkerHost } from './sandbox/plugin-worker-host';
@@ -1307,3 +1308,257 @@ describe('PluginLoaderService — uninstall cleans up split-dir plugin storage',
expect(await storage.createPluginStorage('other-plg').get('token')).toEqual({ secret: 'xyz' });
});
});
+
+/**
+ * Where the loader looks for plugin code at boot.
+ *
+ * The package dir and the plugin registry describe the same install, and they used to default from
+ * two unrelated strings: with PLUGINS_DIR unset the loader scanned ./plugins while the registry (and
+ * every plugin's ctx.storage) lived under <dataDir>/plugins. The scan found nothing and said only
+ * "Loaded 0 plugins", while the registry still listed every plugin as installed — and in Docker the
+ * install landed in the container layer instead of on the data volume, so a recreate destroyed the
+ * code while the config and secrets on the volume survived.
+ *
+ * These tests boot through the REAL configuration factory from a temp cwd standing in for the image's
+ * WORKDIR /app, because the defaults under test are relative paths resolved against the cwd.
+ */
+describe('PluginLoaderService — boot plugins directory', () => {
+ let tmpDir: string;
+ let origCwd: string;
+ const origPluginsDir = process.env.PLUGINS_DIR;
+
+ const loggerOf = (loader: PluginLoaderService): { warn: jest.Mock; log: jest.Mock; debug: jest.Mock } =>
+ (loader as unknown as { logger: { warn: jest.Mock; log: jest.Mock; debug: jest.Mock } }).logger;
+
+ /** Put a loadable plugin package (manifest + main file) at <dir>/<id>, like the installer does. */
+ const installAt = (dir: string, id: string): void => {
+ const pluginDir = path.join(dir, id);
+ fs.mkdirSync(pluginDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(pluginDir, 'manifest.json'),
+ JSON.stringify({ id, name: id, version: '1.0.0', type: 'extension', main: 'index.js' }),
+ );
+ fs.writeFileSync(path.join(pluginDir, 'index.js'), 'module.exports = class {};');
+ };
+
+ /** One `logger.warn(message, context)` call, as recorded by the spy below. */
+ type WarnCall = [message: string, context?: Record<string, unknown>];
+ type WarnMock = jest.Mock<void, WarnCall>;
+
+ const boot = (): { loader: PluginLoaderService; storage: PluginStorageService; warn: WarnMock } => {
+ const config = new ConfigService(configuration());
+ const storage = new PluginStorageService(config);
+ const loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);
+ const warn = jest.spyOn(loggerOf(loader), 'warn').mockImplementation(() => undefined) as unknown as WarnMock;
+ jest.spyOn(loggerOf(loader), 'log').mockImplementation(() => undefined);
+ jest.spyOn(loggerOf(loader), 'debug').mockImplementation(() => undefined);
+ loader.onModuleInit();
+ return { loader, storage, warn };
+ };
+
+ const warningsMatching = (warn: WarnMock, action: string): WarnCall[] =>
+ warn.mock.calls.filter(([, context]) => context?.action === action);
+
+ beforeEach(() => {
+ delete process.env.PLUGINS_DIR;
+ // realpath: on macOS os.tmpdir() is a symlink, and process.cwd() reports the resolved path.
+ tmpDir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'owa-pluginsdir-')));
+ origCwd = process.cwd();
+ process.chdir(tmpDir);
+ });
+
+ afterEach(() => {
+ process.chdir(origCwd);
+ if (origPluginsDir === undefined) delete process.env.PLUGINS_DIR;
+ else process.env.PLUGINS_DIR = origPluginsDir;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ // THE regression: with PLUGINS_DIR unset, plugin code sitting where the registry lives must load.
+ it('loads plugin code from <dataDir>/plugins when PLUGINS_DIR is unset', () => {
+ installAt(path.join(tmpDir, 'data', 'plugins'), 'ext-data');
+
+ const { loader } = boot();
+
+ expect(loader.getPlugin('ext-data')).toBeDefined();
+ // ...and the registry is written into that same tree, which is the whole point: an install's code
+ // and its persisted entry can never end up on different volumes again.
+ expect(fs.existsSync(path.join(tmpDir, 'data', 'plugins', 'registry.json'))).toBe(true);
+ });
+
+ it('still loads plugins left at the legacy ./plugins location, and says so', () => {
+ installAt(path.join(tmpDir, 'plugins'), 'ext-legacy');
+
+ const { loader, warn } = boot();
+
+ expect(loader.getPlugin('ext-legacy')).toBeDefined();
+ const [message] = warningsMatching(warn, 'plugins_legacy_dir')[0];
+ // The operator must be able to act on this without reading the source: both paths, and how to
+ // make the choice permanent either way.
+ expect(message).toContain(path.join('.', 'plugins'));
+ expect(message).toContain(path.join('data', 'plugins'));
+ expect(message).toContain('PLUGINS_DIR');
+ });
+
+ it('loads plugins from both locations while a host is mid-migration', () => {
+ installAt(path.join(tmpDir, 'data', 'plugins'), 'ext-new');
+ installAt(path.join(tmpDir, 'plugins'), 'ext-legacy');
+
+ const { loader } = boot();
+
+ expect(loader.getPlugin('ext-new')).toBeDefined();
+ expect(loader.getPlugin('ext-legacy')).toBeDefined();
+ });
+
+ it('keeps the copy in the configured dir when the same plugin exists in both, without marking it ERROR', () => {
+ installAt(path.join(tmpDir, 'data', 'plugins'), 'ext-both');
+ installAt(path.join(tmpDir, 'plugins'), 'ext-both');
+
+ const { loader, storage } = boot();
+
+ expect(loader.getPlugin('ext-both')).toBeDefined();
+ expect(storage.getPluginStatus('ext-both')).toBe(PluginStatus.INSTALLED);
+ });
+
+ it('honors an explicit PLUGINS_DIR over both the default and the legacy fallback', () => {
+ const custom = path.join(tmpDir, 'custom-plugins');
+ process.env.PLUGINS_DIR = custom;
+ installAt(custom, 'ext-custom');
+ installAt(path.join(tmpDir, 'data', 'plugins'), 'ext-data');
+ installAt(path.join(tmpDir, 'plugins'), 'ext-legacy');
+
+ const { loader, warn } = boot();
+
+ expect(loader.getPlugin('ext-custom')).toBeDefined();
+ expect(loader.getPlugin('ext-data')).toBeUndefined();
+ expect(loader.getPlugin('ext-legacy')).toBeUndefined();
+ expect(warningsMatching(warn, 'plugins_legacy_dir')).toHaveLength(0);
+ });
+
+ it('ignores a legacy directory that holds no loadable plugin package', () => {
+ // <dataDir>/plugins/<id> doubles as the plugin's ctx.storage dir, so "a directory exists" says
+ // nothing about whether code is there — only a manifest does.
+ fs.mkdirSync(path.join(tmpDir, 'plugins', 'ext-storage-only'), { recursive: true });
+ fs.writeFileSync(path.join(tmpDir, 'plugins', 'ext-storage-only', 'key-abc.json'), '{}');
+
+ const { warn } = boot();
+
+ expect(warningsMatching(warn, 'plugins_legacy_dir')).toHaveLength(0);
+ });
+
+ it('warns when the registry holds installed plugins whose code is not there', () => {
+ // A host whose plugin code was destroyed with the container layer: the entry (config, secrets,
+ // enabledByOperator) survived on the volume, the code did not.
+ const config = new ConfigService(configuration());
+ const seed = new PluginStorageService(config);
+ seed.setPluginEntry({
+ id: 'ext-gone',
+ type: PluginType.EXTENSION,
+ name: 'Ext Gone',
+ version: '1.0.0',
+ status: PluginStatus.INSTALLED,
+ config: {},
+ builtIn: false,
+ installedAt: new Date(),
+ updatedAt: new Date(),
+ });
+
+ const { warn } = boot();
+
+ const [message, context] = warningsMatching(warn, 'plugin_registry_without_code')[0];
+ expect(message).toContain('ext-gone');
+ expect(context?.count).toBe(1);
+ expect(context?.pluginsDir).toContain(path.join('data', 'plugins'));
+ });
+
+ it('warns when the plugins directory does not exist at all but the registry has entries', () => {
+ const custom = path.join(tmpDir, 'never-created');
+ process.env.PLUGINS_DIR = custom;
+ const seed = new PluginStorageService(new ConfigService(configuration()));
+ seed.setPluginEntry({
+ id: 'ext-gone',
+ type: PluginType.EXTENSION,
+ name: 'Ext Gone',
+ version: '1.0.0',
+ status: PluginStatus.INSTALLED,
+ config: {},
+ builtIn: false,
+ installedAt: new Date(),
+ updatedAt: new Date(),
+ });
+
+ const { warn } = boot();
+
+ const [message] = warningsMatching(warn, 'plugin_registry_without_code')[0];
+ expect(message).toContain(custom);
+ expect(message).toContain('does not exist');
+ });
+
+ it('stays quiet on a genuinely empty install and for built-ins, which never have a package dir', () => {
+ const seed = new PluginStorageService(new ConfigService(configuration()));
+ seed.setPluginEntry({
+ id: 'whatsapp-web.js',
+ type: PluginType.ENGINE,
+ name: 'whatsapp-web.js',
+ version: '1.0.0',
+ status: PluginStatus.INSTALLED,
+ config: {},
+ builtIn: true,
+ installedAt: new Date(),
+ updatedAt: new Date(),
+ });
+
+ const { warn } = boot();
+
+ expect(warningsMatching(warn, 'plugin_registry_without_code')).toHaveLength(0);
+ expect(warningsMatching(warn, 'plugins_legacy_dir')).toHaveLength(0);
+ });
+
+ it("does not report a built-in's storage directory as a stray non-plugin directory", () => {
+ // <dataDir>/plugins/<id> is also where ctx.storage writes, so a built-in engine that persists
+ // anything gets a manifest-less directory here on every healthy boot. That must not read like a
+ // fault, and must not look the same as an installed plugin whose code is gone.
+ const seed = new PluginStorageService(new ConfigService(configuration()));
+ seed.setPluginEntry({
+ id: 'whatsapp-web.js',
+ type: PluginType.ENGINE,
+ name: 'whatsapp-web.js',
+ version: '1.0.0',
+ status: PluginStatus.INSTALLED,
+ config: {},
+ builtIn: true,
+ installedAt: new Date(),
+ updatedAt: new Date(),
+ });
+ fs.mkdirSync(path.join(tmpDir, 'data', 'plugins', 'whatsapp-web.js'), { recursive: true });
+
+ const { warn } = boot();
+
+ expect(warningsMatching(warn, 'manifest_missing')).toHaveLength(0);
+ });
+
+ it('reports an installed plugin whose storage survived but whose code is gone', () => {
+ const seed = new PluginStorageService(new ConfigService(configuration()));
+ seed.setPluginEntry({
+ id: 'ext-gone',
+ type: PluginType.EXTENSION,
+ name: 'Ext Gone',
+ version: '1.0.0',
+ status: PluginStatus.INSTALLED,
+ config: {},
+ builtIn: false,
+ installedAt: new Date(),
+ updatedAt: new Date(),
+ });
+ const dataOnly = path.join(tmpDir, 'data', 'plugins', 'ext-gone');
+ fs.mkdirSync(dataOnly, { recursive: true });
+ fs.writeFileSync(path.join(dataOnly, 'key-abc.json'), '{}');
+
+ const { warn } = boot();
+
+ const [message] = warningsMatching(warn, 'plugin_code_missing')[0];
+ expect(message).toContain('ext-gone');
+ // The state is intact — the operator needs to know reinstalling is safe, not assume data loss.
+ expect(message).toMatch(/config|data/i);
+ });
+});
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.ts
index 8f57dc604..5f64d1490 100644
--- a/src/core/plugins/plugin-loader.service.ts
+++ b/src/core/plugins/plugin-loader.service.ts
@@ -4,6 +4,7 @@ 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, HookEvent, KNOWN_HOOK_EVENTS, isKnownHookEvent } from '../hooks';
import {
@@ -135,6 +136,28 @@ export function buildSandboxWorkerEnv(source: NodeJS.ProcessEnv = process.env):
// 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;
+ }
+}
+
@Injectable()
export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap, OnModuleDestroy {
private readonly logger = createLogger('PluginLoaderService');
@@ -149,6 +172,12 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
// the start is what makes it hold for a crash or a failed enable, neither of which runs a disable.
private readonly lastSandboxHookError = new Map<string, { event: string; error: string; at: Date }>();
private readonly pluginsDir: string;
+ /**
+ * The package dir OpenWA defaulted to before it moved under <dataDir>. Scanned as a compatibility
+ * fallback so a host that installed plugins there keeps loading them; null when PLUGINS_DIR names a
+ * 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. */
private readonly hostServices: PluginHostServices;
/** Owns the capability surface handed to plugins — permissions, session scope, engine resolution. */
@@ -167,7 +196,10 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
// degrades to identity (no @lid resolution).
@Optional() private readonly lidMappingStore?: LidMappingStoreService,
) {
- this.pluginsDir = this.configService.get<string>('plugins.dir') ?? './plugins';
+ // Same default the `plugins.dir` key is built from, so this fallback cannot drift away from the
+ // tree PluginStorageService keeps the registry and each plugin's ctx.storage in.
+ this.pluginsDir = this.configService.get<string>('plugins.dir') ?? DEFAULT_PLUGINS_DIR;
+ this.legacyPluginsDir = this.configService.get<string>('plugins.legacyDir') ?? null;
this.hostServices = new PluginHostServices(this.moduleRef);
this.capabilities = new PluginCapabilityContext(
this.logger,
@@ -187,10 +219,55 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
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 },
+ );
}
/**
@@ -266,23 +343,65 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap
// 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)) {
- // 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' },
- );
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;
}
diff --git a/src/core/plugins/plugin-storage.service.ts b/src/core/plugins/plugin-storage.service.ts
index 09851bb7f..15163d3a5 100644
--- a/src/core/plugins/plugin-storage.service.ts
+++ b/src/core/plugins/plugin-storage.service.ts
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as fs from 'fs';
import * as path from 'path';
+import { DEFAULT_DATA_DIR } from '../../config/configuration';
import { createLogger } from '../../common/services/logger.service';
import { isPathWithin, isSafeStorageKey } from '../../common/utils/path-safety';
import { PluginStatus, PluginStorage, PluginRegistryEntry } from './plugin.interfaces';
@@ -68,7 +69,9 @@ export class PluginStorageService {
private registry: Map<string, PluginRegistryEntry> = new Map();
constructor(private readonly configService: ConfigService) {
- this.dataDir = this.configService.get<string>('dataDir') ?? './data';
+ // Same constant the `dataDir` key is built from, so this fallback (hit only by a ConfigService
+ // that carries no app config, e.g. in unit tests) can never drift from the configured value.
+ this.dataDir = this.configService.get<string>('dataDir') ?? DEFAULT_DATA_DIR;
this.registryPath = path.join(this.dataDir, 'plugins', 'registry.json');
this.maxPluginStorageBytes =
this.configService.get<number>('plugins.storageMaxBytes') ?? DEFAULT_MAX_PLUGIN_STORAGE_BYTES;