Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Tell a paired phone the desktop's version on /api/health and /api/companion/endpoints (#5761)
Milind Soni9b702058cbc5
diff --git a/companion/src/index.ts b/companion/src/index.tsindex 08f00e2f21..198d9ce0ed 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -155,6 +155,7 @@ const proxy = createProxyHandler({authenticate: (token) => devices.authenticate(token),redeem: (code, deviceName, pairRequestId) => devices.redeem(code, deviceName, pairRequestId),serverName: machineName,+ version: process.env.OMB_APP_VERSION,hosts: () => hostCandidates(),endpoints: () => companionEndpointCandidates(COMPANION_PORT, undefined, undefined, hostedUrl),connected: connectedDevices.open,diff --git a/companion/src/proxy.ts b/companion/src/proxy.tsindex 41a91af107..56dc651ec9 100644--- a/companion/src/proxy.ts+++ b/companion/src/proxy.ts@@ -40,6 +40,8 @@ export interface ProxyOptions {pairRequestId?: unknown,) => { token: string; device: unknown } | { error: string };serverName: () => string;+ /** The desktop app's version: told only to a paired device. */+ version?: string;/** Every host the phone could dial later, best first, sent with the pairing* response as an advisory fallback list. */hosts?: () => string[];@@ -66,6 +68,8 @@ const UPDATE_APP = { error: "update_app" } as const;const PAIRING_SESSION_PATHS = new Set(["POST /api/pair", "GET /api/health"]);+const RELEASE_VERSION = /^[0-9]{1,9}\.[0-9]{1,9}\.[0-9]{1,9}(-[0-9A-Za-z.-]{1,64})?(\+[0-9A-Za-z.-]{1,64})?$/;+/** A token presented inside a session must belong to the device whose psk opened it. */function e2eRefusal(context: E2EContext, method: string, path: string, deviceId: string | undefined): string | null {if (context.peer.kind === "pairing") return PAIRING_SESSION_PATHS.has(`${method} ${path}`) ? null : "pair this phone first";@@ -382,9 +386,10 @@ export function createProxyHandler(options: ProxyOptions) {const capabilityStreams = new Map<string, Set<() => void>>();/** Each device's open `/api/events` streams, for the events the sidecar itself sends. */const eventStreams = new Map<string, Set<(event: string) => void>>();+ const version = options.version !== undefined && RELEASE_VERSION.test(options.version) ? options.version : undefined;const endpointsFor = (deviceId: string | null) => {const descriptor = options.e2eDescriptor?.(deviceId) ?? null;- return { ...endpointSnapshot(options), ...(descriptor ? { e2e: descriptor } : {}) };+ return { ...endpointSnapshot(options), ...(version ? { version } : {}), ...(descriptor ? { e2e: descriptor } : {}) };};const handle = function handle(req: IncomingMessage, res: ServerResponse, listener: ProxyListener = "lan"): void {const target = requestTarget(req.url);@@ -552,7 +557,7 @@ export function createProxyHandler(options: ProxyOptions) {return;}finished = true;- sendJson(res, 200, { app: "openmausbot" });+ sendJson(res, 200, { app: "openmausbot", ...(device && version ? { version } : {}) });});return;}diff --git a/companion/test/proxy.test.ts b/companion/test/proxy.test.tsindex e212a0b085..3c2917abe0 100644--- a/companion/test/proxy.test.ts+++ b/companion/test/proxy.test.ts@@ -2,7 +2,7 @@// live in the seam between them.import { spawn, type ChildProcess } from "node:child_process";import { createServer, request, type IncomingMessage, type Server } from "node:http";-import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";@@ -17,6 +17,7 @@ import { workerPort } from "../../server/testing/worker-port.ts";const HERE = dirname(fileURLToPath(import.meta.url));const ROOT = join(HERE, "..", "..");+const DESKTOP_VERSION = (JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")) as { version: string }).version;/** Candidates from a fixed range below every platform's ephemeral range* (`listen(0)` lands in the 49152+ churn on macOS and Windows), each verified@@ -148,6 +149,7 @@ beforeAll(async () => {? { token: TOKEN, device: { id: "d1", name: String(deviceName) } }: { error: "that code is not right" },serverName: () => "Test computer",+ version: DESKTOP_VERSION,connected: connectedDevices.open,}),);@@ -247,6 +249,13 @@ describe("the sidecar in front of an unmodified harness", () => {expect(JSON.stringify(health.body)).not.toContain("static");});+ it("tells a paired device the desktop's version, and nobody else", async () => {+ expect(await fetch(`${HARNESS}/api/health`).then((reply) => reply.json())).toMatchObject({ app: "openmausbot", version: DESKTOP_VERSION });+ expect((await device("GET", "/api/health")).body).toEqual({ app: "openmausbot", version: DESKTOP_VERSION });+ expect((await device("GET", "/api/health", { token: "omb_wrong" })).body).toEqual({ app: "openmausbot" });+ expect((await device("GET", "/api/companion/endpoints")).body).toEqual({ serverName: "Test computer", endpoints: [], version: DESKTOP_VERSION });+ });+it("refuses what a device has no business doing, by default", async () => {expect((await device("PUT", "/api/config", { body: { xai: { apiKey: "x" } } })).status).toBe(403);expect((await device("GET", "/api/devices")).status).toBe(403);@@ -1040,3 +1049,31 @@ describe("revoking a capability mid-stream", () => {upstream.close();});});++describe("the desktop version the sidecar reports", () => {+ it("is left out unless it is a release version", async () => {+ const answer = async (version: string | undefined) => {+ const server = createServer(createProxyHandler({+ // No harness on port 1: the endpoint list is the sidecar's own answer.+ harnessPort: 1,+ authenticate: (token) => token === TOKEN ? { cloudDesktopAccess: false, browserControlAccess: false } : null,+ redeem: () => ({ error: "not used" }),+ serverName: () => "Test computer",+ version,+ }));+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ try {+ const port = (server.address() as { port: number }).port;+ const reply = await fetch(`http://127.0.0.1:${port}/api/companion/endpoints`, { headers: { authorization: `Bearer ${TOKEN}` } });+ return (await reply.json()) as { version?: string };+ } finally {+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }+ };+ expect((await answer("0.1.156")).version).toBe("0.1.156");+ expect((await answer("0.1.156-beta.2")).version).toBe("0.1.156-beta.2");+ for (const odd of [undefined, "", "unknown", "0.1", "0.1.156\n", `0.1.156-${"x".repeat(65)}`]) {+ expect(await answer(odd)).not.toHaveProperty("version");+ }+ });+});diff --git a/electron/companion.mjs b/electron/companion.mjsindex 5cff93b3bb..77d3d41e3a 100644--- a/electron/companion.mjs+++ b/electron/companion.mjs@@ -213,6 +213,7 @@ async function start({ resourcesPath, harnessPort, mutationToken, hostedUrl = nudelete childEnvironment.OMB_COMPANION_INTERNAL_ORIGIN;delete childEnvironment.OMB_PHONE_SECRET_PUBLIC_KEY;delete childEnvironment.OMB_COMPANION_TAILNET_NAME;+ childEnvironment.OMB_APP_VERSION = app.getVersion();const settings = companionSettings();const direct = directRoutesOn(settings);childEnvironment.OMB_COMPANION_ROUTES = Object.keys(direct).filter((route) => direct[route]).join(",");diff --git a/server/phone-relay.test.ts b/server/phone-relay.test.tsindex 2d49ea54a2..5c026331ee 100644--- a/server/phone-relay.test.ts+++ b/server/phone-relay.test.ts@@ -18,6 +18,8 @@ import { MAX_RELAY_PHONES, MAX_SESSIONS_PER_PHONE, PHONE_RELAY_KEY_FILE, PHONE_Rimport { requestSource, resolveRequestAuth } from "./request-auth.ts";import { SessionRegistry } from "./sessions.ts";+const SERVER_VERSION = (JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string }).version;+const signingKey = generateKeyPairSync("ed25519").privateKey;const keys = new Map([["k1", ed25519RawPublicKey(signingKey)]]);const NODE = "relay1.openmausbot.com";@@ -185,7 +187,7 @@ describe("phones through MausBot Relay on a server", () => {// A token inside the session must be the one whose key opened it.const other = server.sessions.issue({ label: "Laptop", scopes: ["admin", "client"] });expect(await http(session, "GET", "/api/auth/session", { token: other.token }).then((r) => [r.status, json(r).error])).toEqual([401, "this connection belongs to another device"]);- expect(json(await http(session, "GET", "/api/companion/endpoints", { token: reply.token }))).toEqual({ serverName: "VPS", endpoints: [], e2e: descriptor });+ expect(json(await http(session, "GET", "/api/companion/endpoints", { token: reply.token }))).toEqual({ serverName: "VPS", endpoints: [], version: SERVER_VERSION, e2e: descriptor });session.shutdown();// The window is spent; the phone's own key opens the next session, and a session the relay never admitted cannot.diff --git a/server/phone-relay.ts b/server/phone-relay.tsindex b313e4b211..8d13ba1744 100644--- a/server/phone-relay.ts+++ b/server/phone-relay.ts@@ -22,6 +22,7 @@ import { MANAGED_COMPANION_ENDPOINT_FIELD } from "../electron/managed-companion-import { createRelayTokenService, validRelayGrant, type RelayGrant } from "../electron/relay-token.mjs";import { isLoopbackHost } from "../electron/server-address.mjs";import { writeFileAtomic } from "./atomic.ts";+import { reportableServerVersion } from "./environment.ts";import { bearerToken, PROXY_HEADERS } from "./request-auth.ts";import { isPairingCredential, type SessionRegistry } from "./sessions.ts";import { describeTunnelAccount, FLEET_CREDENTIAL_ENV, fleetCredential, openTunnelCredentials } from "./tunnel.ts";@@ -177,6 +178,7 @@ export function startPhoneRelay(options: PhoneRelayOptions): PhoneRelay | null {return null;}const { sessions, dataDir } = options;+ const version = reportableServerVersion();const holder = tunnelHolder(options.env, dataDir);if (holder) {log(`phone relay: off: ${holder}. Use the relay on a machine signed in with \`openmausbot login --relay\`, which holds no tunnel address.`);@@ -334,7 +336,7 @@ export function startPhoneRelay(options: PhoneRelayOptions): PhoneRelay | null {if (method === "GET" && path === "/api/companion/endpoints") {if (!bearer) return reply(res, 401, { error: "pair this device first" });const route = qrRoute(options.publicOrigin());- return reply(res, 200, { serverName: options.serverName(), endpoints: route.endpoints ?? [], ...(descriptor() ? { e2e: descriptor() } : {}) });+ return reply(res, 200, { serverName: options.serverName(), endpoints: route.endpoints ?? [], ...(version ? { version } : {}), ...(descriptor() ? { e2e: descriptor() } : {}) });}}void pairing.run(context, () => Promise.resolve(options.handle(req, res))).catch(() => {diff --git a/server/routes/status.ts b/server/routes/status.tsindex 3510f7fbc0..068d9e2c8d 100644--- a/server/routes/status.ts+++ b/server/routes/status.ts@@ -6,6 +6,7 @@ import { DATA_DIR, EVENTS_DIR, NATIVE_DIR, instanceConfigs, type AppConfig } froimport { boundRetentionDays, decisionsCsv, readDecisionRange, readDecisions, type DecisionRow } from "../decision-log.ts";import { flushNativeLog } from "../drivers/native.ts";import { editionForMembers, editionStatus, entitled } from "../enterprise.ts";+import { reportableServerVersion } from "../environment.ts";import { fleetAvailable, fleetRequest, fleetSocketPath } from "../fleet-client.ts";import { noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";import { loadPlanUsage, planAccountsFromInstances } from "../plan-usage.ts";@@ -44,13 +45,14 @@ export function createStatusRoutes(deps: StatusRouteDeps): RouteHandler {store, cfg, staticDir: STATIC_DIR, sharedWorkspaceFullAccessEnabled, adminActivityRecording,configStatus, broadcast, browserEngineInstall, browserEngineInstallError,} = deps;+ const version = reportableServerVersion();return async ({ req, res, url, path, method, auth, json, readBody }) => {let m: RegExpMatchArray | null = null;const shown = deps.threadShown?.(auth) ?? (() => true);const decision = deps.records?.decisionRow(auth) ?? ((row: DecisionRow) => row);// The packaged app's port fallback: the forked child proves it is ours by echoing its pid.if (method === "GET" && path === "/api/health") {- return json(res, 200, { app: "openmausbot", pid: process.pid, static: Boolean(STATIC_DIR), capabilities: {+ return json(res, 200, { app: "openmausbot", ...(version ? { version } : {}), pid: process.pid, static: Boolean(STATIC_DIR), capabilities: {guardedMessages: 1, guardedRequests: 1, guardedFullAccess: 1, guardedOnBehalfOf: 1,...(sharedWorkspaceFullAccessEnabled() ? { sharedWorkspaceFullAccess: 1 } : {}),}, ...(deps.boxOn ? { box: deps.boxOn() ? "on" : "off" } : {}) });