如何在 Javascript 中收听控制台命令

How to listen to console commands in Javascript

网络游戏《饼干唱首歌》中,有一个成就叫做“作弊饼干味道太差”。获得此徽章的方法是使用 DevTools 控制台生成任意数量的 cookie。我正在尝试复制此行为。

但是,Cookie Clicker 授予某人此徽章的唯一方法是监听实际的控制台并检测命令何时发送。此外,它能够识别您何时在 cookie 中产卵,专门为您授予徽章。他们是如何做到这一点的?

一般的想法是故意公开一个全局函数,该函数在调用时除了执行反作弊逻辑外还会生成一个 cookie。

例如,你可以有这样的东西:

(() => {
  const makeCookie = () => {
    // This function creates the cookie for real
  };

  // This function is the honeypot
  window.makeCookie = () => {
    alertUserThatTheyHaveCheated();
    makeCookie();
  };
})();

或者您可以跟踪调用函数时的时间戳:

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
};

如果页面脚本被设计成允许这样的事情发生,用户通常只能通过控制台调用函数。 (这种全局污染通常被认为是不好的做法,但并不少见。)因此,脚本编写者可以专门设计一些东西,以便暴露的函数可以很容易地检测到它们是通过控制台调用的,而不是来自页面原始代码的其他部分。