Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): act on the directory a plugin was loaded from
Yudhi Armyndharisfd1cb8d49ac4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eeaa3f780..e39057ad8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,6 +44,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `POST /sessions/:id/pairing-code` answers `409` while a whatsapp-web.js session is still starting up, instead of a `500` carrying a raw `TypeError`. The engine stored its client before launching Chromium, so for the whole launch — seconds on a modest host — the route passed its only guard and reached into a browser page that did not exist yet. Requesting a code straight after `POST /start`, which is what the dashboard's linking modal invites, landed in exactly that window. The request is now accepted only once the session reaches `qr_ready`, the state the pairing flow needs anyway.- A burst of inbound media messages no longer loses the media of everything past the eighth. The Baileys adapter capped the download queue at its active slots, and an upsert is submitted in one synchronous pass, so admission was a constant 8 whatever the batch size — a 40-message upsert arrived with 32 of its files replaced by an omitted-media marker. The queue is now unbounded and a burst parks instead of shedding; the concurrent-download bound is unchanged.+- A plugin loaded from the legacy plugins directory can be enabled, uninstalled and updated like any other. The loader scans that directory in addition to the configured one, but recorded nothing about where each package came from, so every later operation built its path as `<plugins.dir>/<id>`: enabling failed with a missing entry file and left the plugin in `ERROR`, uninstalling deleted the storage directory and reported success while the code stayed on disk and reloaded on the next boot, updating renamed a directory that was not there, and the config UI answered `404`. Each plugin now carries the directory it was loaded from, and installing still writes to the configured one.+### Security- An advisory usage-statistics write no longer persists the whole API-key row. A key deleted while a request that had already loaded it was in flight was re-inserted with its original hash and authenticated again; a revocation or a narrowing of role, allowlist, IP allowlist or expiry was likewise reverted to the values that request loaded. The write is now scoped to the two usage columns and affects nothing if the row is gone.diff --git a/src/core/plugins/plugin-legacy-dir.spec.ts b/src/core/plugins/plugin-legacy-dir.spec.tsnew file mode 100644index 000000000..85cda76a5--- /dev/null+++ b/src/core/plugins/plugin-legacy-dir.spec.ts@@ -0,0 +1,127 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { ConfigService } from '@nestjs/config';+import { ModuleRef } from '@nestjs/core';+import { PluginLoaderService } from './plugin-loader.service';+import { PluginStorageService } from './plugin-storage.service';+import { HookManager } from '../hooks';+import { PluginStatus, PluginType, type PluginManifest } from './plugin.interfaces';+import type { PluginWorkerHost } from './sandbox/plugin-worker-host';++/**+ * The loader scans the legacy plugins directory in addition to the configured one, so a host that+ * has not migrated keeps its plugins. What it did not record was WHICH directory each package came+ * from, and every later write against the package assumed the configured one — so a plugin loaded+ * from the legacy tree could be listed and reported as loaded, but not enabled, uninstalled or+ * updated. Nothing here had test coverage, which is why all four went unnoticed.+ */++const manifest: PluginManifest = {+ id: 'legacy-plg',+ name: 'Legacy Plugin',+ version: '1.0.0',+ type: PluginType.EXTENSION,+ main: 'index.js',+};++describe('PluginLoaderService — a plugin loaded from the legacy plugins directory', () => {+ let tmpDir: string;+ let configuredDir: string;+ let legacyDir: string;+ let config: ConfigService;+ let storage: PluginStorageService;+ let loader: LoaderWithFakeSandbox;++ /** Records what enableSandboxed asked the worker to require, and requires it for real. */+ const loadedMainPaths: string[] = [];++ class LoaderWithFakeSandbox extends PluginLoaderService {+ protected createSandboxHost(): PluginWorkerHost {+ return {+ load: (mainPath: string) => {+ loadedMainPaths.push(mainPath);+ // Exactly what sandbox/worker-bootstrap.ts does on a 'load' message. A path in the wrong+ // tree fails here with MODULE_NOT_FOUND, which is the defect's observable outcome.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ require(mainPath);+ return Promise.resolve();+ },+ runLifecycle: () => Promise.resolve(),+ terminate: () => Promise.resolve(),+ } as unknown as PluginWorkerHost;+ }+ }++ const makeLoader = (): LoaderWithFakeSandbox =>+ new LoaderWithFakeSandbox(config, new HookManager(), storage, {} as unknown as ModuleRef);++ beforeEach(() => {+ loadedMainPaths.length = 0;+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-legacy-dir-'));+ configuredDir = path.join(tmpDir, 'data', 'plugins');+ legacyDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(configuredDir, { recursive: true });++ // The package sits ONLY in the legacy tree — the shape of a host whose plugins predate the move.+ const pkg = path.join(legacyDir, manifest.id);+ fs.mkdirSync(pkg, { recursive: true });+ fs.writeFileSync(path.join(pkg, 'manifest.json'), JSON.stringify(manifest));+ fs.writeFileSync(path.join(pkg, 'index.js'), 'module.exports = class {};');++ config = {+ get: (k: string) =>+ ({ dataDir: path.join(tmpDir, 'data'), 'plugins.dir': configuredDir, 'plugins.legacyDir': legacyDir })[k],+ } as unknown as ConfigService;+ storage = new PluginStorageService(config);+ loader = makeLoader();+ loader.onModuleInit();+ });++ afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ });++ it('is loaded from the legacy directory in the first place', () => {+ expect(loader.getPlugin(manifest.id)).toBeDefined();+ });++ it('enables, requiring its entry from the tree it was loaded from', async () => {+ await loader.enablePlugin(manifest.id);++ expect(loader.getPlugin(manifest.id)?.status).toBe(PluginStatus.ENABLED);+ expect(loadedMainPaths).toEqual([path.join(legacyDir, manifest.id, 'index.js')]);+ });++ it('uninstalls the package itself, so it does not come back on the next boot', async () => {+ await loader.uninstallPlugin(manifest.id);++ expect(fs.existsSync(path.join(legacyDir, manifest.id))).toBe(false);++ // The real proof: a fresh loader over the same directories must find nothing to load. Deleting+ // the wrong tree left the package in place and the plugin reappeared, having reported success.+ const next = makeLoader();+ next.onModuleInit();+ expect(next.getPlugin(manifest.id)).toBeUndefined();+ });++ it('resolves its package directory to the legacy tree', () => {+ expect(loader.getPluginPackageDir(manifest.id)).toBe(path.resolve(legacyDir, manifest.id));+ });++ // The counterpart: nothing above may change where an ordinary plugin resolves to, and an id that+ // is not loaded still falls back to the configured directory, which is what a fresh install wants.+ it('leaves a plugin in the configured directory, and an unknown id, resolving as before', () => {+ const other: PluginManifest = { ...manifest, id: 'configured-plg' };+ const pkg = path.join(configuredDir, other.id);+ fs.mkdirSync(pkg, { recursive: true });+ fs.writeFileSync(path.join(pkg, 'manifest.json'), JSON.stringify(other));+ fs.writeFileSync(path.join(pkg, 'index.js'), 'module.exports = class {};');++ const fresh = makeLoader();+ fresh.onModuleInit();++ expect(fresh.getPluginPackageDir(other.id)).toBe(path.resolve(configuredDir, other.id));+ expect(fresh.getPluginPackageDir('never-installed')).toBe(path.join(configuredDir, 'never-installed'));+ });+});diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 1f61a85ef..c340fd924 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -68,6 +68,16 @@ export function resolvePluginMainPath(pluginsDir: string, pluginId: string, mainreturn 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@@ -542,6 +552,10 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapbuiltIn: 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);@@ -772,6 +786,25 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapreturn this.pluginsDir;}+ /**+ * Absolute path of a plugin's own package directory — the tree its code was loaded from.+ *+ * Every operation that acts on the package (enable, uninstall, update, config UI) must use this+ * rather than <plugins.dir>/<id>: the loader also scans the legacy plugins directory, so those are+ * not the same path for a plugin a host has not migrated yet. Falls back to the configured+ * location for an id that is not loaded, which is what a fresh install wants.+ */+ getPluginPackageDir(pluginId: string): string {+ 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;@@ -787,15 +820,21 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapthrow 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);- // Delete the plugin's directory, guarding against a traversal id escaping the plugins dir.- const base = path.resolve(this.pluginsDir);- const dir = path.resolve(base, pluginId);- if (dir !== base && dir.startsWith(base + path.sep) && fs.existsSync(dir)) {+ // 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 });}@@ -947,6 +986,9 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapif (!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-importsconst pluginModule = require(mainPath) as { default?: new () => IPlugin };diff --git a/src/core/plugins/plugin-sandbox-bridge.ts b/src/core/plugins/plugin-sandbox-bridge.tsindex 0f353e68b..71780ec4e 100644--- a/src/core/plugins/plugin-sandbox-bridge.ts+++ b/src/core/plugins/plugin-sandbox-bridge.ts@@ -1,3 +1,4 @@+import * as path from 'path';import { ConfigService } from '@nestjs/config';import { createLogger } from '../../common/services/logger.service';import { HookManager, HookEvent, KNOWN_HOOK_EVENTS, isKnownHookEvent } from '../hooks';@@ -224,7 +225,15 @@ export class PluginSandboxBridge {// than repeated on each way a generation can end.this.lastSandboxHookError.delete(pluginId);// Containment guard: reject a manifest.main that escapes the plugin dir.- const mainPath = this.resolvePluginMainPath(this.pluginsDir, pluginId, plugin.manifest.main);+ // Anchored to the directory the package was loaded from, which is not necessarily+ // <plugins.dir>/<id>: the loader also scans the legacy plugins directory, and the worker's+ // require() of a path in the wrong tree fails with MODULE_NOT_FOUND.+ const packageDir = plugin.packageDir ?? path.join(this.pluginsDir, pluginId);+ const mainPath = this.resolvePluginMainPath(+ path.dirname(packageDir),+ path.basename(packageDir),+ plugin.manifest.main,+ );// The capability dispatcher runs a worker request through the SAME context an in-process plugin// gets, so permission + session-scope checks (assertPermission / assertSessionActive) apply// identically. The worker can only ask; the host is the gatekeeper.diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex 6823b92b5..651c8ce31 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -615,6 +615,12 @@ export interface PluginInstance {// First-party built-ins (engines, bundled extensions) run in-process; plugins loaded from the// plugins directory are untrusted and run sandboxed in a worker. `false` => sandboxed.builtIn?: boolean;+ // Absolute path of the directory this plugin's package was loaded from. Usually+ // <plugins.dir>/<id>, but the loader also scans the legacy plugins directory, and every later+ // operation on the package — enable, uninstall, update, config UI — has to act on the tree the+ // code actually came from rather than assume the configured one. Absent for built-ins, which are+ // registered programmatically and have no on-disk package.+ packageDir?: string;}// ============================================================================diff --git a/src/modules/plugins/plugins-legacy-dir.spec.ts b/src/modules/plugins/plugins-legacy-dir.spec.tsnew file mode 100644index 000000000..0f830c7ac--- /dev/null+++ b/src/modules/plugins/plugins-legacy-dir.spec.ts@@ -0,0 +1,93 @@+import AdmZip from 'adm-zip';+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';+import { ConfigService } from '@nestjs/config';+import { ModuleRef } from '@nestjs/core';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { PluginStorageService } from '../../core/plugins/plugin-storage.service';+import { HookManager } from '../../core/hooks';+import { PluginType, type PluginManifest } from '../../core/plugins/plugin.interfaces';+import { PluginsService } from './plugins.service';++/**+ * The service half of the same defect: a package the loader found in the legacy plugins directory+ * had its config UI read, and its in-place update staged, under the CONFIGURED directory — where it+ * is not. The config UI answered 404; the update renamed a directory that did not exist, after+ * unloadPlugin had already dropped the plugin from the runtime.+ */++const manifest: PluginManifest = {+ id: 'legacy-plg',+ name: 'Legacy Plugin',+ version: '1.0.0',+ type: PluginType.EXTENSION,+ main: 'index.js',+ configUi: { entry: 'ui.html' },+};++const zipOf = (files: Record<string, string>): Buffer => {+ const z = new AdmZip();+ for (const [name, content] of Object.entries(files)) z.addFile(name, Buffer.from(content));+ return z.toBuffer();+};++describe('PluginsService — a plugin loaded from the legacy plugins directory', () => {+ let tmpDir: string;+ let configuredDir: string;+ let legacyDir: string;+ let loader: PluginLoaderService;+ let service: PluginsService;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-legacy-svc-'));+ configuredDir = path.join(tmpDir, 'data', 'plugins');+ legacyDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(configuredDir, { recursive: true });++ const pkg = path.join(legacyDir, manifest.id);+ fs.mkdirSync(pkg, { recursive: true });+ fs.writeFileSync(path.join(pkg, 'manifest.json'), JSON.stringify(manifest));+ fs.writeFileSync(path.join(pkg, 'index.js'), 'module.exports = class {};');+ fs.writeFileSync(path.join(pkg, 'ui.html'), '<p>legacy config ui</p>');++ const config = {+ get: (k: string) =>+ ({ dataDir: path.join(tmpDir, 'data'), 'plugins.dir': configuredDir, 'plugins.legacyDir': legacyDir })[k],+ } as unknown as ConfigService;+ loader = new PluginLoaderService(config, new HookManager(), new PluginStorageService(config), {+ the: 'unused',+ } as unknown as ModuleRef);+ loader.onModuleInit();+ service = new PluginsService(loader, config);+ });++ afterEach(() => {+ fs.rmSync(tmpDir, { recursive: true, force: true });+ });++ it('serves its config UI from the tree it was loaded from', () => {+ expect(service.getConfigUiHtml(manifest.id)).toContain('legacy config ui');+ });++ it('updates in place, leaving the new version where the old one was', async () => {+ const next = { ...manifest, version: '2.0.0' };+ await service.updatePackage(+ manifest.id,+ zipOf({+ 'manifest.json': JSON.stringify(next),+ 'index.js': 'module.exports = class {};',+ 'ui.html': '<p>v2 config ui</p>',+ }),+ );++ const onDisk = JSON.parse(+ fs.readFileSync(path.join(legacyDir, manifest.id, 'manifest.json'), 'utf8'),+ ) as PluginManifest;+ expect(onDisk.version).toBe('2.0.0');+ // The update must not have materialised a second copy under the configured root, which would+ // then win the next boot's duplicate-id skip and shadow the tree that was actually updated.+ expect(fs.existsSync(path.join(configuredDir, manifest.id))).toBe(false);+ expect(loader.getPlugin(manifest.id)?.manifest.version).toBe('2.0.0');+ });+});diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 7ad2b9114..5e9787dde 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -2,7 +2,7 @@ import { Injectable, NotFoundException, BadRequestException, ConflictException,import { ConfigService } from '@nestjs/config';import * as fs from 'fs';import * as path from 'path';-import { PluginLoaderService, PluginStatus, resolvePluginMainPath } from '../../core/plugins';+import { PluginLoaderService, PluginStatus, resolvePluginEntryPath } from '../../core/plugins';import { pluginUpdateBackupDirName, pluginUpdateStagingDirName } from '../../core/plugins';import type { PluginConfigSchema } from '../../core/plugins';import { PluginDto } from './dto/plugin.dto';@@ -281,10 +281,12 @@ export class PluginsService {if (!entry || typeof entry !== 'string') {throw new NotFoundException(`Plugin ${id} has no config UI`);}- const base = path.resolve(this.pluginLoader.getPluginsDir(), id);+ // Anchored to the package's own directory: the plugin is loaded by this point, and a package+ // found in the legacy plugins directory does not live under the configured root.+ const base = path.resolve(this.pluginLoader.getPluginPackageDir(id));let file: string;try {- file = resolvePluginMainPath(this.pluginLoader.getPluginsDir(), id, entry);+ file = resolvePluginEntryPath(base, entry);} catch {throw new NotFoundException(`Config UI entry not found for plugin ${id}`);}@@ -468,11 +470,15 @@ export class PluginsService {}const wasEnabled = plugin.status === PluginStatus.ENABLED;- const pluginsDir = this.pluginLoader.getPluginsDir();- const dir = path.join(pluginsDir, id);- // Dot-prefixed siblings inside pluginsDir: same filesystem (so the renames stay EXDEV-safe) but- // skipped by the loader's directory scan, so a crash mid-update can't leave them loaded as a- // duplicate. The loader's boot-time recovery keys off these exact names.+ // The tree the package was loaded from, which is the legacy plugins directory for a host that+ // has not migrated. Updating in the configured root instead renames a directory that is not+ // there, after unloadPlugin has already dropped the plugin from the runtime.+ const dir = this.pluginLoader.getPluginPackageDir(id);+ const pluginsDir = path.dirname(dir);+ // Dot-prefixed siblings inside that same directory: same filesystem (so the renames stay+ // EXDEV-safe) but skipped by the loader's directory scan, so a crash mid-update can't leave them+ // loaded as a duplicate. The loader's boot-time recovery runs per scanned directory and keys off+ // these exact names, so it reconciles the legacy tree too.const backup = path.join(pluginsDir, pluginUpdateBackupDirName(id));const staging = path.join(pluginsDir, pluginUpdateStagingDirName(id));