Skip to content

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

7.0 KB
Raw Blame
// Served without auth at /.well-known/openmausbot/environment, so a saved connection can check it still reaches the same server.
import { randomUUID } from "node:crypto";
import {
  closeSync,
  existsSync,
  fsyncSync,
  linkSync,
  mkdirSync,
  openSync,
  readFileSync,
  unlinkSync,
  writeFileSync,
} from "node:fs";
import { hostname } from "node:os";
import { dirname, join } from "node:path";

import { cliPrefix } from "./cli-invocation.ts";
import type { EnvironmentDescriptor, ServerInstall } from "../packages/phone-protocol/src/environment.ts";
import { SERVER_ROOT } from "./proxy-paths.ts";

export type { EnvironmentDescriptor, ServerInstall };

const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

function hasCode(error: unknown, code: string): error is NodeJS.ErrnoException {
  return error instanceof Error && "code" in error && error.code === code;
}

function readEnvironmentId(file: string): string | undefined {
  let contents: string;
  try {
    contents = readFileSync(file, "utf8");
  } catch (error) {
    if (hasCode(error, "ENOENT")) return undefined;
    throw new Error(`Cannot read the existing environment identity at ${file}; refusing to replace it.`, {
      cause: error,
    });
  }

  const id = contents.trim();
  if (!UUID_PATTERN.test(id)) {
    throw new Error(`The existing environment identity at ${file} is not a valid UUID; refusing to replace it.`);
  }
  return id;
}

/** Read or create the id. Written once, never rotated by the server itself. */
export function loadEnvironmentId(dataDir: string): string {
  const file = join(dataDir, "environment-id");
  const existing = readEnvironmentId(file);
  if (existing) return existing;

  const directory = dirname(file);
  mkdirSync(directory, { recursive: true, mode: 0o700 });

  const id = randomUUID();
  const temporaryFile = join(directory, `.environment-id.${process.pid}.${randomUUID()}.tmp`);
  let descriptor: number | undefined;

  try {
    descriptor = openSync(temporaryFile, "wx", 0o600);
    writeFileSync(descriptor, id + "\n", "utf8");
    fsyncSync(descriptor);
    closeSync(descriptor);
    descriptor = undefined;

    try {
      // A hard link publishes atomically without replacing, unlike rename, which overwrites on POSIX.
      linkSync(temporaryFile, file);
      return id;
    } catch (error) {
      if (!hasCode(error, "EEXIST")) throw error;
      const winner = readEnvironmentId(file);
      if (winner) return winner;
      throw new Error(`The environment identity at ${file} disappeared while it was being created.`);
    }
  } finally {
    if (descriptor !== undefined) closeSync(descriptor);
    try {
      unlinkSync(temporaryFile);
    } catch {
    }
  }
}

let stamp: string | undefined;
/** This server's release and, on a Cloud, its image: what it runs changes with either, the engines' CLIs included. */
export function buildStamp(): string {
  stamp ??= [serverVersion(), process.env.OMB_CLOUD_IMAGE?.trim()].filter(Boolean).join(" ");
  return stamp;
}

/** The desktop's own version, else the bundle's package.json (scripts/bundle-server.mjs), else the checkout's. */
export function serverVersion(root = SERVER_ROOT): string {
  const fromEnv = process.env.OMB_APP_VERSION?.trim();
  if (fromEnv) return fromEnv;
  for (const file of [join(root, "package.json"), join(root, "..", "package.json")]) {
    try {
      const version = Reflect.get(Object(JSON.parse(readFileSync(file, "utf8"))), "version");
      if (typeof version === "string" && version) return version;
    } catch {
    }
  }
  return "unknown";
}

const RELEASE_VERSION = /^[0-9]{1,9}\.[0-9]{1,9}\.[0-9]{1,9}(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/;

/** The version to tell the control plane, or none: it records what it is told, and stops serving a public address to a
 * version below its minimum, so a version this server could not read must not stand in for the release it runs. */
export function reportableServerVersion(version = serverVersion()): string | undefined {
  return RELEASE_VERSION.test(version) ? version : undefined;
}

/** How this server was started: the rootless Podman service (its unit sets OMB_PODMAN_SERVICE), the Docker image
 * (OMB_CLI_PREFIX, or Docker's own /.dockerenv), a checkout, npx, or a global install. */
export function serverInstall(env: NodeJS.ProcessEnv = process.env, script = process.argv[1] ?? "", docker = () => existsSync("/.dockerenv")): ServerInstall {
  if (env.OMB_PODMAN_SERVICE?.trim()) return "podman-service";
  const prefix = cliPrefix(env, script);
  if (prefix.includes("docker") || docker()) return "docker";
  if (prefix === "pnpm omb" || script.endsWith(".ts")) return "source";
  return prefix === "npx openmausbot" ? "npx" : "global";
}

/** What a server only its one owner signs in to takes from that owner's own desktop by default: told in the owner's own
 * /api/auth/session answer, never in the description anyone may read before pairing. */
export const OWNER_LENDING = Object.freeze({ sharedComputers: true, lendingDetails: true, commandTimeouts: true, longCommands: true, fileEdits: true, lentMcp: true, mcpCaller: true } as const);

export function environmentDescriptor(input: { environmentId: string; desktopManaged: boolean; emailSignIn?: boolean; sharedComputers?: boolean; cloudHome?: boolean; cloudTeam?: boolean; ownHome?: boolean; label?: string }): EnvironmentDescriptor {
  return {
    environmentId: input.environmentId,
    label: input.label?.trim() || process.env.OMB_ENVIRONMENT_LABEL?.trim() || process.env.OMB_SERVER_NAME?.trim() || hostname(),
    platform: process.platform,
    version: serverVersion(),
    capabilities: {
      remoteSessions: true,
      // Never advertise a protocol this server would refuse.
      // lendingDetails: a lent computer may say its platform, and this server remembers what was lent to it.
      ...(input.sharedComputers === true ? { sharedComputers: true as const, lendingDetails: true as const, commandTimeouts: true as const, longCommands: true as const, fileEdits: true as const } : {}),
      ...(input.sharedComputers === true && input.cloudHome === true ? { deviceLink: true as const } : {}),
      ...(input.sharedComputers === true && input.cloudTeam !== true ? { lentMcp: true as const, mcpCaller: true as const } : {}),
      ...(input.sharedComputers === true && input.cloudHome === true && input.cloudTeam !== true ? { myChromeLink: true as const, computerAsks: true as const } : {}),
      ...(input.cloudHome === true ? { cloudHome: true as const, move: 1 as const } : {}),
      ...(input.ownHome === true && input.cloudHome !== true ? { move: 1 as const } : {}),
      ...((input.cloudHome === true && input.cloudTeam !== true) || input.desktopManaged ? { moveBack: 1 as const } : {}),
      ...(input.cloudHome === true && input.cloudTeam === true ? { cloudTeam: true as const } : {}),
      selfUpdate: input.desktopManaged ? "desktop-managed" : "operator",
      ...(input.desktopManaged ? {} : { install: serverInstall() }),
      emailSignIn: input.emailSignIn === true,
      jobs: true,
    },
  };
}