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.

14.7 KB
Raw Blame
import { execFileSync } from "node:child_process";
import path from "node:path";
import { describe, expect, it } from "vitest";

// The CLI's dispatch table and its help are the same comment block, so a verb
// that exists in one and not the other is a real bug. These run WITHOUT a server:
// help and unknown-command are the two paths that must never need auth, because
// they are what you reach for when the service is down.
const CLI = path.join(__dirname, "mso");
const run = (...args: string[]) =>
  execFileSync(CLI, args, { encoding: "utf8", env: { ...process.env, MSO_ENV: "/dev/null" } });
const commandOwnerFiles = [
  "scripts/cli/commands-host.sh",
  "scripts/cli/memory-backup.sh",
  "scripts/cli/commands-runtime.sh",
  "scripts/cli/flows.sh",
  "scripts/cli/workflows.sh",
  "scripts/cli/channels.sh",
  "scripts/cli/agent-groups.sh",
  "scripts/cli/commands-state.sh",
  "scripts/cli/organization.sh",
  "scripts/cli/agent-profiles.sh",
  "scripts/cli/config-command.sh",
  "scripts/cli/commands-admin.sh",
];
const commandOwners = () => {
  const fs = require("node:fs") as typeof import("node:fs");
  const repo = path.join(__dirname, "..");
  return commandOwnerFiles.map((rel) => fs.readFileSync(path.join(repo, rel), "utf8")).join("\n");
};

describe("bin/mso", () => {
  it("labels CLI, app, and build versions instead of presenting one ambiguous number", () => {
    const out = run("--version");
    expect(out).toMatch(/^mso CLI \d+\.\d+\.\d+ · app \d+\.\d+\.\d+ · build [0-9a-f]+/);
  });

  it("prints help without logging in", () => {
    const out = run("-h");
    expect(out).toContain("Manef Shell OS");
    expect(out).toContain("Usage: mso");
    for (const verb of ["camoufox", "approve", "service", "api", "exec", "doctor"]) {
      expect(out).toContain(verb);
    }
  });

  it("documents every verb the dispatch table implements", () => {
    const body = commandOwners();
    // Case arms look like `  ls)` / `  camoufox)` / `  devices|device)`. Aliases
    // are split out too — an alias absent from the help is just as unfindable.
    const verbs = [...body.matchAll(/^ {2}([a-z][a-z|-]*)\)/gm)].flatMap((m) => m[1].split("|"));
    expect(verbs.length).toBeGreaterThan(20);
    expect(verbs).toContain("device");
    const help = run("-h");
    // `help`/`-h`/`--help` are the conventional flags every CLI has; they don't
    // need a line in the very help they print.
    const undocumented = verbs.filter(
      (v) => v !== "help" && !v.startsWith("-") && !help.includes(v),
    );
    expect(undocumented).toEqual([]);
  });

  it("documents the owner-only memory backup command", () => { expect(run("memory-backup", "--help")).toContain("create --confirm"); });

  it("prints memory-graph usage instead of the assistant memory verb", () => { expect(run("memory-graph", "--help")).toContain("memory-graph [project]"); });

  it("documents saved-profile lifecycle without starting a request", () => { expect(run("agent-profiles", "--help")).toContain("agent-profiles list|create|edit|clone|default|enable|disable"); });

  it("exits non-zero on an unknown command", () => {
    expect(() => run("definitely-not-a-verb")).toThrow();
  });

  it("keeps docs/CLI.md in sync with the help", () => {
    // docs/CLI.md is generated from this same help text. A doc that silently
    // describes an older CLI is worse than no doc, so staleness fails here
    // rather than being noticed by whoever followed it.
    expect(() =>
      execFileSync("node", [path.join(__dirname, "../scripts/gen-cli-docs.mjs"), "--check"], {
        encoding: "utf8",
      }),
    ).not.toThrow();
  });

  // "Covers every need" is only true if it stays true. Every API route must be
  // reachable by a named verb, except the ones a shell genuinely cannot drive.
  it("has a named verb for every API route", () => {
    const fs = require("node:fs") as typeof import("node:fs");
    const repo = path.join(__dirname, "..");
    const walk = (dir: string): string[] =>
      fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
        const p = path.join(dir, e.name);
        return e.isDirectory() ? walk(p) : e.name === "route.ts" ? [p] : [];
      });
    // (method, path) pairs, not paths. A path-only check passed while POST
    // /managed-apps/[id] (start/stop/restart/backup), DELETE
    // .../jobs/[jobId] and GET /api/skills?name= had no verb at all — the file
    // merely mentioned the path somewhere for a DIFFERENT method.
    const files = walk(path.join(repo, "app/api"));
    const routes = files.flatMap((p) => {
      const route = "/" + path.relative(repo, p).replace(/^app\//, "").replace(/\/route\.ts$/, "");
      const src = fs.readFileSync(p, "utf8");
      return [...src.matchAll(/export async function (GET|POST|PUT|PATCH|DELETE)\b/g)].map(
        (m) => `${m[1]} ${route}`,
      );
    });
    const cli = [
      fs.readFileSync(CLI, "utf8"),
      fs.readFileSync(path.join(repo, "scripts/cli/transport.sh"), "utf8"),
      fs.readFileSync(path.join(repo, "scripts/cli/commands.sh"), "utf8"),
      ...commandOwnerFiles.map((rel) => fs.readFileSync(path.join(repo, rel), "utf8")),
      fs.readFileSync(path.join(repo, "scripts/mso-cli-agent.sh"), "utf8"),
      fs.readFileSync(path.join(repo, "scripts/cli/ai-provider-auth.sh"), "utf8"),
      fs.readFileSync(path.join(repo, "scripts/mso-cli-integrations.sh"), "utf8"),
    ].join("\n");

    // Not reachable from a shell, each for its own reason:
    //  • /api/sw is fetched by the browser to install the service worker.
    //  • the managed-app proxy exists to be iframed.
    //  • /api/auth/devices reads the same store `mso device list` reads straight
    //    off disk, which keeps working while the service is down.
    // OAuth is NOT here any more: it is a device-code POST, not a redirect, so
    // `mso oauth <provider> start|poll` covers it.
    const browserOnly = [
      "POST /api/v1/integrations/transfer", // File/passphrase input belongs to the authenticated browser, opened by mso integrations transfer.
      // Per-owner Composio session (both methods); its MCP headers are the credential.
      "/api/v1/integrations/composio/session",
      // Credential input is delegated to a write-only browser capability; the
      // named CLI setup verb opens that form without placing keys in shell/tool JSON.
      "POST /api/integrations/setup",
      // Google web OAuth needs a bound browser cookie; unlike device-code OAuth,
      // mso integrations authorize opens the native consent UI. Neither this
      // browser start nor Google's redirect callback may expose codes to a shell.
      "POST /api/integrations/google/start",
      "GET /api/integrations/google/callback",
      "GET /api/sw",
      "GET /api/v1/shell-apps/[id]/session", // Browser-only, origin-bound handoff into a reviewed app; no credential-returning CLI verb.
      "POST /api/v1/channels/telegram/[id]", // Provider callback: requires Telegram webhook signature, not a user CLI action.
      "POST /api/v1/channels/discord/[id]", // Provider callback: requires Discord Ed25519 signature, not a user CLI action.
      "/api/v1/managed-apps/[id]/proxy/[[...path]]",
      "/api/auth/devices",
      // Settings → Account owns display name, icon, and password rotation.
      // Passwords stay in OS_LOGIN_PASSWORD and must not be placed on a shell argv.
      "/api/auth/account",
      "/api/auth/password",
      // The upload endpoint is the browser's half of Settings → Account: it converts an
      // image to WebP/ICO and stores it. The CLI has no image pipeline and no verb that
      // would justify one; `mso` never needs to upload an avatar over argv.
      "/api/auth/account/icon",
      // The update-automation route exists for the Settings card. `mso update --auto`
      // and `--channel` call the SAME lib/host/update-automation module directly, so a
      // CLI verb over HTTP would be a second, drifting implementation of "enabled".
      "/api/v1/sys/update/automation",
      // Internal transport between scripts/mso-agent.mjs and the authenticated
      // server-side MCP catalog. It is not a user-facing CLI verb by design.
      "/api/v1/agent-tools",
      "POST /api/internal/socket-policy", // Private Node-to-Next policy RPC, authenticated by a fresh per-process secret.
    ];

    // The CLI writes each call as `jget "/path"` / `jpost "/path"` / `jdel "/path"`,
    // so the helper name carries the method. `reqraw` and a bare `req` are the
    // escape hatches for the calls the json helpers cannot make — binary bodies
    // (fs/raw, fs/zip), a live SSE stream (term/stream) and multipart (fs/upload)
    // — and `curl` covers doctor's own probes. They are listed under the method
    // they actually issue, so this stays a method check, not a free pass.
    const HELPERS: Record<string, string[]> = {
      GET: ["jget", "reqraw", "curl"],
      // secret_post is the stdin-bodied POST used for credentials and now for
      // model discovery (which carries a pasted API key, so it must stay off argv).
      POST: ["jpost", "req -F", "-X POST", "secret_post"],
      PUT: ["jput"],
      PATCH: ["jpatch"],
      DELETE: ["jdel"],
    };

    const uncovered = routes.filter((mr) => {
      const [method, route] = mr.split(" ");
      if (browserOnly.some((b) => mr === b || route === b)) return false;
      // Dynamic segments are built by interpolation, so match on the literal
      // chunks either side of a [param].
      const parts = route.split("/").filter((s) => s && !s.startsWith("["));
      const stem = `/${parts.join("/")}`;
      const tail = parts[parts.length - 1];
      return !HELPERS[method].some((h) => {
        const i = cli.indexOf(h);
        if (i < 0) return false;
        // Look for the helper and the path on the same line.
        return cli
          .split("\n")
          .some((line) => line.includes(h) && (line.includes(stem) || line.includes(`/${tail}"`) || line.includes(`/${tail}?`) || line.includes(`/${tail}/`)));
      });
    });
    expect(uncovered).toEqual([]);
    expect(routes.length).toBeGreaterThan(50);
  });

  it("refuses `device revoke all` without --yes, and leaves the store intact", () => {
    const fs = require("node:fs") as typeof import("node:fs");
    const os = require("node:os") as typeof import("node:os");
    const store = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "mso-dev-")), "devices.json");
    const before = JSON.stringify({ approved: { ["a".repeat(32)]: { label: "x" } }, pending: {} });
    fs.writeFileSync(store, before);
    const withStore = (...args: string[]) =>
      execFileSync(CLI, args, {
        encoding: "utf8",
        env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
      });

    // Revoking everything signs every browser out; one keystroke from `revoke <id>`.
    expect(() => withStore("device", "revoke", "all")).toThrow();
    expect(fs.readFileSync(store, "utf8")).toBe(before);

    // "-yes" is one character from "--yes"; a near miss must not silently count
    // as confirmation, and must say which flag was actually seen.
    let stderr = "";
    try {
      withStore("device", "revoke", "all", "-yes");
    } catch (e) {
      stderr = String((e as { stderr?: Buffer }).stderr ?? "");
    }
    expect(stderr).toContain('you passed "-yes"');
    expect(fs.readFileSync(store, "utf8")).toBe(before);

    withStore("device", "revoke", "all", "--yes");
    expect(JSON.parse(fs.readFileSync(store, "utf8")).approved).toEqual({});
  });

  it("fails closed instead of replacing a corrupt device allowlist", () => {
    const fs = require("node:fs") as typeof import("node:fs");
    const os = require("node:os") as typeof import("node:os");
    const store = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "mso-dev-")), "devices.json");
    const corrupt = "{ this is not valid json";
    fs.writeFileSync(store, corrupt);
    const id = "e".repeat(32);

    expect(() =>
      execFileSync(CLI, ["device", "approve", id, "test"], {
        encoding: "utf8",
        env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
      }),
    ).toThrow();
    expect(fs.readFileSync(store, "utf8")).toBe(corrupt);
  });

  it("prints a paste-ready command under every device, quoted safely", () => {
    const fs = require("node:fs") as typeof import("node:fs");
    const os = require("node:os") as typeof import("node:os");
    const store = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "mso-dev-")), "devices.json");
    const pendingId = "c".repeat(32);
    const approvedId = "d".repeat(32);
    // A label with a quote AND a space is the case that breaks naive `"${label}"`
    // interpolation — the pasted line would split into several arguments.
    const nasty = 'Chrome "work" laptop';
    fs.writeFileSync(
      store,
      JSON.stringify({
        approved: { [approvedId]: { label: "phone" } },
        pending: { [pendingId]: { label: nasty, ip: "10.0.0.1", attempts: 1 } },
      }),
    );
    const withStore = (...args: string[]) =>
      execFileSync(CLI, args, {
        encoding: "utf8",
        env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
      });

    const list = withStore("device", "list");
    expect(list).toContain(`mso device approve ${pendingId} ${JSON.stringify(nasty)} --role viewer`);
    expect(list).toContain(`mso device revoke ${approvedId}`);
    // The bare id stays on its own line — way (1) still works.
    expect(list).toMatch(new RegExp(`^ {2}${pendingId} `, "m"));

    expect(withStore("device", "pending")).toContain(
      `mso device approve ${pendingId} ${JSON.stringify(nasty)} --role viewer`,
    );
  });

  it("accepts -y as confirmation and reports what is left after a single revoke", () => {
    const fs = require("node:fs") as typeof import("node:fs");
    const os = require("node:os") as typeof import("node:os");
    const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mso-dev-"));
    const store = path.join(dir, "devices.json");
    const ids = ["a".repeat(32), "b".repeat(32)];
    const seed = () =>
      fs.writeFileSync(
        store,
        JSON.stringify({ approved: { [ids[0]]: { label: "one" }, [ids[1]]: { label: "two" } }, pending: {} }),
      );
    const withStore = (...args: string[]) =>
      execFileSync(CLI, args, {
        encoding: "utf8",
        env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
      });

    seed();
    withStore("device", "revoke", "all", "-y");
    expect(JSON.parse(fs.readFileSync(store, "utf8")).approved).toEqual({});

    // Revoking your last device locks you out of the UI — that has to be loud.
    seed();
    expect(withStore("revoke", ids[0])).toContain("1 device(s) still approved");
    expect(withStore("revoke", ids[1])).toContain("NO devices approved");
  });
});