Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): make a plugin whose code went missing recoverable again
Yudhi Armyndharisf36ff37ff555
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 240d819c6..9d53cab32 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -27,6 +27,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- 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.- `.env.example` no longer ships `ENABLE_SWAGGER=true` uncommented: the template also declares `NODE_ENV=production`, so copying it pinned the opt-in that production withholds and served the schema and running version at `/api/docs`, which sits outside the API-key guard. Bare-metal operators who already copied it should check their own `.env`; Docker and Helm are unaffected.+### Fixed++- A plugin whose code went missing is recoverable through the API again: reinstalling now writes over its surviving `ctx.storage` directory instead of answering `409`, and uninstalling a known-but-unloaded id no longer answers `404`.+## [0.15.0] - 2026-08-09### Addeddiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 24ae88e0d..43511354c 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5525,7 +5525,11 @@ Install a plugin from an uploaded `.zip` package.**Response** `201` — the newly installed `PluginDto`.-**Errors:** `400` no file / invalid package / install failed · `401` · `403` · `409` plugin id or directory already exists+Reinstalling over a plugin whose code went missing is supported and is the recovery the boot warning+prescribes: its `ctx.storage` directory, config, session activations and enabled-on-boot decision are+all kept. A directory the gateway did not install is still refused.++**Errors:** `400` no file / invalid package / install failed · `401` · `403` · `409` plugin already loaded, or a directory under that id the gateway did not install---@@ -5724,7 +5728,7 @@ Update an installed plugin in place from a URL, preserving config + enabled stat#### DELETE /api/plugins/:id-Uninstall a plugin: dispatch its `onUnload` lifecycle hook, delete its files, drop its registry entry, and remove its `ctx.storage` data directory (`<dataDir>/plugins/<id>` — a separate tree when `PLUGINS_DIR` points outside the data dir). Built-in plugins are protected.+Uninstall a plugin: dispatch its `onUnload` lifecycle hook, delete its files, drop its registry entry, and remove its `ctx.storage` data directory (`<dataDir>/plugins/<id>` — a separate tree when `PLUGINS_DIR` points outside the data dir). Built-in plugins are protected. A plugin that is installed but not loaded — one whose code went missing — can be uninstalled too; there is simply no runtime to tear down first. `404` therefore means an id the gateway has no registry entry for.**Auth:** API key (ADMIN)diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex 229d060be..d13980b84 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -14,7 +14,7 @@ import * as os from 'os';import * as path from 'path';import { createHash } from 'crypto';import AdmZip from 'adm-zip';-import { BadRequestException } from '@nestjs/common';+import { BadRequestException, ConflictException, NotFoundException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { PluginsService, isIngressCapable } from './plugins.service';@@ -22,7 +22,7 @@ import { fetchSafeBuffer } from './plugin-download';import { SECRET_SENTINEL } from './redact-config';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { PluginStorageService } from '../../core/plugins/plugin-storage.service';-import { PluginStatus } from '../../core/plugins/plugin.interfaces';+import { PluginStatus, PluginType } from '../../core/plugins/plugin.interfaces';import { HookManager } from '../../core/hooks';const manifest = { id: 'svc-plg', name: 'Svc Plugin', version: '1.0.0', type: 'extension', main: 'index.js' };@@ -644,3 +644,148 @@ describe('PluginsService — disable when the plugin is not loaded', () => {await expect(service.disable('never-installed')).rejects.toThrow(/not found/i);});});++/**+ * Recovery for a plugin the gateway still has a registry entry for but whose code is gone — the+ * state the loader announces on every boot ("Reinstall it — its config and stored data are kept").+ *+ * Under the shipped layout `plugins.dir` IS `<dataDir>/plugins`, so a plugin's package directory and+ * its `ctx.storage` directory are the same path. `ctx.storage` is created eagerly the first time the+ * plugin is enabled, so the directory outlives the package — which is exactly what a container+ * recreate leaves behind when the code lived in the image layer and the data on a volume. Both+ * recovery routes then asked the wrong oracle about it: install read the filesystem (a directory+ * exists, so 409) and uninstall read the runtime map (nothing loaded, so 404), leaving the entry,+ * its config and its secrets unremovable through the API.+ */+describe('PluginsService — recovering a plugin whose code went missing', () => {+ let tmpDir: string;+ let pluginsDir: string;+ let config: ConfigService;++ const build = () => {+ const storage = new PluginStorageService(config);+ const loader = new PluginLoaderService(config, new HookManager(), storage, {} as unknown as ModuleRef);+ return { storage, loader, service: new PluginsService(loader, config) };+ };++ /** Install, leave a `ctx.storage` file behind, then strip the package — the orphan state. */+ function orphan(): ReturnType<typeof build> {+ const first = build();+ first.service.install({ buffer: pkg() });+ first.loader.setOperatorEnabled('svc-plg', true);+ first.storage.setPluginConfig('svc-plg', { token: 'keep-me' });+ fs.writeFileSync(path.join(pluginsDir, 'svc-plg', 'key-abc.json'), '{"lastId":"msg-42"}');++ fs.rmSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'));+ fs.rmSync(path.join(pluginsDir, 'svc-plg', 'index.js'));++ const restarted = build();+ expect(restarted.loader.getPlugin('svc-plg')).toBeUndefined();+ expect(restarted.loader.getRegistryEntry('svc-plg')).toBeDefined();+ return restarted;+ }++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'owa-orphan-'));+ pluginsDir = path.join(tmpDir, 'plugins');+ fs.mkdirSync(pluginsDir, { recursive: true });+ config = {+ get: (k: string) => (k === 'plugins.dir' ? pluginsDir : k === 'dataDir' ? tmpDir : undefined),+ } as unknown as ConfigService;+ });+ afterEach(() => fs.rmSync(tmpDir, { recursive: true, force: true }));++ it('reinstalls over the surviving storage directory, keeping config and stored data', () => {+ const { service, loader, storage } = orphan();++ const dto = service.install({ buffer: pkg() });++ expect(dto.id).toBe('svc-plg');+ expect(loader.getPlugin('svc-plg')).toBeDefined();+ // The two promises the boot warning makes: stored data and config both survive the reinstall.+ expect(fs.readFileSync(path.join(pluginsDir, 'svc-plg', 'key-abc.json'), 'utf8')).toContain('msg-42');+ expect(storage.getPluginConfig('svc-plg')).toEqual({ token: 'keep-me' });+ expect(storage.getPluginEntry('svc-plg')?.enabledByOperator).toBe(true);+ });++ it('uninstalls an orphan, taking the registry entry and the directory with it', async () => {+ const { service, storage } = orphan();++ const res = await service.uninstall('svc-plg');++ expect(res.success).toBe(true);++ expect(storage.getPluginEntry('svc-plg')).toBeUndefined();+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg'))).toBe(false);+ });++ it('does not delete surviving stored data when the reinstall itself fails', () => {+ // Narrowing the install guard turns the rollback into a data-loss path: it used to remove a+ // directory install had just created, and would now remove one holding the operator's data.+ const { service, loader } = orphan();+ jest.spyOn(loader, 'loadPlugin').mockImplementation(() => {+ throw new Error('bad package');+ });++ expect(() => service.install({ buffer: pkg() })).toThrow(BadRequestException);++ expect(fs.readFileSync(path.join(pluginsDir, 'svc-plg', 'key-abc.json'), 'utf8')).toContain('msg-42');+ });++ it('still refuses to install over a directory the gateway does not own', () => {+ const { service } = build();+ fs.mkdirSync(path.join(pluginsDir, 'svc-plg'), { recursive: true });+ fs.writeFileSync(path.join(pluginsDir, 'svc-plg', 'operator-notes.txt'), 'not ours');++ // No registry entry: the gateway never installed this, so merging a package into it would+ // silently adopt whatever is already there.+ expect(() => service.install({ buffer: pkg() })).toThrow(ConflictException);+ });++ it('still refuses a duplicate install of a loaded plugin', () => {+ const { service } = build();+ service.install({ buffer: pkg() });++ expect(() => service.install({ buffer: pkg() })).toThrow(ConflictException);+ });++ it('still throws NotFound when uninstalling an id the gateway has never seen', async () => {+ const { service } = build();+ await expect(service.uninstall('never-installed')).rejects.toThrow(NotFoundException);+ });++ it('refuses to uninstall a built-in whose code is not loaded', async () => {+ const { service, storage } = build();+ storage.setPluginEntry({+ id: 'whatsapp-web.js',+ type: PluginType.ENGINE,+ name: 'WhatsApp Web',+ version: '1.0.0',+ status: PluginStatus.INSTALLED,+ config: {},+ builtIn: true,+ installedAt: new Date(),+ updatedAt: new Date(),+ });++ // Reaching the loader's built-in check is the point: this used to 404 as "unknown id", which+ // docs/06 already described as a 400.+ await expect(service.uninstall('whatsapp-web.js')).rejects.toThrow(BadRequestException);+ expect(storage.getPluginEntry('whatsapp-web.js')).toBeDefined();+ });++ it('merges the new package over the old files rather than replacing the directory', () => {+ // Accepted residual, pinned here so it is a decision rather than a surprise: the directory also+ // holds ctx.storage under the shipped layout, so a reinstall cannot clear it first. A file the+ // previous package version shipped and the new one dropped therefore stays on disk. It is inert+ // — nothing loads a file the manifest does not point at — but it is not cleaned up.+ const first = build();+ first.service.install({ buffer: pkg() });+ fs.writeFileSync(path.join(pluginsDir, 'svc-plg', 'legacy.js'), 'module.exports = {};');+ fs.rmSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'));++ build().service.install({ buffer: pkg({ version: '2.0.0' }) });++ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg', 'legacy.js'))).toBe(true);+ });+});diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 594388a81..51e31b69c 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -314,12 +314,20 @@ export class PluginsService {throw new ConflictException(`Plugin "${manifest.id}" is already installed`);}const dir = path.join(this.pluginLoader.getPluginsDir(), manifest.id);- if (fs.existsSync(dir)) {+ // A surviving directory does not prove a surviving package. Under the shipped layout it is also+ // the plugin's `ctx.storage` root, created the first time the plugin was enabled and left behind+ // when the code goes (a container recreate with the packages in the image layer and the data on+ // a volume). Reinstalling is the recovery the boot warning prescribes, so refuse only a+ // directory the gateway never installed — a loaded plugin is already refused above.+ const dirExisted = fs.existsSync(dir);+ if (dirExisted && !this.pluginLoader.getRegistryEntry(manifest.id)) {throw new ConflictException(`A plugin directory "${manifest.id}" already exists`);}- // Write the validated entries then load; roll back the directory on any failure so a bad- // package never leaves a half-installed plugin behind.+ // Write the validated entries then load; roll back on any failure so a bad package never leaves+ // a half-installed plugin behind. Into a pre-existing directory the rollback removes only the+ // files this install wrote: the directory holds the operator's stored data, and deleting it to+ // undo a failed reinstall would destroy exactly what the reinstall promised to keep.try {for (const entry of entries) {const dest = path.join(dir, entry.relPath);@@ -328,7 +336,11 @@ export class PluginsService {}this.pluginLoader.loadPlugin(dir);} catch (error) {- fs.rmSync(dir, { recursive: true, force: true });+ if (dirExisted) {+ for (const entry of entries) fs.rmSync(path.join(dir, entry.relPath), { force: true });+ } else {+ fs.rmSync(dir, { recursive: true, force: true });+ }if (error instanceof HttpException) throw error;throw new BadRequestException(`Failed to install plugin: ${error instanceof Error ? error.message : String(error)}`,@@ -582,8 +594,11 @@ export class PluginsService {}private async uninstallInner(id: string): Promise<{ success: boolean; message: string }> {- const plugin = this.pluginLoader.getPlugin(id);- if (!plugin) {+ // As in `disable`: not loaded is not unknown. A plugin whose code went missing still owns a+ // registry entry with its config and secrets, and `uninstallPlugin` already tolerates having no+ // runtime to tear down — so removing it is the one recovery left when the package cannot be+ // obtained again. A 404 means only what it should: an id nobody knows.+ if (!this.pluginLoader.getPlugin(id) && !this.pluginLoader.getRegistryEntry(id)) {throw new NotFoundException(`Plugin ${id} not found`);}