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

LocalAuth session restore won't work when whatsapp page shows "WhatsApp works with Google Chrome 60+" message #1339

Closed rodrigogomide closed 2 years ago

rodrigogomide commented 2 years ago

Is there an existing issue for this?

Describe the bug

Sometimes, when the session is going to be restored, the WhatsApp page shows a message "WhatsApp works with Google Chrome 60+", in which the WhatsApp page stops working. The message shown has nothing to do with the browser version itself, it is a validation that is done by the Service Worker (https://web.whatsapp.com/serviceworker.js). This JS sets a version 2.2208.13 which is different from the initial version detected by the API. Some internal variable is set in the session, revalidated again after the session is restored, and only then the message "WhatsApp works with Google Chrome 60+" is shown, preventing the API from working properly. We need to try to detect what this serviceworker.js does, what functions exist in it, to try to detect which function is called and what is written in the session to try to adjust what is written/loaded at the time of generating/reading the session.

Expected behavior

When the API is going to retrieve a pre-existing session, use the serviceworker.js control function to bypass the load validation, recognizing the previous value saved in the session. Or force detection of the correct version, expected by the serviceworker.

Steps to Reproduce the Bug or Issue

  1. Load de QR and start a session-;
  2. Stop de API in the server;
  3. Try to restart the API, trying to restored the saved session;
  4. The API will not return QR, READY, AUTHENTICATED, or any other event;
  5. Take a screenshot of the page, will show a "WhatsApp works with Google Chrome 60+" message instead of the proper whatsapp web page;

Relevant Code

On https://web.whatsapp.com/serviceworker.js: Found loading this in the Service Worker: "No ServiceWorker controlling this client."));e.postMessage({action:a,message:s,version:"2.2208.13"}

Browser Type

Chromium

WhatsApp Account Type

WhatsApp Business

Does your WhatsApp account have multidevice enabled?

Yes, I am using Multi Device

Environment

Debian Linux

Additional context

I believe the WhatsApp Web page shows the wrong browser version screen because the version is not matching. It does some initial version detection with the current version. Page changes version in serviceworker ([https://web.whatsapp.com/serviceworker.js] ..."No ServiceWorker controlling this client."));e.postMessage({action:a,message:s, version:"2.2208.13"}...) the first time the API is activated. On loading it shows a version, then the version is changed to that 2.2208.13. From there, when trying to recover the session, it shows the message of the wrong browser version and in this the API cannot work correctly.

rodrigogomide commented 2 years ago

Will restore the session without asking for QR again?

GustavoBlaze commented 2 years ago

I've been facing the same problem with restoring a previous section. Once i created a new one and try to restore it, i get the same behavior. Only works if delete the session folder and start a again and scaning a new QRCode.

rodrigogomide commented 2 years ago

I will try the suggestion of deleting cache and cookies using puppetter, let's see if has any effect on loading the previus session stored.

rodrigogomide commented 2 years ago

Deleting the cache won't work. The session restore does not work every time. Sometimes show the chrome 60+ message, sometimes require QR, sometimes works fine. Looks like some issue with WhatsApp Web. The same problem happens in the whatsapp web page on browser, with normal use. I guess it is a bug that they have in their page or samething.

ayarrus commented 2 years ago

i cant see the bug, my terminal just stay black when i try use the object

wemersonrv commented 2 years ago

@rodrigogomide Here works fine for me... on WhatsApp Web v2.2208.13 and then it updated to version v2.2208.14 and still works fine. Reads the two qrcodes. And when restart it, it accepts the stored session and authenticates just fine.

The unique issue is that sometimes when restart, it ask to scan the second qrcode again... and when do that, it works too.

See below an example of how i am doing.

const fs from 'fs'
import { LocalAuth, Client } from 'whatsapp-web.js'

// ...

const myCustomId = 'my-custom-id'

const authStrategy = new LocalAuth({
    clientId: myCustomId,
    // dataPath: storage.sessionPath, // don't use dataPath to keep it default to ./wwwjs_auth
})

const worker = `${authStrategy.dataPath}/session-${myCustomId}/Default/Service Worker`
if (fs.existsSync(worker)) {
   fs.rmdirSync(worker, { recursive: true })
}

const client = new Client({
   puppeteer: {
      // headless: false,
      executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
   },
   takeoverOnConflict: true,
   takeoverTimeoutMs: 10,
   authStrategy,
 })

client.initialize()
   .then(async () => {
      const version = await this._client.getWWebVersion()
      console.log(`WHATSAPP WEB version: v${version}`)
   })
   .catch((err) => {
      console.error(err)   
   })
LighteningCode commented 2 years ago

@rodrigogomide Here works fine for me... on WhatsApp Web v2.2208.13 and then it updated to version v2.2208.14 and still works fine. Reads the two qrcodes. And when restart it, it accepts the stored session and authenticates just fine.

The unique issue is that sometimes when restart, it ask to scan the second qrcode again... and when do that, it works too.

See below an example of how i am doing.

const fs from 'fs'
import { LocalAuth, Client } from 'whatsapp-web.js'

// ...

const myCustomId = 'my-custom-id'

const authStrategy = new LocalAuth({
    clientId: myCustomId,
    // dataPath: storage.sessionPath, // don't use dataPath to keep it default to ./wwwjs_auth
})

const worker = `${authStrategy.dataPath}/session-${myCustomId}/Default/Service Worker`
if (fs.existsSync(worker)) {
   fs.rmdirSync(worker, { recursive: true })
}

const client = new Client({
   puppeteer: {
      // headless: false,
      executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
   },
   takeoverOnConflict: true,
   takeoverTimeoutMs: 10,
   authStrategy,
 })

client.initialize()
   .then(async () => {
      const version = await this._client.getWWebVersion()
      console.log(`WHATSAPP WEB version: v${version}`)
   })
   .catch((err) => {
      console.error(err)   
   })

Thanks for this, will be trying it soon

rodrigogomide commented 2 years ago

The way is to keep running the same API. If it stops, when restoring, it will ask for the QR Code again. It will not restore the saved session. By the tests I did on the normal WhatsApp Web page, it gives the same behavior. And when trying to restore a pre-existing session, it shows the chrome 60+ message, but it is intermittent, sometimes it shows, sometimes it doesn't. Just deleting the session folder restores 100%. I think it's the new normal for WhatsApp Web now.

wemersonrv commented 2 years ago

he way is to keep running the same API. If it stops, when restoring, it will ask for the QR Code again. It will not restore the saved session. By the tests I did on the normal WhatsApp Web page, it g

NOPE for me. The code above works fine for me for a week in 40 servers, with almost ZERO disconnections or freeze issues. And i ran a cronjob to reboot the entire server every 6h. see below it restarting every 6 hours, after restart the server.

image

LighteningCode commented 2 years ago

he way is to keep running the same API. If it stops, when restoring, it will ask for the QR Code again. It will not restore the saved session. By the tests I did on the normal WhatsApp Web page, it g

NOPE for me. The code above works fine for me for a week in 40 servers, with almost ZERO disconnections or freeze issues. And i ran a cronjob to reboot the entire server every 6h. see below it restarting every 6 hours, after restart the server.

image

Private VPS?

wemersonrv commented 2 years ago

he way is to keep running the same API. If it stops, when restoring, it will ask for the QR Code again. It will not restore the saved session. By the tests I did on the normal WhatsApp Web page, it g

NOPE for me. The code above works fine for me for a week in 40 servers, with almost ZERO disconnections or freeze issues. And i ran a cronjob to reboot the entire server every 6h. see below it restarting every 6 hours, after restart the server. image

Private VPS?

Amazon AWS EC2 1 vCPU and 2 GB RAM $ 10 USD. But i used Digital Ocean too with same setup and works fine too.

0rdep commented 2 years ago

I have the same issue, the current workaround is to delete the session folder before starting the app and ask the user to read the Qrcode again (unfortunately the old session keeps showing up on the user's mobile which confuses the user).

satonio commented 2 years ago

I'm affected too.

albanirneves commented 1 year ago

I have the same issue, the current workaround is to delete the session folder before starting the app and ask the user to read the Qrcode again (unfortunately the old session keeps showing up on the user's mobile which confuses the user).

This is happening with me too, any ideas about how can I restore the session properly? I'm using LocalAuth strategy, but I can't restore the sessions anymore on Ubuntu

keivenlombo13 commented 11 months ago

I have the same issue, the current workaround is to delete the session folder before starting the app and ask the user to read the Qrcode again (unfortunately the old session keeps showing up on the user's mobile which confuses the user).

This is happening with me too, any ideas about how can I restore the session properly? I'm using LocalAuth strategy, but I can't restore the sessions anymore on Ubuntu

This happened to me because Puppeteer creates multiple processes in the background. The workaround is to kill the Chromium process on every init.

const client = new Client({
    authStrategy: this.authStrategy,
    puppeteer: {
        args: [
            '--no-sandbox',
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--disable-accelerated-2d-canvas',
            '--no-first-run',
            '--no-zygote',
            '--single-process', // <- this one doesn't works in Windows
            '--disable-gpu'
        ]
    },
    takeoverOnConflict: true,
    takeoverTimeoutMs: 0,
});

// this line is important to close all the chromium page and process
this.client.pupPage?.close()
await ProcessHelper.kill('Chromium')

client.initialize()
class ProcessHelper {
    public static async kill(name): Promise<void> {
        return new Promise((resolve, reject) => {
            // Check the platform and use the appropriate command to kill Chromium processes
            const command = process.platform === 'darwin' ? 'killall Chromium' : 'pkill Chromium';

            exec(command, (err, stdout, stderr) => {
                if (err) {
                    // If there are no Chromium processes to kill, there might be an error (status code 1)
                    if (err.code === 1 && stderr && stderr.includes('No matching processes belonging to you were found')) {
                        resolve();
                    } else {
                        reject(err);
                    }
                } else {
                    resolve();
                }
            });
        });
    }
}
paulrajib commented 9 months ago

he way is to keep running the same API. If it stops, when restoring, it will ask for the QR Code again. It will not restore the saved session. By the tests I did on the normal WhatsApp Web page, it g

NOPE for me. The code above works fine for me for a week in 40 servers, with almost ZERO disconnections or freeze issues. And i ran a cronjob to reboot the entire server every 6h. see below it restarting every 6 hours, after restart the server. image

Private VPS?

Amazon AWS EC2 1 vCPU and 2 GB RAM $ 10 USD. But i used Digital Ocean too with same setup and works fine too.

Excuse me but how did you get Google Chrome in EC2 !? executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', I am having trouble in way that I can scan as headless on Terminal from server but it's hard for my client to do that whenever re-authenticate is necessary!? The program has to run after every 30 seconds but the lowest Cron Job/ Tab is 2 minutes so I have to run the code in a graceful infinite loop in a node server but How can I notify and let the client scan the by himself with his phone from his PC without logging into the server and rerun the code.