Skip to content

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

6.2 KB
Raw Blame
// The desktop app's launch, stage by stage, for usage analytics: the app's pages can count only launches that got as
// far as a page, so main says how far each launch got. It honours the same Usage analytics switch as the pages.
// Every event goes under this install's analytics id (desktop-prefs.mjs), the one this computer's own page sends under.
import { randomUUID } from "node:crypto";
import { readLastRunVersion } from "./startup-cache-eviction.mjs";

// The app's own PostHog project; the phc_ token is a write-only public key, the same one the app's pages send with.
const TOKEN = "phc_m2hP39w8y2gLPvHgDvSXAu6xcZ3agjf4ruL56rGcMZEe";
const ENDPOINT = "https://us.i.posthog.com/i/v0/e/";
const SEND_TIMEOUT_MS = 10_000;

export const LAUNCH_STAGES = Object.freeze([
  "started", "server_spawned", "server_ready", "server_failed", "window_shown", "page_load_failed", "page_crashed",
]);
/** Why the server did not start, how the window came up, and Electron's render-process-gone reasons. */
export const LAUNCH_REASONS = Object.freeze([
  "timeout", "exited", "foreign-owner", "stuck-child", "relay",
  "painted", "crashed", "shown", "hidden",
  "abnormal-exit", "integrity-failure", "killed", "launch-failed", "oom",
]);
const OS = { darwin: "Mac OS X", win32: "Windows", linux: "Linux" };

/** The first version whose page moves an opt-out kept only in its own storage to the desktop's switch on start. */
const OPT_OUT_KEPT_SINCE = [0, 1, 113];

function atLeast(version, minimum) {
  const parts = /^(\d+)\.(\d+)\.(\d+)/.exec(typeof version === "string" ? version : "");
  if (!parts) return false;
  for (let index = 0; index < 3; index++) {
    const part = Number(parts[index + 1]);
    if (part !== minimum[index]) return part > minimum[index];
  }
  return true;
}

/** A run that sends no analytics whatever its switch says: a development build, the smoke tests, CI. Main keeps to it
 * here, and the pages this desktop shows are told the switch is off (desktop-prefs.mjs). */
export function analyticsSilenced({ packaged, env }) {
  return !packaged || env.OMB_SMOKE_TEST === "1" || Boolean(env.CI);
}

/**
 * Security: main sends only where the pages would. The switch says so (`true`), or no choice was kept (`null`) and either
 * this is the computer's first launch or its last launch ran a version whose page had already moved any opt-out kept
 * only in the page's storage into the switch. Packaged builds only, never under the smoke tests or CI.
 */
export function launchAnalyticsAllowed({ choice, firstLaunch, lastVersion, packaged, env }) {
  if (analyticsSilenced({ packaged, env })) return false;
  if (choice === true) return true;
  if (choice !== null) return false;
  return firstLaunch || atLeast(lastVersion, OPT_OUT_KEPT_SINCE);
}

const allowed = (value, list) => (typeof value === "string" && list.includes(value) ? value : "other");

/** One event to the app's analytics; resolves true once it was taken. Security: no address, no URL, no person. */
export function sendDesktopEvent(fetch, { event, id, at, properties }) {
  try {
    return Promise.resolve(fetch(ENDPOINT, {
      method: "POST", headers: { "content-type": "application/json" }, credentials: "omit", cache: "no-store",
      body: JSON.stringify({ api_key: TOKEN, event, distinct_id: id, timestamp: new Date(at).toISOString(), properties: { ...properties, $process_person_profile: false } }),
      signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
    })).then(response => response?.ok === true, () => false);
  } catch { return Promise.resolve(false); }
}
export const desktopOs = platform => OS[platform] ?? "other";

/**
 * One `desktop_launch` event per stage reached, under the install's analytics id (`installId()`, null while there is
 * none to send under) and marked `telemetry: "launch"`, so a launch is never counted as a person using the app.
 * `launch_id`, random and kept nowhere, ties the stages of one launch together.
 */
export function createLaunchAnalytics({ fetch, choice, installId, lastVersion, version, platform, packaged, env, now = Date.now, id = randomUUID() }) {
  const startedAt = now();
  const firstLaunch = lastVersion === null;
  const updated = !firstLaunch && lastVersion !== version;
  const reached = new Set();
  let serverFailure = null;
  const mayRun = () => launchAnalyticsAllowed({ choice: choice(), firstLaunch, lastVersion, packaged, env });
  const stage = (name, { reason, hidden } = {}) => {
    if (!LAUNCH_STAGES.includes(name) || reached.has(name)) return;
    reached.add(name);
    if (!mayRun()) return;
    const install = installId();
    if (!install) return;
    const why = reason ?? (name === "server_failed" ? serverFailure : undefined);
    const properties = {
      stage: name, ms: Math.max(0, Math.round(now() - startedAt)), first_launch: firstLaunch, updated,
      ...(typeof hidden === "boolean" ? { hidden } : {}), ...(why === undefined || why === null ? {} : { reason: allowed(why, LAUNCH_REASONS) }),
      telemetry: "launch", launch_id: id, app_version: version, platform: "desktop", surface: "main", $os: desktopOs(platform),
    };
    void sendDesktopEvent(fetch, { event: "desktop_launch", id: install, at: now(), properties });
  };
  return {
    stage,
    /** Whether this launch may send at all: the id to send under, or null. Security: none is made while it may not. */
    installId: () => (mayRun() ? installId() : null),
    /** The latest reason a server child did not come up; sent with `server_failed`. */
    serverFailed(outcome) { serverFailure = outcome; },
    /** A recorded crash: only the main window's page counts. */
    crashed(event) {
      if (event?.kind === "renderer" && event.surface === "main-window" && event.reason !== "clean-exit") stage("page_crashed", { reason: event.reason });
    },
  };
}

/** This app's launch: Electron's own `app` and `session`, and the desktop's kept choices. */
export function desktopLaunchAnalytics({ app, session, prefs, env = process.env }) {
  return createLaunchAnalytics({
    fetch: (...args) => session.defaultSession.fetch(...args), choice: () => prefs.analytics(), installId: () => prefs.analyticsId(), lastVersion: readLastRunVersion(app.getPath("userData")),
    version: app.getVersion(), platform: process.platform, packaged: app.isPackaged, env,
  });
}