Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): keep another session's login on a PostgreSQL delete
Yudhi Armyndharis3157d7ad0a63
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.tsindex c96e88916..895a31298 100644--- a/src/modules/session/session-engine-controls.ts+++ b/src/modules/session/session-engine-controls.ts@@ -7,8 +7,7 @@ import {ServiceUnavailableException,} from '@nestjs/common';import { ConfigService } from '@nestjs/config';-import { isUUID } from 'class-validator';-import { EntityTarget, EntityManager, In, IsNull, Repository, DataSource } from 'typeorm';+import { EntityTarget, EntityManager, In, IsNull, Raw, Repository, DataSource } from 'typeorm';import { Session, SessionStatus } from './entities/session.entity';import { Message } from '../message/entities/message.entity';import { MessageBatch } from '../message/entities/message-batch.entity';@@ -957,14 +956,16 @@ export class SessionEngineControls {// 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. On- // PostgreSQL the id column is a uuid, so a name of any other shape is no session's id there, and- // looking it up would fail rather than miss.+ // failed lookup withholds the name rather than fail a delete that has already committed. The id+ // column is varchar on PostgreSQL too (an import keeps any safe key), so a name of any shape can be+ // a session's id there; it is compared as text, which also covers a column typed uuid.// Keyed by `id`, not `session.id`: TypeORM clears a removed entity's primary key, so session.id// is undefined here and the purge would refuse it as an unsafe key and remove nothing.- const nameIsAnId =- (dataSource.options.type !== 'postgres' || isUUID(session.name)) &&- (await this.sessionRepository.exists({ where: { id: session.name } }).catch(() => true));+ const legacyId =+ dataSource.options.type === 'postgres'+ ? Raw(alias => `CAST(${alias} AS text) = :legacyId`, { legacyId: session.name })+ : session.name;+ const nameIsAnId = await this.sessionRepository.exists({ where: { id: legacyId } }).catch(() => true);await this.engineFactory.purgeSessionData(id, nameIsAnId ? undefined : session.name);} catch (error) {// The session survives, but the write scopes closed above stay retired for good: a bulk batchdiff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex b3e04ee98..0b44e38a9 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -449,6 +449,49 @@ describe('SessionService', () => {// 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.each(['better-sqlite3', 'postgres'] as const)(+ "delete() preserves another imported session's id-keyed directories on %s",+ async dialect => {+ Object.assign(dataSource, { options: { type: dialect } });+ (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).toHaveBeenCalled();+ expect((engineFactory.purgeSessionData as jest.Mock).mock.calls).toEqual([['sess-uuid-1', undefined]]);+ },+ );++ it.each([false, true])('executes the text ID lookup before legacy cleanup (collision: %s)', async collision => {+ // The portable cast runs through the real TypeORM parser and SQLite driver.+ const sql = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [Session],+ synchronize: true,+ });+ await sql.initialize();+ try {+ const sessions = sql.getRepository(Session);+ if (collision) await sessions.save({ id: 'imported-bob', name: 'other-session' });+ Object.assign(dataSource, { options: { type: 'postgres' } });+ (repository.findOne as jest.Mock).mockResolvedValue(+ createMockSession({ id: 'sess-uuid-1', name: 'imported-bob' }),+ );+ (repository.exists as jest.Mock).mockImplementation((options: Parameters<typeof sessions.exists>[0]) =>+ sessions.exists(options),+ );+ await service.delete('sess-uuid-1');+ await expect((repository.exists as jest.Mock).mock.results[0].value).resolves.toBe(collision);+ expect((engineFactory.purgeSessionData as jest.Mock).mock.calls).toEqual([+ ['sess-uuid-1', collision ? undefined : 'imported-bob'],+ ]);+ } finally {+ await sql.destroy();+ }+ });+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' }),