Skip to content

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

Harness: narrow a phone from the standalone companion too

aivsomkarb9793be884d8
diff --git a/server/provider-key-check.ts b/server/provider-key-check.ts
index a958250151..13ff60fe7b 100644
--- a/server/provider-key-check.ts
+++ b/server/provider-key-check.ts
@@ -22,7 +22,7 @@ export function isPhoneKeyPatch(body: unknown): boolean {
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)
+ return fields !== undefined && typeof entry === "object" && entry !== null && !Array.isArray(entry) && Object.hasOwn(entry, "key")
&& Object.entries(entry).every(([name, value]) => Object.hasOwn(fields, name) && typeof value === fields[name]);
});
}
diff --git a/server/request-auth.ts b/server/request-auth.ts
index 2b67a311f6..71ed5d8a3d 100644
--- a/server/request-auth.ts
+++ b/server/request-auth.ts
@@ -192,6 +192,12 @@ export function isProxied(req: IncomingMessage): boolean {
return PROXY_HEADERS.some((name) => req.headers[name] !== undefined);
}
+/** A paired phone's request. The companion marks everything it forwards and the mark only narrows, so this also
+ * covers the standalone companion, which has no desktop token and so never sets `companionDevice`. */
+export function fromPairedDevice(req: IncomingMessage, auth: RequestAuth): boolean {
+ return (auth.kind === "loopback" && auth.companionDevice !== undefined) || req.headers["x-openmausbot-companion"] === "1";
+}
+
const LOOPBACK_PEER = /^(?:127\.|::1$|::ffff:127\.)/;
/** A TCP peer other than this machine. */
diff --git a/server/routes/config-phone-keys.test.ts b/server/routes/config-phone-keys.test.ts
index f37876eed0..cfeb545087 100644
--- a/server/routes/config-phone-keys.test.ts
+++ b/server/routes/config-phone-keys.test.ts
@@ -3,15 +3,17 @@ 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"] };
+// With the desktop's token the companion's phone is a verified device; the standalone companion only marks its requests.
+const viaDesktop = { auth: { ...desktop, companionDevice: "phone-1" }, headers: { "x-openmausbot-companion": "1", "x-openmausbot-companion-device": "phone-1" } };
+const standalone = { auth: desktop, headers: { "x-openmausbot-companion": "1", "x-openmausbot-companion-device": "phone-1" } };
-async function put(auth: RequestAuth, body: unknown, method = "PUT") {
+async function put(from: { auth: RequestAuth; headers: Record<string, string> }, 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,
+ req: { headers: from.headers }, res: {}, url: new URL("http://host/api/config"), path: "/api/config", method, auth: from.auth,
json: (_res: unknown, status: number, reply: unknown) => { replies.push({ status, body: reply }); },
readBody: async () => body,
} as unknown as Parameters<typeof route>[0]);
@@ -20,7 +22,7 @@ async function put(auth: RequestAuth, body: unknown, method = "PUT") {
const SENTENCE = "From a phone, only API keys can be changed. Change other settings on your computer.";
-describe("config writes from a paired phone", () => {
+describe.each([["through the desktop app", viaDesktop], ["through the standalone companion", standalone]])("config writes from a paired phone %s", (_name, phone) => {
it.each<Record<string, unknown>>([
{ mistral: { key: "k" } },
{ openai: { key: "" } },
@@ -39,14 +41,16 @@ describe("config writes from a paired phone", () => {
{ mistral: { key: "k" }, signIn: { admins: [] } },
{ mistral: "k" },
{ toString: { key: "k" } },
+ { anthropic: { everyClaudeBot: true } },
{},
])("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);
- });
+it("leaves the desktop's own write alone", async () => {
+ const own = { auth: desktop, headers: {} };
+ expect(await put(own, {})).toEqual({ status: 400, body: { error: "nothing to save" } });
+ expect((await put(own, { signIn: { admins: [] } }))?.status).toBe(409);
});
diff --git a/server/routes/config.ts b/server/routes/config.ts
index 8d357ad4c4..3036626c5d 100644
--- a/server/routes/config.ts
+++ b/server/routes/config.ts
@@ -26,7 +26,7 @@ import {
type AppConfig,
} from "../config.ts";
import type { InstanceConfigMap, ModelSelection } from "../contracts.ts";
-import type { RequestAuth } from "../request-auth.ts";
+import { fromPairedDevice, type RequestAuth } from "../request-auth.ts";
import { parseConfigPatchForPerson } from "../decider/config-errors.ts";
import { teamPersonalHint } from "../../shared/cloud-hints.ts";
import { DECIDER_KEY_ERROR, deciderIncludedHere, deciderPatchKey, deciderSavePatch, deciderBorrowedKey, type Decider } from "../decider/index.ts";
@@ -138,7 +138,8 @@ 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)) {
+ const pairedDevice = fromPairedDevice(req, auth);
+ if (pairedDevice && !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 });
@@ -564,7 +565,8 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
: null;
const enginesBefore = engineLaunches(providerConfigs());
const localVmModeChanged = changingLocalVmMode ? localVmModeChanging() : null;
- const externalSecretStorage = url.searchParams.get("secretStorage") === "external";
+ // Only the desktop's own save has put the key in the encrypted store; a phone's must land in config.json.
+ const externalSecretStorage = !pairedDevice && url.searchParams.get("secretStorage") === "external";
try {
if (patch.live) patch.live = liveSavePatch(cfg.live, patch.live);
// Before the provider commit, so a failed write never leaves a foreign voice id to speak.
diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.ts
index 4ef78f724b..a8d841ddb3 100644
--- a/server/routes/instances.test.ts
+++ b/server/routes/instances.test.ts
@@ -104,8 +104,11 @@ describe("engine sign-in routes", () => {
});
});
+const phoneHeaders = { "x-openmausbot-companion": "1", "x-openmausbot-companion-device": "phone-1" };
+
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: "{}" });
+ const start = (base: string, headers: Record<string, string> = {}) =>
+ fetch(`${base}/api/instances/a/auth/start`, { method: "POST", headers: { "content-type": "application/json", ...headers }, 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" };
@@ -127,10 +130,28 @@ describe("browser sign-in from a paired phone", () => {
expect((await start(onPhone.base)).status).toBe(200);
instance(desktop).authenticationMethod = "browser";
+ // The standalone companion has no desktop token: its phone is plain loopback carrying only the companion's mark.
+ expect((await start(desktop.base, phoneHeaders)).status).toBe(403);
expect((await start(desktop.base)).status).toBe(200);
});
});
+describe("whose sign-in it is", () => {
+ it("gives a phone its own, so it never resumes or cancels the computer's", async () => {
+ const { base } = await serve();
+ const start = (headers: Record<string, string> = {}) =>
+ fetch(`${base}/api/instances/a/auth/start`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: "{}" });
+ const cancel = (headers: Record<string, string> = {}) =>
+ fetch(`${base}/api/instances/a/auth/cancel`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify({ flowId: "flow-1" }) });
+
+ expect((await start()).status).toBe(200);
+ expect((await start(phoneHeaders)).status).toBe(409);
+ expect((await cancel(phoneHeaders)).status).toBe(404);
+ expect((await start()).status).toBe(200);
+ expect((await cancel()).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 6839b4e713..3ab2170301 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -40,7 +40,7 @@ import { checkEngine, type EngineCheck } from "../engine-check.ts";
import { HOSTED_PROVIDER_SETTINGS_ERROR } from "../hosted-models.ts";
import type { ProviderAuthSessions } from "../provider-auth-sessions.ts";
import { providerIconPatchSchema, withInstanceIcon } from "../provider-icon.ts";
-import { isLoopbackHost, isProxied, ownerOrAdmin } from "../request-auth.ts";
+import { fromPairedDevice, isLoopbackHost, isProxied, ownerOrAdmin } from "../request-auth.ts";
import type { SessionRegistry } from "../sessions.ts";
import type { Store } from "../store.ts";
import type { BusyFlag, ConfigStatus } from "./config.ts";
@@ -316,10 +316,13 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
} finally { providerConfigBusy.set(false); }
}
+ // Each phone has its own sign-in, so it never resumes or reads the computer's, or another phone's.
+ const signInOwner = () => auth.kind === "session" ? auth.session.id
+ : fromPairedDevice(req, auth) ? `companion:${String(req.headers["x-openmausbot-companion-device"] ?? "")}` : "loopback";
const authStatus = /^\/api\/instances\/([\w.-]+)\/auth\/status$/.exec(path);
if (method === "GET" && authStatus) {
res.setHeader("cache-control", "no-store");
- const state = await providerAuthSessions.status(authStatus[1], auth.kind === "session" ? auth.session.id : "loopback", url.searchParams.get("flowId") ?? "");
+ const state = await providerAuthSessions.status(authStatus[1], signInOwner(), url.searchParams.get("flowId") ?? "");
// A finished device sign-in changed what the engine reports; the page reads the engines next.
if (state.phase !== "waiting") registry.forgetSnapshots();
return json(res, 200, { auth: state });
@@ -331,7 +334,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
}
const instanceId = instanceAction[1];
const action = instanceAction[2];
- const owner = auth.kind === "session" ? auth.session.id : "loopback";
+ const owner = signInOwner();
if (action.startsWith("auth/")) res.setHeader("cache-control", "no-store");
try {
if (action === "check") {
@@ -365,7 +368,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) || (auth.kind === "loopback" && auth.companionDevice !== undefined))) {
+ && (isProxied(req) || !isLoopbackHost(req.socket.remoteAddress) || fromPairedDevice(req, auth))) {
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.` });
}