Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

7.2 KB
Raw Blame
import "server-only";
import path from "node:path";
import { getManagedAppDefinition } from "./catalog";
import { dockerUsable } from "./docker";
import { managedAppInstallSupport } from "./host-compatibility";
import { userBusUnavailable } from "./user-bus";
import { startManagedAppJob } from "./jobs";
import { getManagedApp } from "./manager";
import { managedAppOrigin } from "./origin";
import { findProvider } from "./providers";
import type { ManagedAppId, ManagedAppJob } from "./types";

// Installing a managed app used to be something MSO showed you rather than did,
// on the grounds that both upstream installers were interactive. That stopped
// being true: `hermes setup --non-interactive` is documented as "use
// defaults/env vars", and `openclaw onboard --non-interactive` exists behind an
// `--accept-risk` acknowledgement. So this file is the missing verb — the same
// job machinery update/uninstall/restore already use, pointed at scripts/managed-app-install.
//
// The one rule that shapes everything here: THE KEY NEVER TOUCHES argv. A job's
// argv is persisted in its record, returned by the jobs API and written to the
// audit log; `options.env` is none of those things (it is merged over childEnv()
// inside job-child.ts and dropped). So the argv stays two elements long and the
// secret travels in the environment.

/** Where the sequence lives. Resolved against the server's cwd — mso runs
 *  with `WorkingDirectory` at the repo root, and the script ships with the repo,
 *  so a fresh clone on another machine needs no path configuration. */
const INSTALL_SCRIPT = path.join(process.cwd(), "scripts", "managed-app-install");

/** Hermes fetches uv, a Python, Node and ffmpeg before it does anything of its
 *  own, so it needs a budget several times OpenClaw's `npm i -g`. Both stay
 *  under the job layer's 1 h ceiling. */
const INSTALL_TIMEOUT_MS: Record<ManagedAppId, number> = { hermes: 2_700_000, openclaw: 900_000, "9router": 900_000, orca: 900_000 };

/** A key is never inspected beyond this: it is opaque upstream credential
 *  material, so the only questions worth asking are "could it break the
 *  environment block" and "is it plausibly a key at all". A control character
 *  cannot appear in a real one and is the only shape that could do damage. */
function assertKeyShape(key: string): void {
  if (key.length > 512 || /\p{Cc}/u.test(key)) throw new Error("that does not look like an API key");
}

export interface InstallOptions {
  /** Omitted = install with no provider configured. The app comes up and says so;
   *  the same panel can supply one afterwards. */
  provider?: string | null;
  apiKey?: string | null;
  /** `loopback` unless the operator asks otherwise. Only this host wants `lan`,
   *  and only because Traefik has to reach the gateway from a container. */
  bind?: string | null;
}

const BINDS = new Set(["loopback", "lan", "tailnet", "auto"]);

/** Orca's pinned release is linux-x64-glibc only, so the support gate must prove
 *  glibc rather than assume it. `process.report` is Node's own reading. */
function hostUsesGlibc(): boolean {
  try {
    const report = process.report?.getReport() as { header?: { glibcVersionRuntime?: string } } | undefined;
    return typeof report?.header?.glibcVersionRuntime === "string";
  } catch {
    return false;
  }
}

/** Start an install job. Refuses when the app is already installed: the upstream
 *  installers are re-runnable, but "install" arriving at a live app is a UI bug
 *  or a stale page, and re-running one restarts services under whoever is using
 *  them. Update is the verb for an app that is already there. */
export async function startInstall(id: ManagedAppId, options: InstallOptions = {}): Promise<ManagedAppJob> {
  const definition = getManagedAppDefinition(id);
  const view = await getManagedApp(id);
  if (view.installed) throw new Error(`${definition.name} is already installed — use Update instead`);
  const support = managedAppInstallSupport(definition, {
    platform: process.platform,
    arch: process.arch,
    glibc: hostUsesGlibc(),
    userSystemd: !userBusUnavailable(),
    docker: definition.installBackends.includes("docker") && await dockerUsable(),
  });
  if (!support.supported) throw new Error(support.reason ?? "managed app installer unsupported on this host");

  // Fail CLOSED on an unreadable reading. This guard's own reason for existing
  // (above) is that re-running an installer "restarts services under whoever is
  // using them" — and Hermes' upstream installer recreates the venv that the
  // RUNNING gateway is executing from. `installed: false` arriving because MSO
  // cannot see user services is exactly when that is most destructive, so
  // "I could not check" must not be treated as "it is not there".
  if (view.diagnostic) {
    throw new Error(`cannot determine whether ${definition.name} is installed — refusing to run the installer. ${view.diagnostic}`);
  }

  const env: Record<string, string> = {};
  const bind = options.bind ?? "loopback";
  if (!BINDS.has(bind)) throw new Error("unsupported gateway bind mode");
  // Orca's browser client is only ever framed through the split-origin proxy, so
  // a non-loopback bind would expose the runtime directly. Refuse it explicitly
  // even though sibling installers accept LAN/tailnet binds.
  if (id === "orca" && bind !== "loopback") throw new Error("Orca install supports loopback only; refusing a non-loopback bind");
  env.MSO_INSTALL_GATEWAY_BIND = bind;

  const key = options.apiKey?.trim();
  // Orca ships no provider configuration and stores no API key; a key would only
  // be silently dropped, so refuse rather than claim a configured install.
  if (id === "orca" && (key || options.provider)) throw new Error("Orca does not accept a provider or API key");

  // Where MSO will frame this app. OpenClaw's Control UI keeps its own origin
  // allowlist and rejects the socket before it opens otherwise — a healthy gateway
  // that the dashboard cannot talk to. Orca needs the same origin: the managed
  // runtime advertises exactly this WSS endpoint, and there is NO same-origin
  // fallback, so an install without it cannot produce a usable browser session.
  const appOrigin = managedAppOrigin(id);
  if (id === "orca" && !appOrigin) {
    throw new Error("Orca install requires a configured split app origin (NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE); refusing to install a runtime the browser cannot reach");
  }
  if (appOrigin) env.MSO_INSTALL_APP_ORIGIN = appOrigin;

  if (key) {
    const provider = findProvider(options.provider);
    if (!provider) throw new Error("unsupported provider");
    if (!provider.apps.includes(id)) throw new Error(`${provider.label} is not supported by this application`);
    assertKeyShape(key);
    env.MSO_INSTALL_PROVIDER = provider.id;
    // The provider's documented environment variable is inherited only by the
    // installer child. Hermes reads it directly; OpenClaw stores an env SecretRef.
    // The generic MSO key remains for Hermes' private .env persistence path.
    env.MSO_INSTALL_API_KEY = key;
    env[provider.envVar] = key;
  }

  return startManagedAppJob({
    applicationId: id,
    kind: "install",
    argv: [INSTALL_SCRIPT, id],
    env,
    timeoutMs: INSTALL_TIMEOUT_MS[id],
  });
}