Search code examples
userscripts

A simple login script sometimes work and sometimes doesn't


I have the following code I execute in Chrome with Tampermonkey, which I use to login to digitalocean.com.

setTimeout (function() {
document.querySelector("input[type=submit]").click();
}, 3000);

For some reason, this code sometimes work and sometimes it doesn't: That is, sometimes I'm logged in and sometimes (most cases) I get DigitalOcean's 404 webpage.

My login details are already saved in local storage and appear on the form.

By principle, this problem can be reproduced by registering to DigitalOcean, installing Tampermonkey, and executing the code with it, with the match:

https://cloud.digitalocean.com/login*

Might something be missing to ensure human-like behavior in the eyes of the machine?


Solution

  • OK, it took some digging, but I see what's going on.

    • There is an authentication token in the form.
    • If the token is not what the server expects, it kicks you to a 404 error at https://cloud.digitalocean.com/sessions.
    • If your browser loads the login page from cache (usually because you got to it by clicking the "back" button in your browser) you'll be submitting an invalid token (the one you got back when the page was put in the cache).
    • Sometimes it's wrong for some other reason I haven't figured out.

    To deal with the cache-loaded page issue

    I'd edit your script check if the page was loaded from cache, and refresh the page instead of triggering the click event:

    if (window.performance.navigation.type === 2)
    {
        location.reload();
    } else {
        document.querySelector("input[type=submit]").click();
    }
    

    The other issue is probably an issue with DigitalOcean's back-end

    I'd recommend that you report the fact that their login page seems to occasionally get a bad authentication token, as the issue can intermittently be reproduced by clicking (with the mouse) on the "Log In" button of a freshly loaded copy of the page.
    (I wouldn't mention the script or they'll blame it and then you'll be out of luck.)

    In the mean-time

    As a stop-gap until they fix their issue, you could make a new script matching https://cloud.digitalocean.com/sessions (it sends me to that page exactly, but add a * if it's needed) that sends you back if you came from the login page, and got a 404 error:

    if (document.referrer.startsWith("https://cloud.digitalocean.com/login") && document.title.endsWith(" (404)"))
    {
        history.back();
    }
    

    Note that document.title.endsWith(" (404)") only works because the contents of their 404 page's <title> tag ends with (404).