Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): purge both engines' auth dirs when a session is deleted (#928)

Yudhi Armyndharis5f9efe3b0785
diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.ts
index b58f63357..96d8d8f70 100644
--- a/src/engine/engine.factory.spec.ts
+++ b/src/engine/engine.factory.spec.ts
@@ -138,62 +138,73 @@ describe('EngineFactory', () => {
fs.rmSync(tmpRoot, { recursive: true, force: true });
});
- it('removes the whatsapp-web.js LocalAuth dir (session-<name> under sessionDataPath)', async () => {
+ // Both auth-dir shapes live under tmpRoot so the tests are hermetic regardless of CWD.
+ const buildBothDirFactory = (engineType: string) => {
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 authDir = path.join(tmpRoot, 'baileys');
const factory = new EngineFactory(
- buildConfigService({ 'engine.type': 'whatsapp-web.js', 'engine.sessionDataPath': sessionDataPath }),
+ buildConfigService({
+ 'engine.type': engineType,
+ 'engine.sessionDataPath': sessionDataPath,
+ 'engine.baileys.authDir': authDir,
+ }),
noPluginLoader(),
buildMessageStore(),
buildLidStore(),
);
- await factory.purgeSessionData('alice');
+ return { factory, wwjsDir: path.join(sessionDataPath, 'session-alice'), baileysDir: path.join(authDir, 'alice') };
+ };
- expect(fs.existsSync(dir)).toBe(false);
- });
+ it.each(['whatsapp-web.js', 'baileys'])(
+ "removes BOTH engines' auth dirs when the active engine is %s (engine-switch residue)",
+ async engineType => {
+ const { factory, wwjsDir, baileysDir } = buildBothDirFactory(engineType);
+ fs.mkdirSync(wwjsDir, { recursive: true });
+ fs.mkdirSync(baileysDir, { recursive: true });
+ fs.writeFileSync(path.join(wwjsDir, 'creds.json'), '{}');
+ fs.writeFileSync(path.join(baileysDir, 'creds.json'), '{}');
- 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'), '{}');
+ await factory.purgeSessionData('alice');
- const factory = new EngineFactory(
- buildConfigService({ 'engine.type': 'baileys', 'engine.baileys.authDir': authDir }),
- noPluginLoader(),
- buildMessageStore(),
- buildLidStore(),
- );
- await factory.purgeSessionData('bob');
+ expect(fs.existsSync(wwjsDir)).toBe(false);
+ expect(fs.existsSync(baileysDir)).toBe(false);
+ },
+ );
- expect(fs.existsSync(dir)).toBe(false);
+ it('still purges the other engine dir (and resolves) when one rm fails', async () => {
+ const { factory, wwjsDir, baileysDir } = buildBothDirFactory('baileys');
+ fs.mkdirSync(wwjsDir, { recursive: true });
+ fs.mkdirSync(baileysDir, { recursive: true });
+
+ const realRm = fs.promises.rm.bind(fs.promises);
+ const spy = jest
+ .spyOn(fs.promises, 'rm')
+ .mockImplementation(async (...args: Parameters<typeof fs.promises.rm>) => {
+ if (String(args[0]) === baileysDir) throw new Error('EIO: simulated disk failure');
+ return realRm(...args);
+ });
+ try {
+ await expect(factory.purgeSessionData('alice')).resolves.toBeUndefined();
+ } finally {
+ spy.mockRestore();
+ }
+
+ // The healthy engine's purge still ran; the failed one is left behind (logged, never thrown).
+ expect(fs.existsSync(wwjsDir)).toBe(false);
+ expect(fs.existsSync(baileysDir)).toBe(true);
});
- 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(),
- );
+ it('is a no-op (no throw) when neither auth dir exists', async () => {
+ const { factory } = buildBothDirFactory('baileys');
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(),
- );
+ const { factory } = buildBothDirFactory('baileys');
await factory.purgeSessionData('../baileys-evil');
expect(fs.existsSync(sibling)).toBe(true);
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index 1038c62b6..57a2b93dc 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -13,7 +13,7 @@ import { LidMappingStoreService } from './identity/lid-mapping-store.service';
import { isSafeSessionName } from '../common/utils/path-safety';
export interface EngineCreateOptions {
- /** Session NAME — the on-disk auth-directory key (matches purgeSessionData/sessionAuthDir). */
+ /** Session NAME — the on-disk auth-directory key (matches the dirs purgeSessionData removes). */
sessionId: string;
/** Session UUID (Session.id) — the DB-row key for FK-bound stores (e.g. baileys_stored_messages). */
dbSessionId: string;
@@ -127,14 +127,24 @@ export class EngineFactory implements OnModuleInit {
}
/**
- * 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
+ * Remove a session's persistent on-disk auth/store directories 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.
+ * frequently not even loaded (a stopped session has none), so the paths are derived from config
+ * here rather than from a live adapter; otherwise recreating a session under the same name would
+ * reload a stale store.
+ *
+ * BOTH engine shapes are purged, not just the active engine's: ENGINE_TYPE is a deploy-level
+ * switch, so a session that ever ran under both engines leaves a live auth dir for each, and
+ * removing only the active engine's would strand the other's WhatsApp credentials on disk after
+ * "delete" — able to silently re-link if the engine is ever switched back (and carried into
+ * backups). Each rm is isolated best-effort: an unsafe name is refused up front, and one engine's
+ * rm failure is logged per-engine — it neither fails the delete nor skips the other engine's purge.
+ *
+ * Note: session START deliberately does NOT purge the inactive engine's residue. An operator
+ * trialling the other engine keeps the previous engine's link so switching back doesn't force a
+ * re-pair; the residue is removed only when the session itself is deleted.
*/
async purgeSessionData(sessionName: string): Promise<void> {
if (!isSafeSessionName(sessionName)) {
@@ -145,35 +155,45 @@ export class EngineFactory implements OnModuleInit {
});
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),
- });
+ const dirs: Array<{ engine: string; dir: string }> = [
+ { engine: 'whatsapp-web.js', dir: this.wwjsAuthDir(sessionName) },
+ { engine: 'baileys', dir: this.baileysAuthDir(sessionName) },
+ ];
+ for (const { engine, dir } of dirs) {
+ try {
+ await fs.promises.rm(dir, { recursive: true, force: true });
+ this.logger.log('Purged session auth directory', { action: 'engine_purge', engine, sessionName, dir });
+ } catch (error) {
+ this.logger.warn('Failed to purge session auth directory', {
+ action: 'engine_purge_failed',
+ engine,
+ 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
+ * The on-disk auth directory whatsapp-web.js keeps for `sessionName`, matching exactly what the
+ * adapter constructs: sessionDataPath resolved, then `session-${name}` appended (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);
- }
+ private wwjsAuthDir(sessionName: string): string {
const sessionDataPath = this.configService.get<string>('engine.sessionDataPath') ?? './data/sessions';
return path.join(path.resolve(sessionDataPath), `session-${sessionName}`);
}
+ /**
+ * The on-disk auth directory baileys keeps for `sessionName`: `path.join(authDir, name)`, with
+ * authDir left unresolved, as the adapter does.
+ */
+ private baileysAuthDir(sessionName: string): string {
+ const authDir = this.configService.get<string>('engine.baileys.authDir') ?? './data/baileys';
+ return path.join(authDir, 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.ts
index 229bd90ad..9af293027 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -237,7 +237,7 @@ 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 () => {
+ it('delete() purges the on-disk auth dirs (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' }),
);
@@ -248,6 +248,23 @@ describe('SessionService', () => {
expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
});
+ it('delete() delegates the both-engines purge exactly once, after the DB rows are removed', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ createMockSession({ id: 'sess-uuid-1', name: 'test-session' }),
+ );
+
+ await expect(service.delete('sess-uuid-1')).resolves.toBeUndefined();
+
+ // The factory owns the per-engine best-effort isolation (covered in engine.factory.spec);
+ // the service hands it the session NAME once, only after the DB removal has committed.
+ expect(dataSource.transaction).toHaveBeenCalled();
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledTimes(1);
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('test-session');
+ const txOrder = (dataSource.transaction as jest.Mock).mock.invocationCallOrder[0];
+ const purgeOrder = (engineFactory.purgeSessionData as jest.Mock).mock.invocationCallOrder[0];
+ expect(txOrder).toBeLessThan(purgeOrder);
+ });
+
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' }),
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index e7f620eed..cae508d44 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -535,10 +535,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
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.
+ // Purge the persistent on-disk auth/store dirs — BOTH engine shapes (see EngineFactory), since
+ // an engine switch may have left a live link for the other engine behind. They're keyed by
+ // session NAME and live independently of the (now torn-down, and on delete often never-loaded)
+ // engine instance, so the teardown above doesn't touch them. 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.