Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
import { Instance, Message } from '@prisma/client';
import { createJid } from '@utils/createJid';
import { fetchLatestWaWebVersion } from '@utils/fetchLatestWaWebVersion';
import { makeProxyAgent } from '@utils/makeProxyAgent';

Check failure on line 85 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Replace `makeProxyAgent,·makeProxyAgentUndici` with `·makeProxyAgent,·makeProxyAgentUndici·`
import { getOnWhatsappCache, saveOnWhatsappCache } from '@utils/onWhatsappCache';
import { status } from '@utils/renderStatus';
import { sendTelemetry } from '@utils/sendTelemetry';
Expand Down Expand Up @@ -266,6 +266,28 @@

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

const db = this.configService.get<Database>('DATABASE');
const cache = this.configService.get<CacheConf>('CACHE');
const provider = this.configService.get<ProviderSession>('PROVIDER');

if (provider?.ENABLED) {
const authState = await this.authStateProvider.authStateProvider(this.instance.id);

await authState.removeCreds()

Check failure on line 276 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `;`
}

if (cache?.REDIS.ENABLED && cache?.REDIS.SAVE_INSTANCES) {
const authState = await useMultiFileAuthStateRedisDb(this.instance.id, this.cache);

await authState.removeCreds()

Check failure on line 282 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `;`
}

if (db.SAVE_DATA.INSTANCE) {
const authState = await useMultiFileAuthStatePrisma(this.instance.id, this.cache);

await authState.removeCreds()

Check failure on line 288 in src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

View workflow job for this annotation

GitHub Actions / check-lint-and-build

Insert `;`
}

const sessionExists = await this.prismaRepository.session.findFirst({ where: { sessionId: this.instanceId } });
if (sessionExists) {
await this.prismaRepository.session.delete({ where: { sessionId: this.instanceId } });
Expand Down
27 changes: 27 additions & 0 deletions src/utils/use-multi-file-auth-state-prisma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { INSTANCE_DIR } from '@config/path.config';
import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from 'baileys';
import fs from 'fs/promises';
import path from 'path';
import {Logger} from "@config/logger.config";

const fixFileName = (file: string): string | undefined => {
if (!file) {
Expand Down Expand Up @@ -73,12 +74,15 @@ async function fileExists(file: string): Promise<any> {
}
}

const logger = new Logger('useMultiFileAuthStatePrisma');

export default async function useMultiFileAuthStatePrisma(
sessionId: string,
cache: CacheService,
): Promise<{
state: AuthenticationState;
saveCreds: () => Promise<void>;
removeCreds: () => Promise<void>;
}> {
const localFolder = path.join(INSTANCE_DIR, sessionId);
const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
Expand Down Expand Up @@ -142,6 +146,27 @@ export default async function useMultiFileAuthStatePrisma(
}
}

async function removeCreds(): Promise<any> {

const cacheConfig = configService.get<CacheConf>('CACHE');

// Redis
try {
if (cacheConfig.REDIS.ENABLED) {
await cache.delete(sessionId);
logger.info({ action: 'redis.delete', sessionId });

return
}
} catch (err) {
logger.warn({ action: 'redis.delete', sessionId, err });
}

logger.info({ action: 'auth.key.delete', sessionId });

await deleteAuthKey(sessionId);
}
Comment on lines +149 to +167
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Avoid function declarations, favouring function assignment expressions, inside blocks. (avoid-function-declarations-in-blocks)

ExplanationFunction declarations may be hoisted in Javascript, but the behaviour is inconsistent between browsers. Hoisting is generally confusing and should be avoided. Rather than using function declarations inside blocks, you should use function expressions, which create functions in-scope.


let creds = await readData('creds');
if (!creds) {
creds = initAuthCreds();
Expand Down Expand Up @@ -183,5 +208,7 @@ export default async function useMultiFileAuthStatePrisma(
saveCreds: () => {
return writeData(creds, 'creds');
},

removeCreds
};
}
23 changes: 22 additions & 1 deletion src/utils/use-multi-file-auth-state-provider-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ import { Logger } from '@config/logger.config';
import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
import { isNotEmpty } from 'class-validator';

export type AuthState = { state: AuthenticationState; saveCreds: () => Promise<void> };
export type AuthState = {
state: AuthenticationState;
saveCreds: () => Promise<void>
removeCreds: () => Promise<void>;
};

export class AuthStateProvider {
constructor(private readonly providerFiles: ProviderFiles) {}
Expand Down Expand Up @@ -86,6 +90,19 @@ export class AuthStateProvider {
return response;
};

const removeCreds = async () => {

const [response, error] = await this.providerFiles.removeSession(instance);
if (error) {
// this.logger.error(['removeData', error?.message, error?.stack]);
return;
}
Comment on lines +93 to +98
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): removeCreds swallows errors silently; consider logging or surfacing them.

Errors from providerFiles.removeSession are currently ignored. If downstream consumers rely on error handling, log or propagate these errors.

Suggested change
const removeCreds = async () => {
const [response, error] = await this.providerFiles.removeSession(instance);
if (error) {
// this.logger.error(['removeData', error?.message, error?.stack]);
return;
}
const removeCreds = async () => {
const [response, error] = await this.providerFiles.removeSession(instance);
if (error) {
if (this.logger) {
this.logger.error(['removeCreds', error?.message, error?.stack]);
} else {
console.error('removeCreds error:', error);
}
throw error;
}


logger.info({ action: 'remove.session', instance });

return;
};

const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();

return {
Expand Down Expand Up @@ -126,6 +143,10 @@ export class AuthStateProvider {
saveCreds: async () => {
return await writeData(creds, 'creds');
},

removeCreds
};
}
}

const logger = new Logger('useMultiFileAuthStatePrisma');
14 changes: 14 additions & 0 deletions src/utils/use-multi-file-auth-state-redis-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export async function useMultiFileAuthStateRedisDb(
): Promise<{
state: AuthenticationState;
saveCreds: () => Promise<void>;
removeCreds: () => Promise<void>;
}> {
const logger = new Logger('useMultiFileAuthStateRedisDb');

Expand Down Expand Up @@ -36,6 +37,17 @@ export async function useMultiFileAuthStateRedisDb(
}
};

async function removeCreds(): Promise<any> {
try {

logger.warn({ action: 'redis.delete', instanceName });

return await cache.delete(instanceName);
} catch {
return;
}
Comment on lines +41 to +47
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Consider using logger.info for successful deletion and logger.warn only for errors.

Use logger.info to indicate successful deletion, and reserve logger.warn or logger.error for error cases to improve log clarity.

Suggested change
try {
logger.warn({ action: 'redis.delete', instanceName });
return await cache.delete(instanceName);
} catch {
return;
}
try {
logger.info({ action: 'redis.delete', instanceName });
await cache.delete(instanceName);
} catch (err) {
logger.warn({ action: 'redis.delete.failed', instanceName, error: err });
return;
}

}
Comment on lines +40 to +48
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (code-quality): Avoid function declarations, favouring function assignment expressions, inside blocks. (avoid-function-declarations-in-blocks)

ExplanationFunction declarations may be hoisted in Javascript, but the behaviour is inconsistent between browsers. Hoisting is generally confusing and should be avoided. Rather than using function declarations inside blocks, you should use function expressions, which create functions in-scope.


const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();

return {
Expand Down Expand Up @@ -76,5 +88,7 @@ export async function useMultiFileAuthStateRedisDb(
saveCreds: async () => {
return await writeData(creds, 'creds');
},

removeCreds
};
}
Loading