pedroslopez / whatsapp-web.js

A WhatsApp client library for NodeJS that connects through the WhatsApp Web browser app
https://wwebjs.dev
Apache License 2.0
14.62k stars 3.48k forks source link

🐛🐛 session does not persist using LocalAuth id 🐛🐛 #2164

Open andresmv94 opened 1 year ago

andresmv94 commented 1 year ago

Is there an existing issue for this?

Describe the bug

I have been using "whatsapp-web.js" in my application for about 6 months, and yesterday the session persistence stopped working, I am using authStrategy: new LocalAuth({ clientId: user._id }), and with this When I want to use the WhatsApp channel again, I can use it without having to scan the QR again, but every time that I want to use the channel and send messages, it is making me to scan the QR and this was not happening until yesterday

Expected behavior

for first time scan the QR once, and be able to continue using whatsapp without having to scan each time I use it

Steps to Reproduce the Bug or Issue

  1. configure the server in linux to work
  2. configure whatsapp web js with authStrategy: new LocalAuth({ clientId: "some-client-id" })
  3. scan the QR and send a message
  4. reuse sending messages with the same "some-client-id"

Relevant Code

function authWhatsapp (user) => {
    console.log("init authentication");
    const client = await new Client({
      authStrategy: new LocalAuth({ clientId: user._id }), // user = {_id: "1234abc", name: "juan"}
      qrMaxRetries: 3,
      authTimeoutMs: 60000,
      puppeteer: {
        executablePath: process.env.CHROME_EXECUTABLE_PATH, // CHROME_EXECUTABLE_PATH=/usr/bin/google-chrome-stable
        args: ["--no-sandbox", "--disable-setuid-sandbox"],
      },
    }); 

    client.on("qr", async (qr) => {
        console.log("scan qr");
        console.log(qr);        

    });

     client.on("ready", async () => {
        console.log("Wapp web connected");
     });

}

function sendWhatsapp (user) => {
    console.log("try send messages");
    client = await new Client({
      authStrategy: new LocalAuth({ clientId: user._id }), // user = {_id: "1234abc", name: "juan"}
      authTimeoutMs: 60000,
      puppeteer: {
        executablePath: process.env.CHROME_EXECUTABLE_PATH,  // CHROME_EXECUTABLE_PATH=/usr/bin/google-chrome-stable
        args: ["--no-sandbox", "--disable-setuid-sandbox"],
      },
    });

     client.on("ready", async () => { // this is never executed 🫤
        console.log("perfect, your are authenticated, Wapp web connected");
        /*
            code to send messages...
        */
     });

     client.on("qr", async (qr) => {

        console.log("The whatsapp is asking for QR you are not authenticated"); 
        console.log(qr);    

    });

}

for authWhatsapp function:

> init authentication
> scan qr
> 2@Zy5JBs9MeMX0GBeDlNd1....RUI9lbeATZGDNBtx52+29CIw=
> Wapp web connected

for sendWhatsapp function: 

> try send messages
> The whatsapp is asking for QR you are not authenticated
> 2@TYQbrQCmYVbCB0KG...dEy8edXIPh32AiME0=

Browser Type

Google Chrome

WhatsApp Account Type

Standard

Does your WhatsApp account have multidevice enabled?

Yes, I am using Multi Device

Environment

OS: Ubuntu 20
Phone OS:  Android, iOS
whatsapp-web.js version [1.19.5]
WhatsApp Web version [2.2317.10]:
Node.js Version [v19.8.1]

Additional context

remember: this was not happening until yesterday, I already tried setting all the permissions to the .wwebjs_auth folder, and to all its content, but it's still the same, I also notice that in windows (no server -> my personal computer) with exactly the same configuration but using CHROME_EXECUTABLE_PATH=C:/Program Files/Google/Chrome /Application/chrome.exe, it is working correctly, any idea why?

maybe the session files are not being saved correctly in the ".wwebjs_auth" folder, but I don't really know how to look at that part

Update: in other computer with Windows is happenig the same issue so is not the OS.

eduardotorresdev commented 4 months ago

@Avivbens, I tried but it didn't made it. Can you share the whatsapp-web.js version? Did you change the puppeteer version? Any help is very welcome.

Avivbens commented 4 months ago

@Avivbens, I tried but it didn't made it. Can you share the whatsapp-web.js version? Did you change the puppeteer version? Any help is very welcome.

Sure man 👍

Here are my deps versions: CleanShot 2024-02-20 at 19 16 30

Avivbens commented 4 months ago

@eduardotorresdev BTW, let the connection to establish for a minute or two...

You'll see on your WhatsApp client over the device that your chats are in sync. Keep it that way for a bit, then test the restart.

eduardotorresdev commented 4 months ago

@Avivbens It's worked! Thank you. I just waited the time for WhatsApp client sync with device and, that's it, worked like charm.

Avivbens commented 4 months ago

@Avivbens It's worked! Thank you. I just waited the time for WhatsApp client sync with device and, that's it, worked like charm.

Happy to hear 🥳

For future documentation - list here the versions you're on please 🙏

eduardotorresdev commented 4 months ago

I'm using whatsapp-web.js at "^1.23.0" version. I didn't changed puppeteer version or of any related package to wwebjs lib. I just added the webVersion that you told previously.

eduardotorresdev commented 4 months ago

@Avivbens Can i colaborate with something? I believe that is very important to documentate all this question of auth and his persistance, so maybe we can do this together.

Avivbens commented 4 months ago

@Avivbens Can i colaborate with something? I believe that is very important to documentate all this question of auth and his persistance, so maybe we can do this together.

Well, that is a good idea. Personally, I find GitHub issues part of the documentation, but we might add it into the official docs for such an important thing.

That being said, the documentation structure of this project isn't in its best shape. The current documentation site is being generated by JsDocs, but I cannot see the content anywhere in the repo.

Maybe the owner can give us a hint here 👼

@pedroslopez

yairmelamed commented 4 months ago

OK, I've managed to resolve the issue:

TL;DR Set the webVersion to 2.2306.7

NestJS provider

export const WhatsappClientProvider: Provider<Client> = {
    provide: WHATSAPP_CLIENT,
    inject: [ConfigService],
    useFactory: async (configService: ConfigService) => {
        const logger: Logger = new Logger('WHATSAPP_CLIENT')
        const env = configService.get<Envs>(EnvVariables.NODE_ENV, Envs.Production)
        const args = env === Envs.Production ? ['--no-sandbox', '--disable-setuid-sandbox'] : undefined

        const client = new Client({
            authStrategy: new LocalAuth(),
            webVersion: '2.2306.7', // this keeps the Whatsapp Verison with the latest version worked 👍 
            puppeteer: {
                args,
            },
        })

        client.once('qr', (qr) => {
            logger.debug('QR code received, scan please')
            return qrcode.generate(qr)
        })

        client.on('authenticated', () => {
            logger.debug('Authenticated successfully!')
        })

        client.on('disconnected', (reason) => {
            logger.error(`Disconnected, reason: ${reason}`)
        })

        const prm = new Promise<void>((resolve) =>
            client.on('ready', async () => {
                logger.debug('WhatsApp Client is ready!')
                resolve()
            }),
        )

        client.initialize()

        await prm
        return client
    },
}

Terminal Screenshot

CleanShot 2024-02-19 at 17 35 08

It doesn't help, it works for one week and then suddenly it disconnects and asks for qr again on restore with no reason.. how can we fix this?? why it's happening?

Avivbens commented 4 months ago

OK, I've managed to resolve the issue: TL;DR Set the webVersion to 2.2306.7

NestJS provider

export const WhatsappClientProvider: Provider<Client> = {
    provide: WHATSAPP_CLIENT,
    inject: [ConfigService],
    useFactory: async (configService: ConfigService) => {
        const logger: Logger = new Logger('WHATSAPP_CLIENT')
        const env = configService.get<Envs>(EnvVariables.NODE_ENV, Envs.Production)
        const args = env === Envs.Production ? ['--no-sandbox', '--disable-setuid-sandbox'] : undefined

        const client = new Client({
            authStrategy: new LocalAuth(),
            webVersion: '2.2306.7', // this keeps the Whatsapp Verison with the latest version worked 👍 
            puppeteer: {
                args,
            },
        })

        client.once('qr', (qr) => {
            logger.debug('QR code received, scan please')
            return qrcode.generate(qr)
        })

        client.on('authenticated', () => {
            logger.debug('Authenticated successfully!')
        })

        client.on('disconnected', (reason) => {
            logger.error(`Disconnected, reason: ${reason}`)
        })

        const prm = new Promise<void>((resolve) =>
            client.on('ready', async () => {
                logger.debug('WhatsApp Client is ready!')
                resolve()
            }),
        )

        client.initialize()

        await prm
        return client
    },
}

Terminal Screenshot

CleanShot 2024-02-19 at 17 35 08

It doesn't help, it works for one week and then suddenly it disconnects and asks for qr again on restore with no reason.. how can we fix this?? why it's happening?

Well, in general, the library has an Apache license, meaning it has no responsibility for the stability of the product. I can just assume that Whatsapp servers can revoke client authentication based on its behavior.

That being said, you can try to use the RemoteAuth strategy, it might be a bit more stable.

yairmelamed commented 2 months ago

Hello every one.. is there a solution here? It is so frustrating.. It still happens..

josuelmm commented 1 month ago

Same problem

MikeSoft commented 2 weeks ago

up