In the online game "Cookie Clicker", there is an achievement called "Cheated Cookies Taste Awful". The way to earn this badge is to use DevTools Console to spawn in as many cookies as you want. I am trying to replicate this behavior.
However, the only way that Cookie Clicker could award someone this badge is to listen to the actual console and detect when a command gets sent. Furthermore, it is able to recognize when you are spawning in cookies specifically to award you the badge. How did they manage to pull this off?
The general idea would be to deliberately expose a global function that, when called, spawns a cookie in addition to carrying out anti-cheat logic.
For example, you could have something like:
(() => {
const makeCookie = () => {
// This function creates the cookie for real
};
// This function is the honeypot
window.makeCookie = () => {
alertUserThatTheyHaveCheated();
makeCookie();
};
})();
Or you could keep track of the timestamps when the function is called:
let timeCookieWasLastSpawned = 0;
const makeCookie = () => {
const now = Date.now();
if (now - timeCookieWasLastSpawned < 180_000) {
// makeCookie cannot be called from elsewhere in the code
// more than once in a 3-minute period
// so the user must have typed in makeCookie() into the console
alertUserThatTheyHaveCheated();
}
timeCookieWasLastSpawned = now;
// proceed with logic that makes the cookie
};
Users can usually only call functions via the console if the page script has been designed to permit such a thing to happen. (This sort of global pollution is generally considered bad practice, but it's not uncommon.) So, the script-writer can specifically design things such that the functions that are exposed can easily detect that they're being called via the console, rather than from other parts of the page's original code.