Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(identity): release a deleted session's lid mappings

Yudhi Armyndharis3ce0bf04cf0e
diff --git a/src/engine/engine.factory.spec.ts b/src/engine/engine.factory.spec.ts
index 47e580688..a68ed9866 100644
--- a/src/engine/engine.factory.spec.ts
+++ b/src/engine/engine.factory.spec.ts
@@ -41,6 +41,7 @@ describe('EngineFactory', () => {
getCached: jest.fn(),
lidsForPhone: jest.fn().mockReturnValue([]),
remember: jest.fn().mockResolvedValue(undefined),
+ releaseSession: jest.fn().mockResolvedValue(undefined),
}) as unknown as LidMappingStoreService;
const buildChatStateStore = (): ChatStateStoreService =>
@@ -290,6 +291,7 @@ describe('EngineFactory', () => {
const buildBothDirFactory = (engineType: string) => {
const sessionDataPath = path.join(tmpRoot, 'sessions');
const authDir = path.join(tmpRoot, 'baileys');
+ const lidStore = buildLidStore();
const factory = new EngineFactory(
buildConfigService({
'engine.type': engineType,
@@ -298,11 +300,12 @@ describe('EngineFactory', () => {
}),
noPluginLoader(),
buildMessageStore(),
- buildLidStore(),
+ lidStore,
buildChatStateStore(),
);
return {
factory,
+ lidStore,
wwjsDir: wwjsAuthDir(sessionDataPath, SESSION_ID),
baileysDir: baileysAuthDir(authDir, SESSION_ID),
};
@@ -347,6 +350,17 @@ describe('EngineFactory', () => {
expect(fs.existsSync(baileysDir)).toBe(true);
});
+ it("hands the deleted session's lid mappings to no session, and not for an unsafe key", async () => {
+ const { factory, lidStore } = buildBothDirFactory('baileys');
+ const { releaseSession } = lidStore as unknown as { releaseSession: jest.Mock };
+
+ await factory.purgeSessionData(SESSION_ID);
+ await factory.purgeSessionData('../baileys-evil');
+
+ expect(releaseSession).toHaveBeenCalledTimes(1);
+ expect(releaseSession).toHaveBeenCalledWith(SESSION_ID);
+ });
+
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();
diff --git a/src/engine/engine.factory.ts b/src/engine/engine.factory.ts
index b08bf1b78..126943450 100644
--- a/src/engine/engine.factory.ts
+++ b/src/engine/engine.factory.ts
@@ -167,6 +167,9 @@ export class EngineFactory implements OnModuleInit {
* id-keyed directory already there), so purging only the id-keyed dirs would strand a complete
* WhatsApp login on the volume and in every backup taken after the delete. It is removed only when
* the base directory really holds an entry with that exact name; see readAuthDirEntries.
+ *
+ * The session's lid mappings are kept (the table is shared) but handed to no session, so a phone
+ * this session stored can still be cleared by the session that replaces it (see LidMappingStoreService).
*/
async purgeSessionData(sessionId: string, legacyName?: string): Promise<void> {
if (!isSafeSessionName(sessionId)) {
@@ -177,6 +180,7 @@ export class EngineFactory implements OnModuleInit {
});
return;
}
+ await this.lidMappingStore.releaseSession(sessionId);
const dirs: Array<{ engine: string; dir: string }> = [
{ engine: 'whatsapp-web.js', dir: this.wwjsAuthDir(sessionId) },
{ engine: 'baileys', dir: this.baileysAuthDir(sessionId) },
diff --git a/src/engine/identity/lid-mapping-store.service.ts b/src/engine/identity/lid-mapping-store.service.ts
index 1b791dc72..94123ba4e 100644
--- a/src/engine/identity/lid-mapping-store.service.ts
+++ b/src/engine/identity/lid-mapping-store.service.ts
@@ -328,6 +328,20 @@ export class LidMappingStoreService implements LidMappingStore, OnModuleInit {
this.absentFromTable.delete(lid);
}
+ /**
+ * Hand a deleted session's rows to no session. Its id never comes back (a re-created session gets a
+ * new one), so without this no later negative could clear a phone it stored. The rows stay: the table
+ * is shared. Never throws: the session is already gone.
+ */
+ async releaseSession(sessionId: string): Promise<void> {
+ try {
+ // updatedAt is kept: no mapping changed, and the preload ranks rows by it.
+ await this.repo.update({ sessionId }, { sessionId: null, updatedAt: () => '"updatedAt"' });
+ } catch (err) {
+ this.logger.warn(`Could not release lid mappings: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+
/**
* Repository fallback for a cache miss. Rows past the preload cap (or evicted by the LRU) are
* still persisted, so a miss is warmed from the table: THIS lookup still returns undefined —
diff --git a/src/engine/identity/lid-mapping-store.spec.ts b/src/engine/identity/lid-mapping-store.spec.ts
index 4e3de992d..41c7515ec 100644
--- a/src/engine/identity/lid-mapping-store.spec.ts
+++ b/src/engine/identity/lid-mapping-store.spec.ts
@@ -856,6 +856,26 @@ describe('LidMappingStoreService: a negative result on the shared table', () =>
expect(store.lidsForPhone('628111')).toEqual([]);
});
+ it('lets a later session clear a phone once the session that stored it is released', async () => {
+ await store.remember('111', '628111', 's1');
+ await store.remember('222', '628222', 's9');
+ const stamp = new Date('2020-01-01T00:00:00.000Z');
+ await repo.update({ lid: '111' }, { updatedAt: stamp });
+
+ await store.releaseSession('s1');
+
+ expect(await row('111')).toMatchObject({ phone: '628111', sessionId: null, updatedAt: stamp });
+ expect(await row('222')).toMatchObject({ phone: '628222', sessionId: 's9' });
+ await store.remember('111', null, 's2');
+ expect(await row('111')).toMatchObject({ phone: null, sessionId: 's2' });
+ });
+
+ it('releaseSession never throws', async () => {
+ jest.spyOn(repo, 'update').mockRejectedValueOnce(new Error('connection lost'));
+
+ await expect(store.releaseSession('s1')).resolves.toBeUndefined();
+ });
+
it('a phone from any session still replaces the row', async () => {
await store.remember('111', null, 's1');
await store.remember('111', '628111', 's2');