Skip to content

Commit be57609

Browse files
committed
Durante o processo de logout de uma instância, as chaves associadas ao estado criptográfico não estavam sendo removidas corretamente do Redis.
Dessa forma, quando uma nova conexão era estabelecida reutilizando o mesmo instanceName, o Baileys carregava chaves antigas e inválidas, incompatíveis com o novo conjunto de credenciais (creds) gerado na reconexão. Essa inconsistência gerava o seguinte sintoma prático: A instância autenticava com sucesso; Contudo, ao tentar enviar mensagens, entrava em estado de bloqueio, exibindo o status “aguardando mensagem” indefinidamente.
1 parent 3454bec commit be57609

File tree

4 files changed

+85
-1
lines changed

4 files changed

+85
-1
lines changed

src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,28 @@ export class BaileysStartupService extends ChannelStartupService {
266266

267267
this.client?.ws?.close();
268268

269+
const db = this.configService.get<Database>('DATABASE');
270+
const cache = this.configService.get<CacheConf>('CACHE');
271+
const provider = this.configService.get<ProviderSession>('PROVIDER');
272+
273+
if (provider?.ENABLED) {
274+
const authState = await this.authStateProvider.authStateProvider(this.instance.id);
275+
276+
await authState.removeCreds()
277+
}
278+
279+
if (cache?.REDIS.ENABLED && cache?.REDIS.SAVE_INSTANCES) {
280+
const authState = await useMultiFileAuthStateRedisDb(this.instance.id, this.cache);
281+
282+
await authState.removeCreds()
283+
}
284+
285+
if (db.SAVE_DATA.INSTANCE) {
286+
const authState = await useMultiFileAuthStatePrisma(this.instance.id, this.cache);
287+
288+
await authState.removeCreds()
289+
}
290+
269291
const sessionExists = await this.prismaRepository.session.findFirst({ where: { sessionId: this.instanceId } });
270292
if (sessionExists) {
271293
await this.prismaRepository.session.delete({ where: { sessionId: this.instanceId } });

src/utils/use-multi-file-auth-state-prisma.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { INSTANCE_DIR } from '@config/path.config';
55
import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from 'baileys';
66
import fs from 'fs/promises';
77
import path from 'path';
8+
import {Logger} from "@config/logger.config";
89

910
const fixFileName = (file: string): string | undefined => {
1011
if (!file) {
@@ -73,12 +74,15 @@ async function fileExists(file: string): Promise<any> {
7374
}
7475
}
7576

77+
const logger = new Logger('useMultiFileAuthStatePrisma');
78+
7679
export default async function useMultiFileAuthStatePrisma(
7780
sessionId: string,
7881
cache: CacheService,
7982
): Promise<{
8083
state: AuthenticationState;
8184
saveCreds: () => Promise<void>;
85+
removeCreds: () => Promise<void>;
8286
}> {
8387
const localFolder = path.join(INSTANCE_DIR, sessionId);
8488
const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
@@ -142,6 +146,27 @@ export default async function useMultiFileAuthStatePrisma(
142146
}
143147
}
144148

149+
async function removeCreds(): Promise<any> {
150+
151+
const cacheConfig = configService.get<CacheConf>('CACHE');
152+
153+
// Redis
154+
try {
155+
if (cacheConfig.REDIS.ENABLED) {
156+
await cache.delete(sessionId);
157+
logger.info({ action: 'redis.delete', sessionId });
158+
159+
return
160+
}
161+
} catch (err) {
162+
logger.warn({ action: 'redis.delete', sessionId, err });
163+
}
164+
165+
logger.info({ action: 'auth.key.delete', sessionId });
166+
167+
await deleteAuthKey(sessionId);
168+
}
169+
145170
let creds = await readData('creds');
146171
if (!creds) {
147172
creds = initAuthCreds();
@@ -183,5 +208,7 @@ export default async function useMultiFileAuthStatePrisma(
183208
saveCreds: () => {
184209
return writeData(creds, 'creds');
185210
},
211+
212+
removeCreds
186213
};
187214
}

src/utils/use-multi-file-auth-state-provider-files.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,11 @@ import { Logger } from '@config/logger.config';
3939
import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
4040
import { isNotEmpty } from 'class-validator';
4141

42-
export type AuthState = { state: AuthenticationState; saveCreds: () => Promise<void> };
42+
export type AuthState = {
43+
state: AuthenticationState;
44+
saveCreds: () => Promise<void>
45+
removeCreds: () => Promise<void>;
46+
};
4347

4448
export class AuthStateProvider {
4549
constructor(private readonly providerFiles: ProviderFiles) {}
@@ -86,6 +90,19 @@ export class AuthStateProvider {
8690
return response;
8791
};
8892

93+
const removeCreds = async () => {
94+
95+
const [response, error] = await this.providerFiles.removeSession(instance);
96+
if (error) {
97+
// this.logger.error(['removeData', error?.message, error?.stack]);
98+
return;
99+
}
100+
101+
logger.info({ action: 'remove.session', instance });
102+
103+
return;
104+
};
105+
89106
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
90107

91108
return {
@@ -126,6 +143,10 @@ export class AuthStateProvider {
126143
saveCreds: async () => {
127144
return await writeData(creds, 'creds');
128145
},
146+
147+
removeCreds
129148
};
130149
}
131150
}
151+
152+
const logger = new Logger('useMultiFileAuthStatePrisma');

src/utils/use-multi-file-auth-state-redis-db.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export async function useMultiFileAuthStateRedisDb(
88
): Promise<{
99
state: AuthenticationState;
1010
saveCreds: () => Promise<void>;
11+
removeCreds: () => Promise<void>;
1112
}> {
1213
const logger = new Logger('useMultiFileAuthStateRedisDb');
1314

@@ -36,6 +37,17 @@ export async function useMultiFileAuthStateRedisDb(
3637
}
3738
};
3839

40+
async function removeCreds(): Promise<any> {
41+
try {
42+
43+
logger.warn({ action: 'redis.delete', instanceName });
44+
45+
return await cache.delete(instanceName);
46+
} catch {
47+
return;
48+
}
49+
}
50+
3951
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
4052

4153
return {
@@ -76,5 +88,7 @@ export async function useMultiFileAuthStateRedisDb(
7688
saveCreds: async () => {
7789
return await writeData(creds, 'creds');
7890
},
91+
92+
removeCreds
7993
};
8094
}

0 commit comments

Comments
 (0)