Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(session): fully purge on-disk auth directory when deleting a session (#656)
محفوظae9e5c7fa792
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 22a12a2c2..fc3391858 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **A session with auto-reconnect turned off no longer reports "reconnection failed after 0 attempts".** When a disconnect fired with the reconnect budget set to `0` (auto-reconnect disabled), the session was marked `FAILED` with the exhausted-retries message and a count of `0` — implying a retry loop had run and failed rather than a feature that is simply off. That case now records an explicit "Auto-reconnect is disabled" reason; the genuine exhausted-retries message (with its real attempt count) is unchanged.- **A failed inbound integration (ingress) delivery is no longer silently dropped on the inline path.** With the queue disabled (or Redis unreachable), an ingress delivery is dispatched inline; if the plugin handler threw, the error was swallowed and the event was stranded — the provider had already received its `202`, and the redrive tooling only scans the dead-letter table, which never got a row. The inline path now persists a dead-letter record (the same shape the queued path writes on its final failed attempt), so the event is redrivable. The write is best-effort: a failure to persist it is logged but never turns the `202` into a `5xx` (the delivery is already dedup-persisted, so the provider won't re-send).- **Plugin instance session bindings are re-derived on startup, so a binding lost while the plugin was momentarily unloaded self-heals.** Provisioning a plugin instance mirrors its config into the plugin runtime (per-session config + activation) so an ingress handler resolves the right `ctx.config`; if the plugin happened to be unloaded at that moment the bridge was skipped (only an INFO audit), leaving the instance marked enabled but resolving base config only — previously recoverable only by re-saving the instance. A boot-time reconciliation now re-applies every enabled instance's binding from the persisted `plugin_instances` rows (honoring each row's real `enabled` flag), so a restart restores it. The binding logic moved into a dedicated service shared by provisioning and the reconciler.+- **Deleting a session now purges its on-disk engine auth directory.** `DELETE /sessions/:id` tore down the running engine and removed the database rows but left the engine's persistent auth store behind (`data/baileys/<name>` for the Baileys engine, `data/sessions/session-<name>` for whatsapp-web.js) — these are keyed by session **name** and live independently of any engine instance, so recreating a session under the same name reloaded stale credentials. The delete now removes that directory too (best-effort, keyed by name, guarded against path traversal, and correctly a no-op when the session was already stopped and had no live engine). Thanks @m7fz7.## [0.8.10] - 2026-07-07diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.tsindex e75f4ae08..6d2cd7026 100644--- a/src/engine/engine.factory.spec.ts+++ b/src/engine/engine.factory.spec.ts@@ -1,3 +1,6 @@+import * as fs from 'fs';+import * as os from 'os';+import * as path from 'path';import { EngineFactory } from './engine.factory';import { ConfigService } from '@nestjs/config';import { PluginLoaderService, PluginType } from '../core/plugins';@@ -118,4 +121,77 @@ describe('EngineFactory', () => {);expect(() => factory.create({ sessionId: 'sess-b' })).toThrow(/baileys/i);});++ describe('purgeSessionData (delete fully removes on-disk auth, keyed by session name)', () => {+ const noPluginLoader = () => ({ getPlugin: jest.fn() }) as unknown as PluginLoaderService;+ let tmpRoot: string;++ beforeEach(() => {+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'engine-purge-'));+ });+ afterEach(() => {+ fs.rmSync(tmpRoot, { recursive: true, force: true });+ });++ it('removes the whatsapp-web.js LocalAuth dir (session-<name> under sessionDataPath)', async () => {+ const sessionDataPath = path.join(tmpRoot, 'sessions');+ const dir = path.join(sessionDataPath, 'session-alice');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'creds.json'), '{}');++ const factory = new EngineFactory(+ buildConfigService({ 'engine.type': 'whatsapp-web.js', 'engine.sessionDataPath': sessionDataPath }),+ noPluginLoader(),+ buildMessageStore(),+ buildLidStore(),+ );+ await factory.purgeSessionData('alice');++ expect(fs.existsSync(dir)).toBe(false);+ });++ it('removes the baileys auth dir (<authDir>/<name>) when the active engine is baileys', async () => {+ const authDir = path.join(tmpRoot, 'baileys');+ const dir = path.join(authDir, 'bob');+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'creds.json'), '{}');++ const factory = new EngineFactory(+ buildConfigService({ 'engine.type': 'baileys', 'engine.baileys.authDir': authDir }),+ noPluginLoader(),+ buildMessageStore(),+ buildLidStore(),+ );+ await factory.purgeSessionData('bob');++ expect(fs.existsSync(dir)).toBe(false);+ });++ it('is a no-op (no throw) when the auth dir does not exist', async () => {+ const factory = new EngineFactory(+ buildConfigService({ 'engine.type': 'baileys', 'engine.baileys.authDir': path.join(tmpRoot, 'baileys') }),+ noPluginLoader(),+ buildMessageStore(),+ buildLidStore(),+ );+ await expect(factory.purgeSessionData('never-linked')).resolves.toBeUndefined();+ });++ it('refuses to purge an unsafe session name (no rm on a traversal path)', async () => {+ const authDir = path.join(tmpRoot, 'baileys');+ // A sibling that a '../' name would resolve to — it must survive the refused purge.+ const sibling = path.join(tmpRoot, 'baileys-evil');+ fs.mkdirSync(sibling, { recursive: true });++ const factory = new EngineFactory(+ buildConfigService({ 'engine.type': 'baileys', 'engine.baileys.authDir': authDir }),+ noPluginLoader(),+ buildMessageStore(),+ buildLidStore(),+ );+ await factory.purgeSessionData('../baileys-evil');++ expect(fs.existsSync(sibling)).toBe(true);+ });+ });});diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.tsindex 5965f1d6a..8382f996b 100644--- a/src/engine/engine.factory.ts+++ b/src/engine/engine.factory.ts@@ -1,3 +1,5 @@+import * as fs from 'fs';+import * as path from 'path';import { Injectable, OnModuleInit } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';@@ -120,6 +122,54 @@ export class EngineFactory implements OnModuleInit {return this.createFallbackEngine(options);}+ /**+ * Remove a session's persistent on-disk auth/store directory for the active engine, so deleting a+ * session fully purges its footprint. The dir is keyed by session NAME — the same key {@link create}+ * uses (`path.join(authDir, name)` for baileys, `session-${name}` under sessionDataPath for+ * whatsapp-web.js) — and survives independently of any engine instance. On delete the engine is+ * frequently not even loaded (a stopped session has none), so the path is derived from config here+ * rather than from a live adapter; otherwise recreating a session under the same name would reload a+ * stale store. Best-effort: an unsafe name or an rm failure is logged, never thrown, so it can't turn+ * a successful delete into a 500.+ */+ async purgeSessionData(sessionName: string): Promise<void> {+ if (!isSafeSessionName(sessionName)) {+ // Same guard as create(): never let a name with '.', '/' or '\\' reach an rm -rf sink.+ this.logger.warn('Refusing to purge session data for an unsafe session name', {+ action: 'engine_purge_unsafe',+ sessionName: JSON.stringify(sessionName),+ });+ return;+ }+ const dir = this.sessionAuthDir(sessionName);+ try {+ await fs.promises.rm(dir, { recursive: true, force: true });+ this.logger.log('Purged session auth directory', { action: 'engine_purge', sessionName, dir });+ } catch (error) {+ this.logger.warn('Failed to purge session auth directory', {+ action: 'engine_purge_failed',+ sessionName,+ dir,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ }++ /**+ * The on-disk auth directory the active engine keeps for `sessionName`, matching exactly what each+ * adapter constructs: baileys uses `path.join(authDir, name)` (authDir left unresolved, as the+ * adapter does); whatsapp-web.js resolves sessionDataPath and appends `session-${name}` (mirrors+ * WhatsAppWebJsAdapter.clearLocalAuth).+ */+ private sessionAuthDir(sessionName: string): string {+ if (this.engineType === 'baileys') {+ const authDir = this.configService.get<string>('engine.baileys.authDir') ?? './data/baileys';+ return path.join(authDir, sessionName);+ }+ const sessionDataPath = this.configService.get<string>('engine.sessionDataPath') ?? './data/sessions';+ return path.join(path.resolve(sessionDataPath), `session-${sessionName}`);+ }+private isEnginePlugin(instance: unknown): instance is IEnginePlugin {return (typeof instance === 'object' &&diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex b52324828..57a4fabba 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -97,6 +97,7 @@ describe('SessionService', () => {engineFactory = {create: jest.fn().mockReturnValue(mockEngine),+ purgeSessionData: jest.fn().mockResolvedValue(undefined),};eventsGateway = {@@ -193,6 +194,28 @@ describe('SessionService', () => {expect(dataSource.transaction).toHaveBeenCalled(); // DB removal still ran});+ it('delete() purges the engine on-disk auth dir (keyed by session NAME) so a same-name recreate starts clean', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockSession({ id: 'sess-uuid-1', name: 'test-session' }),+ );+ enginesOf().set('sess-uuid-1', { forceDestroy: jest.fn().mockResolvedValue(undefined) });++ await service.delete('sess-uuid-1');++ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');+ });++ it('delete() purges even when no engine is loaded (a stopped session has none)', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockSession({ id: 'sess-uuid-1', name: 'test-session' }),+ );+ // No engine in the map — the common delete case.++ await service.delete('sess-uuid-1');++ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');+ });+it('stop() completes when engine.disconnect() rejects — map reconciled, status updated', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 2cf687445..c4284819d 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -427,6 +427,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatsessionId: id,action: 'delete',});++ // Purge the engine's persistent on-disk auth/store dir. It's keyed by session NAME and lives+ // independently of the (now torn-down, and on delete often never-loaded) engine instance, so the+ // teardown above doesn't touch it. Without this, recreating a session under the same name reloads+ // a stale store. Best-effort inside the factory — never fails an otherwise-successful delete.+ await this.engineFactory.purgeSessionData(session.name);} finally {// Always clear the teardown mark so a later recreate/start with this id isn't suppressed.this.stoppingSessions.delete(id);