Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): keep containment and the conflict answer while merging an install
Yudhi Armyndharisec3a08080b8d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d53cab32..cb6c74989 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,16 +21,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The group-list and status routes no longer appear twice in the OpenAPI contract under different path-parameter names, so a client generated from it gets one method per endpoint; the parameters are now `sessionId` and `id`. The URLs themselves are unchanged.- A bare `@SkipThrottle()` no longer leaves a route throttled: it writes one metadata key the guard never read, so `/api/metrics` and the `/api/health*` probes were rate-limited despite being documented as exempt, and a 429 on readiness reads as unhealthy to every configured probe. Those four routes are also `@Public()`, so the global IP limit was the only one reaching them and they now carry none — rate-limit them at your proxy if they are internet-facing.- The chat-media retention purge and orphan sweep now run while `CHAT_MEDIA_ARCHIVE_ENABLED` is off; previously turning archiving off stopped both, leaving files past their TTL and crash-leftover orphans in the store indefinitely. Note the consequence for a deployment that has archiving off: the orphan sweep now deletes any file under the `chat-media/` prefix that no message row references, once it has been unreferenced for the grace window (`CHAT_MEDIA_ORPHAN_GRACE_MS`, default 1h). A file a surviving row points at is never touched.+- 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`.### 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.- `.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/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex d13980b84..89db33d73 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -749,6 +749,52 @@ describe('PluginsService — recovering a plugin whose code went missing', () =>expect(() => service.install({ buffer: pkg() })).toThrow(ConflictException);});+ it('refuses a plugin path that is a symlink escaping the plugins directory', () => {+ // `existsSync` follows symlinks, so the unconditional guard this replaced happened to refuse+ // this too. Narrowing it to registry-owned directories must not hand the reinstall a path that+ // resolves outside the plugins dir: every write below goes through the link, and so does the+ // rollback's delete.+ const outside = path.join(tmpDir, 'outside');+ fs.mkdirSync(outside, { recursive: true });+ fs.writeFileSync(path.join(outside, 'manifest.json'), 'victim');+ const { service, storage } = orphan();+ fs.rmSync(path.join(pluginsDir, 'svc-plg'), { recursive: true, force: true });+ fs.symlinkSync(outside, path.join(pluginsDir, 'svc-plg'));+ expect(storage.getPluginEntry('svc-plg')).toBeDefined();++ expect(() => service.install({ buffer: pkg() })).toThrow(ConflictException);++ expect(fs.readFileSync(path.join(outside, 'manifest.json'), 'utf8')).toBe('victim');+ });++ it('does not delete a file the failed install never got as far as writing', () => {+ // The rollback removes what this install wrote. Removing every entry path instead would reach+ // files the write never reached — the previous version's, still sitting in a directory the+ // reinstall was supposed to leave intact.+ const { service } = orphan();+ fs.writeFileSync(path.join(pluginsDir, 'svc-plg', 'index.js'), 'previous version');+ // Fail the very first write, so the install has written nothing: every entry path still holds+ // whatever was there before, and the rollback must leave all of it alone.+ const write = jest.spyOn(fs, 'writeFileSync').mockImplementationOnce(() => {+ throw new Error('disk full');+ });++ expect(() => service.install({ buffer: pkg() })).toThrow(BadRequestException);++ expect(fs.readFileSync(path.join(pluginsDir, 'svc-plg', 'index.js'), 'utf8')).toBe('previous version');+ write.mockRestore();+ });++ it('answers a conflict, not a crash, when a package entry path is occupied by a directory', () => {+ // The write fails with EISDIR, and the rollback's `rmSync(..., { force: true })` fails the same+ // way — `force` suppresses ENOENT, not EISDIR — so without care the second throw escapes the+ // catch entirely and the route answers 500 where it used to answer 409.+ const { service } = orphan();+ fs.mkdirSync(path.join(pluginsDir, 'svc-plg', 'manifest.json'), { recursive: true });++ 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);diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 51e31b69c..7ad2b9114 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -313,31 +313,52 @@ export class PluginsService {if (this.pluginLoader.getPlugin(manifest.id)) {throw new ConflictException(`Plugin "${manifest.id}" is already installed`);}- const dir = path.join(this.pluginLoader.getPluginsDir(), manifest.id);+ const pluginsDir = this.pluginLoader.getPluginsDir();+ const dir = path.join(pluginsDir, manifest.id);// 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`);+ if (dirExisted) {+ if (!this.pluginLoader.getRegistryEntry(manifest.id)) {+ throw new ConflictException(`A plugin directory "${manifest.id}" already exists`);+ }+ // `existsSync` answers for the link's TARGET, so narrowing the guard above must not also+ // narrow containment: a link planted at this path would send every write below — and the+ // rollback's delete — wherever it points.+ if (fs.realpathSync(dir) !== path.join(fs.realpathSync(pluginsDir), manifest.id)) {+ throw new ConflictException(`A plugin directory "${manifest.id}" already exists`);+ }+ // Merging into a pre-existing directory means an entry path can already be occupied by a+ // directory. Refusing here keeps that a conflict; writing into it fails with EISDIR, which+ // the rollback below cannot clean up either.+ for (const entry of entries) {+ const dest = path.join(dir, entry.relPath);+ if (fs.existsSync(dest) && fs.statSync(dest).isDirectory()) {+ throw new ConflictException(`Cannot install "${manifest.id}": "${entry.relPath}" is a directory`);+ }+ }}// 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.+ // files this install actually 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.+ const written: string[] = [];try {for (const entry of entries) {const dest = path.join(dir, entry.relPath);fs.mkdirSync(path.dirname(dest), { recursive: true });fs.writeFileSync(dest, entry.data);+ written.push(dest);}this.pluginLoader.loadPlugin(dir);} catch (error) {if (dirExisted) {- for (const entry of entries) fs.rmSync(path.join(dir, entry.relPath), { force: true });+ for (const dest of written) fs.rmSync(dest, { force: true });} else {fs.rmSync(dir, { recursive: true, force: true });}