Skip to content

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

Companion: let a paired phone set provider keys and sign engines in

aivsomkar30915ca1ef3f
diff --git a/companion/src/routes.ts b/companion/src/routes.ts
index bdba698a78..46a6ce67ec 100644
--- a/companion/src/routes.ts
+++ b/companion/src/routes.ts
@@ -80,13 +80,19 @@ export function isBrowserControlAccess(method: string, path: string): boolean {
/** Every request the iOS app makes, and nothing else. Paths arrive undecoded
* and are anchored at both ends, so an encoded traversal fails to match. */
const ALLOWED: ReadonlyArray<{ method: string; path: RegExp }> = [
- // Configured-or-not booleans, never keys; the write side is refused below.
+ // Configured-or-not booleans, never keys.
{ method: "GET", path: /^\/api\/config$/ },
+ // The harness takes only provider keys from a paired device; every other setting stays on the host.
+ { method: "PUT", path: /^\/api\/config$/ },
+ { method: "POST", path: /^\/api\/keys\/test$/ },
{ method: "GET", path: /^\/api\/events$/ },
{ method: "GET", path: /^\/api\/instances$/ },
// The harness refuses it while any Claude turn runs. Instance ids may carry
// dots, so a dots-only segment is refused outright.
{ method: "POST", path: /^\/api\/instances\/(?!\.+\/)[\w.-]+\/claude-update$/ },
+ // Engine sign-in. The harness refuses browser-based methods from a paired device. Dots-only ids are refused as above.
+ { method: "POST", path: /^\/api\/instances\/(?!\.+\/)[\w.-]+\/auth\/(?:start|complete|cancel|sign-out)$/ },
+ { method: "GET", path: /^\/api\/instances\/(?!\.+\/)[\w.-]+\/auth\/status$/ },
{ method: "GET", path: /^\/api\/team-map$/ },
// Sidecar-owned: the proxy answers it locally.
{ method: "GET", path: /^\/api\/companion\/endpoints$/ },
@@ -275,7 +281,7 @@ const EXPLAINED: ReadonlyArray<{ path: RegExp; error: string }> = [
// Losing the phone must not mean losing the ability to lock it out.
error: "Remote access settings are managed on the host computer",
},
- { path: /^\/api\/config$/, error: "API keys can only be changed on your computer" },
+ { path: /^\/api\/config$/, error: "this setting is changed on your computer" },
{ path: /^\/api\/local-computer(\/|$)/, error: "the Local VM is set up on your computer" },
{
// Creating one exposes an endpoint to the internet.
diff --git a/companion/test/routes.test.ts b/companion/test/routes.test.ts
index c494d11ae4..281f7c423e 100644
--- a/companion/test/routes.test.ts
+++ b/companion/test/routes.test.ts
@@ -157,7 +157,6 @@ describe("what it may not", () => {
it("refuses host configuration, and says where it happens", () => {
for (const [method, path] of [
- ["PUT", "/api/config"],
["PATCH", "/api/config"],
["GET", "/api/devices"],
["GET", "/api/companion"],
@@ -342,7 +341,7 @@ describe("what it may not", () => {
expect(allowed("GET", "/api/sidebar-sections")).toBe(false);
expect(allowed("PATCH", "/api/sidebar-sections")).toBe(false);
expect(allowed("POST", "/api/sidebar-sections/extra")).toBe(false);
- expect(allowed("PUT", "/api/config")).toBe(false);
+ expect(allowed("PATCH", "/api/config")).toBe(false);
expect(allowed("GET", "/api/attachments/../config.json")).toBe(false);
expect(allowed("GET", "/api/files")).toBe(false);
expect(allowed("POST", "/api/files/anything")).toBe(false);
@@ -374,9 +373,34 @@ describe("what it may not", () => {
}
});
+ it("lets a phone set provider keys and sign engines in, and nothing wider", () => {
+ for (const [method, path] of [
+ ["PUT", "/api/config"],
+ ["POST", "/api/keys/test"],
+ ["POST", "/api/instances/codex/auth/start"],
+ ["POST", "/api/instances/claude.work/auth/complete"],
+ ["POST", "/api/instances/codex/auth/cancel"],
+ ["POST", "/api/instances/codex/auth/sign-out"],
+ ["GET", "/api/instances/codex/auth/status"],
+ ] as Array<[string, string]>) {
+ expect(allowed(method, path), `${method} ${path}`).toBe(true);
+ }
+ for (const [method, path] of [
+ ["POST", "/api/instances/../auth/start"],
+ ["GET", "/api/instances/codex/auth/start"],
+ ["POST", "/api/instances/codex/auth/status"],
+ ["POST", "/api/instances/codex/install"],
+ ["PUT", "/api/config/extra"],
+ ["PATCH", "/api/config"],
+ ] as Array<[string, string]>) {
+ expect(allowed(method, path), `${method} ${path}`).toBe(false);
+ }
+ expect(ask("PATCH", "/api/config")?.error).toBe("this setting is changed on your computer");
+ });
+
it("allows only the four Live call routes, never the key", () => {
expect(ask("POST", "/api/live/summary")?.status).toBe(404);
- expect(ask("PUT", "/api/config")?.status).toBe(403);
+ expect(ask("PATCH", "/api/config")?.status).toBe(403);
expect(allowed("PUT", "/api/live/settings")).toBe(false);
expect(allowed("GET", "/api/live/settings")).toBe(false);
expect(allowed("GET", "/api/live/session")).toBe(false);
diff --git a/server/provider-key-check.ts b/server/provider-key-check.ts
index 8b5fb3e216..a958250151 100644
--- a/server/provider-key-check.ts
+++ b/server/provider-key-check.ts
@@ -10,6 +10,23 @@ export type ProviderKeyVerdict =
export const PROVIDER_KEY_KINDS: readonly ProviderKeyKind[] = ["anthropic", "openai", "openrouter", "openaiCompat", "xai", "mistral", "cerebras", "groq", "greenference", "modelgo", "meta"];
+/** What a paired phone may write per provider: a key, never a URL (`openaiCompat` carries one, so it is absent). */
+const PHONE_KEY_FIELDS: Readonly<Record<string, Readonly<Record<string, "string" | "boolean">>>> = {
+ anthropic: { key: "string", everyClaudeBot: "boolean" },
+ ...Object.fromEntries(PROVIDER_KEY_KINDS.filter((kind) => kind !== "anthropic" && kind !== "openaiCompat").map((kind) => [kind, { key: "string" }])),
+};
+
+/** True when `body` sets only provider keys, so a paired phone's config write cannot widen into anything else. */
+export function isPhoneKeyPatch(body: unknown): boolean {
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return false;
+ const entries = Object.entries(body);
+ return entries.length > 0 && entries.every(([kind, entry]) => {
+ const fields = Object.hasOwn(PHONE_KEY_FIELDS, kind) ? PHONE_KEY_FIELDS[kind] : undefined;
+ return fields !== undefined && typeof entry === "object" && entry !== null && !Array.isArray(entry)
+ && Object.entries(entry).every(([name, value]) => Object.hasOwn(fields, name) && typeof value === fields[name]);
+ });
+}
+
const DEFAULT_URLS: Record<ProviderKeyKind, string> = {
anthropic: "https://api.anthropic.com",
openai: "https://api.openai.com/v1",
diff --git a/server/request-auth.test.ts b/server/request-auth.test.ts
index 69d5d45859..2c11ad7ae2 100644
--- a/server/request-auth.test.ts
+++ b/server/request-auth.test.ts
@@ -333,7 +333,7 @@ describe("resolveRequestAuth", () => {
for (const overrides of forged) expect(check("POST", "/api/bots/b/read", overrides).auth).toBeNull();
expect(check("POST", "/api/bots/b/read", {}, "").auth).toBeNull();
for (const [method, path] of [
- ["PUT", "/api/config"], ["POST", "/api/auth/pairing"],
+ ["PATCH", "/api/config"], ["POST", "/api/auth/pairing"],
["POST", "/api/internal/anything"], ["GET", "/api/auth/sessions"],
["POST", "/api/not-yet-supported"],
]) expect(check(method, path).auth, path).toBeNull();
diff --git a/server/routes/config-phone-keys.test.ts b/server/routes/config-phone-keys.test.ts
new file mode 100644
index 0000000000..492e43577a
--- /dev/null
+++ b/server/routes/config-phone-keys.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+
+import type { RequestAuth } from "../request-auth.ts";
+import { createConfigRoutes, type ConfigRouteDeps } from "./config.ts";
+
+const phone: RequestAuth = { kind: "loopback", scopes: ["admin", "client"], companionDevice: "phone-1" };
+const desktop: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };
+
+async function put(auth: RequestAuth, body: unknown, method = "PUT") {
+ const replies: Array<{ status: number; body: unknown }> = [];
+ // A busy provider config answers 409 only after the phone guard, so a 409 means the guard let it through.
+ const route = createConfigRoutes({ hostedModels: false, providerConfigBusy: { get: () => true } } as unknown as ConfigRouteDeps);
+ await route({
+ req: {}, res: {}, url: new URL("http://host/api/config"), path: "/api/config", method, auth,
+ json: (_res: unknown, status: number, reply: unknown) => { replies.push({ status, body: reply }); },
+ readBody: async () => body,
+ } as unknown as Parameters<typeof route>[0]);
+ return replies[0];
+}
+
+const SENTENCE = "From a phone, only API keys can be changed. Change other settings on your computer.";
+
+describe("config writes from a paired phone", () => {
+ it.each([
+ { mistral: { key: "k" } },
+ { openai: { key: "" } },
+ { anthropic: { key: "k", everyClaudeBot: false } },
+ ])("lets a key-only patch past the guard: %j", async (body) => {
+ expect((await put(phone, body))?.status).toBe(409);
+ });
+
+ it.each([
+ { signIn: { admins: ["[email protected]"] } },
+ { browserEngine: { egress: { proxy: "socks5://127.0.0.1:1080" } } },
+ { openaiCompat: { key: "k" } },
+ { openai: { key: "k", url: "http://evil.test/v1" } },
+ { mistral: { key: "k", everyClaudeBot: true } },
+ { mistral: { key: 5 } },
+ { mistral: { key: "k" }, signIn: { admins: [] } },
+ { mistral: "k" },
+ { toString: { key: "k" } },
+ {},
+ ])("refuses anything else: %j", async (body) => {
+ expect(await put(phone, body)).toEqual({ status: 403, body: { error: SENTENCE } });
+ expect(await put(phone, body, "PATCH")).toEqual({ status: 403, body: { error: SENTENCE } });
+ });
+
+ it("leaves the desktop's own write alone", async () => {
+ expect(await put(desktop, {})).toEqual({ status: 400, body: { error: "nothing to save" } });
+ expect((await put(desktop, { signIn: { admins: [] } }))?.status).toBe(409);
+ });
+});
diff --git a/server/routes/config.ts b/server/routes/config.ts
index 9a2f626b95..8d357ad4c4 100644
--- a/server/routes/config.ts
+++ b/server/routes/config.ts
@@ -34,7 +34,7 @@ import type { ProviderRegistry } from "../harness/registry.ts";
import { HOSTED_PROVIDER_SETTINGS_ERROR } from "../hosted-models.ts";
import { forgetKey } from "../key-rejections.ts";
import type { ComputerIdleTimer } from "../computer-idle.ts";
-import { PROVIDER_KEY_KINDS } from "../provider-key-check.ts";
+import { isPhoneKeyPatch, PROVIDER_KEY_KINDS } from "../provider-key-check.ts";
import type { SessionRegistry } from "../sessions.ts";
import type { SharedComputerControl } from "../shared-computer-control.ts";
import type { SharedComputers } from "../shared-computers.ts";
@@ -138,6 +138,9 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
}
if ((method === "PUT" || method === "PATCH") && path === "/api/config") {
const body = await readBody(req);
+ if (auth.kind === "loopback" && auth.companionDevice !== undefined && !isPhoneKeyPatch(body)) {
+ return json(res, 403, { error: "From a phone, only API keys can be changed. Change other settings on your computer." });
+ }
if (hostedModels && ["instances", "anthropic", "openai", "openrouter", "openaiCompat", "xai", "mistral", "cerebras", "groq", "greenference", "modelgo", "meta", "opencodeGo"].some(key => Object.hasOwn(body, key))) return json(res, 403, { error: HOSTED_PROVIDER_SETTINGS_ERROR });
const patch = parseConfigPatchForPerson(body);
if (deps.cloudTeam && patch.browserEngine?.egress?.proxy !== undefined && !(auth.kind === "session" && auth.session.teamRole === "owner")) {
diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.ts
index f50c4cc71b..4ef78f724b 100644
--- a/server/routes/instances.test.ts
+++ b/server/routes/instances.test.ts
@@ -71,7 +71,7 @@ async function serve(extra: Partial<InstanceRouteDeps> = {}, auth: RequestAuth =
await call("GET", "/api/instances");
return fake.probes.length;
};
- return { sign, call, probesAfterList, base, fake };
+ return { sign, call, probesAfterList, base, fake, registry };
}
describe("engine sign-in routes", () => {
@@ -104,6 +104,33 @@ describe("engine sign-in routes", () => {
});
});
+describe("browser sign-in from a paired phone", () => {
+ const start = (base: string) => fetch(`${base}/api/instances/a/auth/start`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
+
+ it("is refused with the instruction to use the computer, while a code sign-in and the desktop itself are not", async () => {
+ const phone: RequestAuth = { kind: "loopback", scopes: ["admin", "client"], companionDevice: "phone-1" };
+ const onPhone = await serve({}, phone);
+ const desktop = await serve();
+ const instance = (served: typeof onPhone) => served.registry.get("a") as { authenticationMethod?: string };
+
+ instance(onPhone).authenticationMethod = "browser";
+ const refused = await start(onPhone.base);
+ expect(refused.status).toBe(403);
+ expect(((await refused.json()) as { error: string }).error).toMatch(/happens in a browser on the computer/);
+
+ instance(onPhone).authenticationMethod = "browser-pkce";
+ const pkce = await start(onPhone.base);
+ expect(pkce.status).toBe(403);
+ expect(((await pkce.json()) as { error: string }).error).toMatch(/Continue with ChatGPT on the computer/);
+
+ instance(onPhone).authenticationMethod = "code";
+ expect((await start(onPhone.base)).status).toBe(200);
+
+ instance(desktop).authenticationMethod = "browser";
+ expect((await start(desktop.base)).status).toBe(200);
+ });
+});
+
describe("the engine list", () => {
it("answers again from the last status read, and reads every engine again when asked for fresh", async () => {
const { call, probesAfterList, fake } = await serve();
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index 39e50f8bcc..6839b4e713 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -365,7 +365,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
if (!instance) return json(res, 404, { error: "unknown instance" });
// The official local OAuth callback terminates on this machine, not a phone or a remote browser.
if ((instance.authenticationMethod === "browser-pkce" || instance.authenticationMethod === "browser")
- && (isProxied(req) || !isLoopbackHost(req.socket.remoteAddress))) {
+ && (isProxied(req) || !isLoopbackHost(req.socket.remoteAddress) || (auth.kind === "loopback" && auth.companionDevice !== undefined))) {
if (instance.authenticationMethod === "browser") {
return json(res, 403, { error: `This sign-in happens in a browser on the computer running ${productName()}. Open ${productName()} there to sign in.` });
}