Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Companion: advertise custom HTTPS endpoints for phone pairing
erywim3bd372ce5c9e
diff --git a/companion/src/control.ts b/companion/src/control.tsindex 8d14b0e5cb..ba2aed3f59 100644--- a/companion/src/control.ts+++ b/companion/src/control.ts@@ -26,6 +26,8 @@ export interface ControlOptions {* leaves Electron's encrypted store. */secretPublicKey?: () => string | null;hostedUrl?: () => string | null;+ /** Custom HTTPS origins from OMB_COMPANION_EXTRA_URL, after the managed hosted route. */+ extraUrls?: () => readonly string[];/** Electron publishes a route after its connector health check succeeds* and withdraws it on connector loss. */setHostedUrl?: (url: string | null) => void;@@ -228,6 +230,8 @@ export function companionState(options: Omit<ControlOptions, "controlToken">) {addresses,name,currentHostedUrl(options),+ undefined,+ options.extraUrls?.() ?? [],),...(secretPublicKey ? { secretPublicKey } : {}),pairing: pairing ? { code: pairing.code, token: pairing.token, expiresAt: pairing.expiresAt } : null,diff --git a/companion/src/endpoints.ts b/companion/src/endpoints.tsindex 6b904fbb96..2799b230fd 100644--- a/companion/src/endpoints.ts+++ b/companion/src/endpoints.ts@@ -20,12 +20,17 @@ export const MAX_COMPANION_ENDPOINTS = 8;export function hostedCompanionUrl(value: string | undefined): string | null {const configured = value?.trim();if (!configured) return null;+ return companionHttpsOrigin(configured, "OMB_COMPANION_HOSTED_URL");+}+/** One origin, or one reason it cannot be a companion route. The variable name+ * is in the message because a typo stops the sidecar before it serves. */+function companionHttpsOrigin(configured: string, name: string): string {let parsed: URL;try {parsed = new URL(configured);} catch {- throw new Error("OMB_COMPANION_HOSTED_URL must be an absolute HTTPS origin");+ throw new Error(`${name} must be an absolute HTTPS origin`);}if (@@ -36,31 +41,46 @@ export function hostedCompanionUrl(value: string | undefined): string | null {parsed.search ||parsed.hash) {- throw new Error("OMB_COMPANION_HOSTED_URL must be an HTTPS origin without a path, credentials, query, or fragment");+ throw new Error(`${name} must be an HTTPS origin without a path, credentials, query, or fragment`);}return parsed.origin;}+/** Custom HTTPS origins in `OMB_COMPANION_EXTRA_URL` (commas or newlines), for a+ * self-hosted reverse proxy in front of this companion. Empty entries are skipped. */+export function extraCompanionUrls(value: string | undefined): string[] {+ const origins = (value ?? "")+ .split(/[\n,]/)+ .map((entry) => entry.trim())+ .filter(Boolean)+ .map((entry) => companionHttpsOrigin(entry, "OMB_COMPANION_EXTRA_URL"));+ return [...new Set(origins)].slice(0, MAX_COMPANION_ENDPOINTS);+}+const httpOrigin = (host: string, port: number): string => {const authority = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;return `http://${authority}:${port}`;};-/** Best first: the hosted HTTPS route when configured, then the direct routes- * in the host list's order, Bonjour last. The cap bounds QR size and the- * connection walk. */+/** Best first: the hosted HTTPS route when configured, then custom HTTPS origins,+ * then the direct routes in the host list's order, Bonjour last. The cap bounds QR+ * size and the connection walk. */export function companionEndpointCandidates(port: number,addresses: string[] = routedAddresses(),magicDnsName: string | null = tailnetName(),hostedUrl: string | null = null,bonjourHost: string | null = directRoutes().wifi ? defaultHostName() : null,+ extraUrls: readonly string[] = [],): CompanionEndpoint[] {const tailscale = tailscaleAddress(addresses);const candidates: CompanionEndpoint[] = [];if (hostedUrl) candidates.push({ url: hostedUrl, kind: "hosted", priority: 0 });+ extraUrls.forEach((url, index) => {+ candidates.push({ url, kind: "hosted", priority: 50 + index });+ });if (tailscale && magicDnsName) {candidates.push({ url: httpOrigin(magicDnsName, port), kind: "tailnet", priority: 100 });}diff --git a/companion/src/index.ts b/companion/src/index.tsindex 08de44113b..a0933a8cba 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -11,7 +11,7 @@ import { createAddressWatcher } from "./advertise-watch.ts";import { createControlServer, hostCandidates, initialControlToken } from "./control.ts";import { createConnectedDeviceTracker } from "./connected-devices.ts";import { DeviceRegistry } from "./devices.ts";-import { companionEndpointCandidates, hostedCompanionUrl } from "./endpoints.ts";+import { companionEndpointCandidates, extraCompanionUrls, hostedCompanionUrl } from "./endpoints.ts";import { tailnetName, tailscaleAddress } from "./listener.ts";import { acceptsConnection, anyDirectRoute, directRoutes, directRoutesFromEnv, routedAddresses, setDirectRoutes } from "./direct-routes.ts";import {@@ -94,6 +94,7 @@ const COMPANION_PORT = num(process.env.OMB_COMPANION_PORT, 8810);const CONTROL_PORT = num(process.env.OMB_CONTROL_PORT, 8811);const SERVICE_TYPE = "_openmausbot._tcp";let hostedUrl = hostedCompanionUrl(process.env.OMB_COMPANION_HOSTED_URL);+const extraUrls = extraCompanionUrls(process.env.OMB_COMPANION_EXTRA_URL);directRoutesFromEnv(process.env);const PRIVATE_ORIGIN = companionOriginSocket(process.env.OMB_COMPANION_INTERNAL_ORIGIN);const SECRET_PUBLIC_KEY = normalizedPhoneSecretPublicKey(@@ -178,7 +179,7 @@ const proxy = createProxyHandler({serverName: machineName,version: process.env.OMB_APP_VERSION,hosts: () => hostCandidates(),- endpoints: () => companionEndpointCandidates(COMPANION_PORT, undefined, undefined, hostedUrl),+ endpoints: () => companionEndpointCandidates(COMPANION_PORT, undefined, undefined, hostedUrl, undefined, extraUrls),connected: connectedDevices.open,e2eDescriptor: (deviceId) => e2e.descriptor(deviceId),e2ePaired: (context, deviceId) => e2e.paired(context, deviceId),@@ -281,6 +282,7 @@ const control = createControlServer({companionPort: COMPANION_PORT,secretPublicKey: () => SECRET_PUBLIC_KEY,hostedUrl: () => hostedUrl,+ extraUrls: () => extraUrls,setHostedUrl: (next) => {hostedUrl = next;},diff --git a/companion/test/control.test.ts b/companion/test/control.test.tsindex 443613e814..80ec959308 100644--- a/companion/test/control.test.ts+++ b/companion/test/control.test.ts@@ -11,6 +11,7 @@ let connectedDeviceIds: string[] = [];let disconnectedDeviceIds: string[] = [];let revokedDeviceIds: string[] = [];const routeBodies: unknown[] = [];+const extraUrls: string[] = [];const CONTROL_TOKEN = "c".repeat(43);let controlToken: string | null = CONTROL_TOKEN;const withToken = { "x-openmausbot-control-token": CONTROL_TOKEN };@@ -40,6 +41,7 @@ beforeAll(async () => {companionPort: 8810,secretPublicKey: () => "BIPBQ12_dWnF1DZLsTZO3Vg0NGjds5-jp9h3jhjr2To7bJelczS0LM82rfXV68PmSJhz2ePosj3fL974XckCpDU",hostedUrl: () => hostedUrl,+ extraUrls: () => extraUrls,setHostedUrl: (next) => {hostedUrl = next;},@@ -358,6 +360,16 @@ describe("hosted endpoint advertisement", () => {expect(withdrawn.body.endpoints.some((endpoint: { kind: string }) => endpoint.kind === "hosted")).toBe(false);});+ it("advertises custom HTTPS origins after the managed hosted route", async () => {+ extraUrls.push("https://relay.example:8443");+ try {+ const hosted = (await ask("GET", "/state")).body.endpoints.filter((endpoint: { kind: string }) => endpoint.kind === "hosted");+ expect(hosted.at(-1)).toEqual({ url: "https://relay.example:8443", kind: "hosted", priority: 50 });+ } finally {+ extraUrls.length = 0;+ }+ });+it("accepts exactly one string-or-null url field", async () => {const headers = { "content-type": "application/json" };for (const body of [diff --git a/companion/test/endpoints.test.ts b/companion/test/endpoints.test.tsindex 6a810c095c..362485a149 100644--- a/companion/test/endpoints.test.ts+++ b/companion/test/endpoints.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vitest";import {companionEndpointCandidates,+ extraCompanionUrls,hostedCompanionUrl,MAX_COMPANION_ENDPOINTS,} from "../src/endpoints.ts";@@ -29,6 +30,36 @@ describe("hostedCompanionUrl", () => {});});+describe("extraCompanionUrls", () => {+ it("reads custom HTTPS origins separated by commas or newlines", () => {+ expect(extraCompanionUrls(" https://relay.example ,\nhttps://relay2.example:8443\n")).toEqual([+ "https://relay.example",+ "https://relay2.example:8443",+ ]);+ expect(extraCompanionUrls(undefined)).toEqual([]);+ expect(extraCompanionUrls(" , \n")).toEqual([]);+ });++ it("normalizes, dedupes and caps the list", () => {+ expect(extraCompanionUrls("https://Relay.Example/ , https://relay.example")).toEqual(["https://relay.example"]);+ const many = Array.from({ length: 10 }, (_, index) => `https://r${index}.example`).join(",");+ expect(extraCompanionUrls(many)).toHaveLength(MAX_COMPANION_ENDPOINTS);+ });++ it("refuses insecure or ambiguous origins, naming the variable", () => {+ for (const value of [+ "http://relay.example",+ "https://user:[email protected]",+ "https://relay.example/companion",+ "https://relay.example?device=one",+ "https://relay.example#pair",+ "not a URL",+ ]) {+ expect(() => extraCompanionUrls(value)).toThrow(/OMB_COMPANION_EXTRA_URL/);+ }+ });+});+describe("companionEndpointCandidates", () => {it("puts hosted HTTPS first, followed by tailnet, LAN, and Bonjour routes", () => {expect(@@ -70,6 +101,32 @@ describe("companionEndpointCandidates", () => {]);});+ it("tries custom HTTPS origins after the managed hosted route and before direct ones", () => {+ expect(+ companionEndpointCandidates(+ 8810,+ ["100.121.5.6", "192.168.1.42"],+ "macbook.tail1234.ts.net",+ "https://device-123.companion.example",+ "openmausbot-abcd1234.local",+ ["https://relay.example", "https://relay2.example:8443"],+ ),+ ).toEqual([+ { url: "https://device-123.companion.example", kind: "hosted", priority: 0 },+ { url: "https://relay.example", kind: "hosted", priority: 50 },+ { url: "https://relay2.example:8443", kind: "hosted", priority: 51 },+ { url: "http://macbook.tail1234.ts.net:8810", kind: "tailnet", priority: 100 },+ { url: "http://192.168.1.42:8810", kind: "lan", priority: 201 },+ { url: "http://openmausbot-abcd1234.local:8810", kind: "bonjour", priority: 300 },+ ]);+ });++ it("keeps one entry when a custom origin repeats the managed hosted route", () => {+ expect(+ companionEndpointCandidates(8810, [], null, "https://device-123.companion.example", null, ["https://device-123.companion.example"]),+ ).toEqual([{ url: "https://device-123.companion.example", kind: "hosted", priority: 0 }]);+ });+it("caps pathological interface lists without losing the Bonjour fallback", () => {const addresses = Array.from({ length: 20 }, (_, index) => `192.168.1.${index + 1}`);const endpoints = companionEndpointCandidates(