Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): guard the delete purge on live session ids, not shape

Yudhi Armyndharis331b6c13a31b
diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.ts
index 7f3f89a6d..2a39df1db 100644
--- a/src/engine/engine.factory.spec.ts
+++ b/src/engine/engine.factory.spec.ts
@@ -328,20 +328,21 @@ describe('EngineFactory', () => {
expect(fs.existsSync(otherSession)).toBe(true);
});
- // A name is free text that passes the session-name rule, so it can be another session's id. The
- // legacy dirs it names are then that other session's live id-keyed credentials.
- it("leaves another session's auth dirs alone when the deleted session is named after its id", async () => {
+ // The shape of a name says nothing about whose login its directory holds: a session named after a
+ // tenant UUID owns it. Whether the name is another session's live id is the caller's to decide
+ // (SessionEngineControls.delete asks the table and withholds such a name).
+ it('removes the legacy directories of a UUID-shaped name as well', async () => {
const { factory } = buildBothDirFactory('baileys');
- const otherId = '0b5c3a52-6d1e-4c1a-9f0e-2a7b8c9d0e1f';
- const otherWwjs = wwjsAuthDir(path.join(tmpRoot, 'sessions'), otherId);
- const otherBaileys = baileysAuthDir(path.join(tmpRoot, 'baileys'), otherId);
- fs.mkdirSync(otherWwjs, { recursive: true });
- fs.mkdirSync(otherBaileys, { recursive: true });
+ const uuidName = '0b5c3a52-6d1e-4c1a-9f0e-2a7b8c9d0e1f';
+ const legacyWwjs = wwjsAuthDir(path.join(tmpRoot, 'sessions'), uuidName);
+ const legacyBaileys = baileysAuthDir(path.join(tmpRoot, 'baileys'), uuidName);
+ fs.mkdirSync(legacyWwjs, { recursive: true });
+ fs.mkdirSync(legacyBaileys, { recursive: true });
- await factory.purgeSessionData(SESSION_ID, otherId);
+ await factory.purgeSessionData(SESSION_ID, uuidName);
- expect(fs.existsSync(otherWwjs)).toBe(true);
- expect(fs.existsSync(otherBaileys)).toBe(true);
+ expect(fs.existsSync(legacyWwjs)).toBe(false);
+ expect(fs.existsSync(legacyBaileys)).toBe(false);
});
it('refuses to purge an unsafe session key (no rm on a traversal path)', async () => {
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index 5e4a46a80..a20b08625 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -2,7 +2,6 @@ import * as fs from 'fs';
import * as path from 'path';
import { Injectable, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
-import { isUUID } from 'class-validator';
import { IWhatsAppEngine } from './interfaces/whatsapp-engine.interface';
import { WhatsAppWebJsAdapter } from './adapters/whatsapp-web-js.adapter';
import { PluginLoaderService, PluginType, IEnginePlugin, PluginManifest } from '../core/plugins';
@@ -182,9 +181,9 @@ export class EngineFactory implements OnModuleInit {
{ engine: 'whatsapp-web.js', dir: this.wwjsAuthDir(sessionId) },
{ engine: 'baileys', dir: this.baileysAuthDir(sessionId) },
];
- // A UUID-shaped name is skipped: the name rule lets a session be named after another session's
- // id, and the dirs that name points at are then that session's live id-keyed credentials.
- if (legacyName !== undefined && isSafeSessionName(legacyName) && !isUUID(legacyName)) {
+ // The caller withholds a name that is another session's id: the dirs it points at are then that
+ // session's live id-keyed credentials, and only the caller can see the table.
+ if (legacyName !== undefined && isSafeSessionName(legacyName)) {
const legacyDirs = [
{ engine: 'whatsapp-web.js', dir: this.wwjsAuthDir(legacyName) },
{ engine: 'baileys', dir: this.baileysAuthDir(legacyName) },
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.ts
index 065c1f08d..f1cb4de31 100644
--- a/src/modules/session/logout-teardown-race.spec.ts
+++ b/src/modules/session/logout-teardown-race.spec.ts
@@ -77,6 +77,7 @@ describe('SessionService logout() name-scoped teardown fence', () => {
repository = {
findOne: jest.fn().mockResolvedValue(createMockSession()),
update: jest.fn().mockResolvedValue({ affected: 1 }),
+ exists: jest.fn().mockResolvedValue(false),
};
const messageRepository = { find: jest.fn().mockResolvedValue([]) };
const manager = { delete: jest.fn().mockResolvedValue({ affected: 1 }), remove: jest.fn() };
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index c9a137a73..7489bd53f 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -595,8 +595,12 @@ export class SessionEngineControls {
// session's WhatsApp credentials stay on the volume. Best-effort inside the factory — never
// fails an otherwise-successful delete. By this point both fences passed, so no old remover is
// live against this session's directories. The name goes too: it is the key the directories
- // carried before 0.23.5, and the boot migration keeps a legacy one it could not rename.
- await this.engineFactory.purgeSessionData(session.id, session.name);
+ // carried before 0.23.5, and the boot migration keeps a legacy one it could not rename. Unless
+ // it is another session's id, whatever its shape (an import accepts any safe key): the dirs it
+ // names are then that session's live login, the same exact-id guard the migration keeps. A
+ // failed lookup withholds the name rather than fail a delete that has already committed.
+ const nameIsAnId = await this.sessionRepository.exists({ where: { id: session.name } }).catch(() => true);
+ await this.engineFactory.purgeSessionData(session.id, nameIsAnId ? undefined : session.name);
} finally {
// Always clear the teardown mark so a later recreate/start with this id isn't suppressed. This
// stop mark was set after fence #1, so clearing it on a rejected 409 only undoes what THIS
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 669e5e688..9107defe1 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -124,6 +124,7 @@ describe('SessionService', () => {
save: jest.fn(),
remove: jest.fn(),
update: jest.fn(),
+ exists: jest.fn().mockResolvedValue(false),
};
messageRepository = {
@@ -351,6 +352,45 @@ describe('SessionService', () => {
expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1', 'test-session');
});
+ // Name-keyed directories predate 0.23.5, and a session may well be named after a tenant UUID: its
+ // shape says nothing about whose login the directory holds. Only a live session id does.
+ it('delete() purges the legacy dirs of a UUID-shaped name that is no session id', async () => {
+ const uuidName = '0f9e8d7c-6b5a-4938-8271-605f4e3d2c1b';
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ id: 'sess-uuid-1', name: uuidName }));
+
+ await service.delete('sess-uuid-1');
+
+ expect(repository.exists).toHaveBeenCalledWith({ where: { id: uuidName } });
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledWith('sess-uuid-1', uuidName);
+ });
+
+ // The name rule lets a session be named after another session's id, whatever that id looks like
+ // (an import accepts any safe key). The dirs that name points at are then the other session's
+ // live credentials, so the name is kept out of the purge.
+ it("delete() keeps the name out of the purge when it is another session's id", async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ createMockSession({ id: 'sess-uuid-1', name: 'imported-bob' }),
+ );
+ (repository.exists as jest.Mock).mockResolvedValue(true);
+
+ await service.delete('sess-uuid-1');
+
+ expect(repository.exists).toHaveBeenCalledWith({ where: { id: 'imported-bob' } });
+ expect(engineFactory.purgeSessionData).toHaveBeenCalledTimes(1);
+ expect((engineFactory.purgeSessionData as jest.Mock).mock.calls[0]).toEqual(['sess-uuid-1', undefined]);
+ });
+
+ it('delete() still purges the id-keyed dirs, and resolves, when the name lookup fails', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(
+ createMockSession({ id: 'sess-uuid-1', name: 'test-session' }),
+ );
+ (repository.exists as jest.Mock).mockRejectedValue(new Error('db gone'));
+
+ await expect(service.delete('sess-uuid-1')).resolves.toBeUndefined();
+
+ expect((engineFactory.purgeSessionData as jest.Mock).mock.calls[0]).toEqual(['sess-uuid-1', undefined]);
+ });
+
it('stop() escalates to forceDestroy when engine.disconnect() rejects — stop completes with a warning', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });