Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

7.1 KB
Raw Blame
// @vitest-environment happy-dom
// @vitest-environment-options {"url":"http://127.0.0.1:5174/","settings":{"disableJavaScriptFileLoading":true,"disableJavaScriptEvaluation":true,"disableCSSFileLoading":true,"disableIframePageLoading":true}}
// The real posthog-js on a page the desktop app shows, behind a recording network stub. The app's user agent names the
// app, and posthog-js sends nothing from a user agent with a crawler's mark ("bot/" is one) unless told the page is no
// crawler. One flow: posthog-js is a single instance per process.
import { gunzipSync } from "node:zlib";
import { expect, it, vi } from "vitest";

/** What Electron makes of the packaged app's name and version, the same on every platform but for the system part. */
const DESKTOP_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) OpenMausBot/0.1.186 Chrome/150.0.7871.250 Electron/43.8.13 Safari/537.36";
const TOKEN = "phc_m2hP39w8y2gLPvHgDvSXAu6xcZ3agjf4ruL56rGcMZEe";

const sent: Array<{ url: string; body: unknown }> = [];
class RecordingXhr {
  readyState = 0;
  status = 0;
  responseText = "";
  withCredentials = false;
  onreadystatechange: (() => void) | null = null;
  private url = "";
  open(_method: string, url: string) { this.url = url; }
  setRequestHeader() {}
  send(body?: unknown) {
    sent.push({ url: this.url, body });
    this.readyState = 4;
    this.status = 200;
    this.responseText = "{}";
    queueMicrotask(() => this.onreadystatechange?.());
  }
  abort() {}
}
function memoryStorage() {
  const map = new Map<string, string>();
  return {
    get length() { return map.size; },
    key: (index: number) => [...map.keys()][index] ?? null,
    getItem: (key: string) => map.get(key) ?? null,
    setItem: (key: string, value: string) => void map.set(key, String(value)),
    removeItem: (key: string) => void map.delete(key),
    clear: () => map.clear(),
  };
}

// posthog-js reads these when its module loads, so they are in place before analytics.ts imports it.
vi.stubGlobal("fetch", async (input: unknown, init?: { body?: unknown }) => {
  sent.push({ url: String((input as { url?: string })?.url ?? input), body: init?.body });
  const json = { status: 1 };
  return { status: 200, ok: true, headers: new Headers(), text: async () => JSON.stringify(json), json: async () => json };
});
vi.stubGlobal("XMLHttpRequest", RecordingXhr);
Object.defineProperty(navigator, "sendBeacon", { configurable: true, value: (url: string, body: unknown) => (sent.push({ url, body }), true) });
Object.defineProperty(navigator, "webdriver", { configurable: true, get: () => false });
Object.defineProperty(navigator, "userAgent", { configurable: true, get: () => DESKTOP_USER_AGENT });
vi.stubGlobal("sessionStorage", memoryStorage());
vi.stubGlobal("localStorage", memoryStorage());
// The desktop app's bridge on this computer's own page, with no analytics choice kept yet. Main deletes its analytics
// id when the switch goes off and makes a new one when it comes back on.
const INSTALL_IDS = ["install-AAAAAAAAAAAAAAAAAAAAAAAAAAAA", "install-BBBBBBBBBBBBBBBBBBBBBBBBBBBB"];
let installId: string | null = INSTALL_IDS[0]!;
Object.assign(window, { ogb: { environments: {}, desktopAnalytics: {
  enabled: () => null, id: () => installId,
  set: async (enabled: boolean) => { installId = enabled ? INSTALL_IDS[1]! : null; },
} } });
// PostHog's CDN config for this project, as posthog-js would have loaded it.
(window as unknown as Record<string, unknown>)._POSTHOG_REMOTE_CONFIG = {
  [TOKEN]: {
    config: {
      analytics: { endpoint: "/i/v0/e/" }, hasFeatureFlags: false, sessionRecording: false, surveys: false, heatmaps: false,
      productTours: false, conversations: false, captureDeadClicks: false, autocaptureExceptions: false, siteApps: [],
      supportedCompression: ["gzip", "gzip-js"],
    },
  },
};

async function bodyText(body: unknown): Promise<string> {
  if (body === undefined || body === null) return "";
  if (typeof body === "string") return body.startsWith("data=") ? Buffer.from(decodeURIComponent(body.slice(5)), "base64").toString("utf8") : body;
  const bytes = Buffer.from(body instanceof Blob ? await body.arrayBuffer() : body as ArrayBuffer);
  return (bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes).toString("utf8");
}

type Sent = { event: string; properties: Record<string, unknown> & { distinct_id?: string } };
async function events(): Promise<Sent[]> {
  const bodies = await Promise.all(sent.map(({ body }) => bodyText(body)));
  return bodies.filter(Boolean).flatMap((body) => { const parsed = JSON.parse(body) as Sent | { batch: Sent[] }; return "batch" in parsed ? parsed.batch : [parsed]; });
}

it("sends the desktop app's page events although the app's user agent carries a crawler's mark", async () => {
  expect(navigator.userAgent.toLowerCase()).toContain("bot/");
  vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"] });
  try {
    const analytics = await import("./analytics");
    await analytics.initAnalytics();
    analytics.track("app_snapshot", { bots: 3 });
    for (let elapsed = 0; elapsed < 60; elapsed += 10) {
      await vi.advanceTimersByTimeAsync(10_000);
      await new Promise((resolve) => setImmediate(resolve));
    }
    // posthog-js gzips each batch with the platform's CompressionStream, which finishes on the real clock.
    await vi.waitFor(async () => {
      expect((await events()).map(({ event }) => event)).toEqual(expect.arrayContaining(["app_first_open", "app_opened", "app_active", "app_snapshot"]));
    }, { timeout: 30_000, interval: 20 });

    expect(sent.map(({ url }) => { const { origin, pathname } = new URL(url); return `${origin}${pathname}`; }).filter((url) => url !== "https://us.i.posthog.com/i/v0/e/")).toEqual([]);
    const all = await events();
    for (const { properties } of all) {
      expect(properties).toMatchObject({ platform: "desktop", surface: "local" });
      // posthog-js's own guess from the user agent would call every desktop page a bot.
      expect(properties).not.toHaveProperty("$browser_type");
    }
    expect(JSON.stringify(all)).not.toContain("127.0.0.1");
    // One install is one id: the app's own, whichever port's storage this page has.
    expect([...new Set(all.map(({ properties }) => properties.distinct_id))]).toEqual([INSTALL_IDS[0]]);

    const before = sent.length;
    analytics.setAnalyticsEnabled(false);
    analytics.track("after_off");
    for (let elapsed = 0; elapsed < 600; elapsed += 10) await vi.advanceTimersByTimeAsync(10_000);
    expect(sent.slice(before).map(({ url }) => url)).toEqual([]);

    analytics.setAnalyticsEnabled(true);
    await vi.advanceTimersByTimeAsync(0);
    analytics.track("after_on");
    for (let elapsed = 0; elapsed < 60; elapsed += 10) {
      await vi.advanceTimersByTimeAsync(10_000);
      await new Promise((resolve) => setImmediate(resolve));
    }
    await vi.waitFor(async () => expect((await events()).map(({ event }) => event)).toContain("after_on"), { timeout: 30_000, interval: 20 });
    expect((await events()).filter(({ event }) => event === "after_on").map(({ properties }) => properties.distinct_id)).toEqual([INSTALL_IDS[1]]);
  } finally {
    vi.useRealTimers();
  }
});