Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Save a phone's key through the desktop's own credential save
aivsomkar12088ca37500
diff --git a/companion/src/index.ts b/companion/src/index.tsindex c1ea2538d6..08de44113b 100755--- a/companion/src/index.ts+++ b/companion/src/index.ts@@ -47,9 +47,15 @@ let mutationToken: string | null = null;let controlToken = initialControlToken(process.env, Boolean(parentPort));let controlTokenReceived = (): void => {};const controlReady = controlToken ? Promise.resolve() : new Promise<void>((resolve) => { controlTokenReceived = resolve; });+type ProviderKeyReply = { status: number; body: unknown };+const providerKeySaves = new Map<number, (reply: ProviderKeyReply) => void>();+let providerKeySaveId = 0;parentPort?.on("message", ({ data }) => {if (!data || typeof data !== "object") return;const message = data as Record<string, unknown>;+ if (message.type === "openmausbot:companion-provider-key-result" && typeof message.status === "number") {+ return void providerKeySaves.get(message.id as number)?.({ status: message.status, body: message.body });+ }if (message.type === "openmausbot:companion-e2e") return void configureE2E(message);if (message.type === "openmausbot:companion-e2e-redial") return void relay?.redial();if (message.type !== "openmausbot:companion-mutation-token") return;@@ -62,6 +68,20 @@ parentPort?.on("message", ({ data }) => {}});+/** A phone's key goes to the desktop app, which saves it the way its own Settings do. */+const saveProviderKey = (port: NonNullable<typeof parentPort>) => (patch: unknown): Promise<ProviderKeyReply> =>+ new Promise((resolve) => {+ const id = ++providerKeySaveId;+ const done = (reply: ProviderKeyReply) => {+ clearTimeout(timer);+ providerKeySaves.delete(id);+ resolve(reply);+ };+ const timer = setTimeout(() => done({ status: 504, body: { error: "The computer took too long to save the key. Try again." } }), 60_000);+ providerKeySaves.set(id, done);+ port.postMessage({ type: "openmausbot:companion-provider-key", id, patch });+ });+/** A typo'd port must not become port 0. */const num = (value: string | undefined, fallback: number): number => {const parsed = Number(value);@@ -162,6 +182,7 @@ const proxy = createProxyHandler({connected: connectedDevices.open,e2eDescriptor: (deviceId) => e2e.descriptor(deviceId),e2ePaired: (context, deviceId) => e2e.paired(context, deviceId),+ saveProviderKey: parentPort ? saveProviderKey(parentPort) : undefined,});const e2eOrigin = createE2EOrigin((req, res) => proxy(req, res), (req, socket, head) => proxy.upgrade(req, socket, head));const companion = createServer((req, res) => proxy(req, res, "lan"));diff --git a/companion/src/proxy.ts b/companion/src/proxy.tsindex 12b717ffc5..dab366d2fa 100644--- a/companion/src/proxy.ts+++ b/companion/src/proxy.ts@@ -58,6 +58,9 @@ export interface ProxyOptions {e2eDescriptor?: (deviceId: string | null) => E2EDescriptor | null;/** A phone paired through an encrypted session keyed by the pairing token: the session is now that device's. */e2ePaired?: (context: E2EContext, deviceId: string) => void;+ /** The desktop app's own key save (encrypted store first). When set, a phone's `PUT /api/config` goes here and+ * never to the harness, which would keep the key only in its config file. */+ saveProviderKey?: (patch: unknown) => Promise<{ status: number; body: unknown }>;}/** Which listener a request reached. Only `lan` (port 8810, plain HTTP) refuses a device that has gone end-to-end;@@ -498,6 +501,15 @@ export function createProxyHandler(options: ProxyOptions) {return sendJson(res, 200, endpointsFor(device?.id ?? null));}+ const { saveProviderKey } = options;+ if (device && saveProviderKey && method === "PUT" && path === "/api/config") {+ readJson(req, 8 * 1024).then(+ (body) => saveProviderKey(body).then((reply) => sendJson(res, reply.status, scrub(reply.body))),+ (error: Error) => sendJson(res, 400, { error: error.message }),+ ).catch(() => sendJson(res, 502, { error: "the key could not be saved on this computer" }));+ return;+ }+const mutationToken = device ? options.mutationToken?.() : undefined;if (device && options.mutationToken && !mutationToken) {return sendJson(res, 503, { error: "The desktop connection is starting. Please try again shortly." });diff --git a/companion/test/provider-key-save.test.ts b/companion/test/provider-key-save.test.tsnew file mode 100644index 0000000000..f4b4346688--- /dev/null+++ b/companion/test/provider-key-save.test.ts@@ -0,0 +1,75 @@+// Inside the desktop app a phone's key goes to the desktop's own save (encrypted store first), never straight to the+// harness; the standalone companion has no such save and forwards it.+import { createServer, type Server } from "node:http";+import { afterEach, describe, expect, it } from "vitest";++import { createProxyHandler, type ProxyOptions } from "../src/proxy.ts";++const TOKEN = "omb_test_token";+const servers: Server[] = [];++const listen = async (server: Server): Promise<number> => {+ servers.push(server);+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ return (server.address() as { port: number }).port;+};++afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))));+});++async function companion(saveProviderKey?: ProxyOptions["saveProviderKey"]) {+ const harness: Array<{ method: string; url: string; body: string }> = [];+ const harnessPort = await listen(createServer((req, res) => {+ let body = "";+ req.on("data", (chunk) => { body += chunk; });+ req.on("end", () => {+ harness.push({ method: req.method ?? "", url: req.url ?? "", body });+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ from: "harness" }));+ });+ }));+ const port = await listen(createServer(createProxyHandler({+ harnessPort,+ authenticate: (token) => (token === TOKEN ? { id: "phone-1", cloudDesktopAccess: false, browserControlAccess: false } : null),+ redeem: () => ({ error: "not used here", code: "pairing_code_wrong" }),+ serverName: () => "Test computer",+ saveProviderKey,+ })));+ const put = async (body: string, token = TOKEN) => {+ const res = await fetch(`http://127.0.0.1:${port}/api/config?secretStorage=external`, {+ method: "PUT", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body,+ });+ return { status: res.status, body: await res.json() };+ };+ return { harness, put };+}++describe("a phone's PUT /api/config", () => {+ it("goes to the desktop's save and never to the harness when the desktop supplies one", async () => {+ const patches: unknown[] = [];+ const { harness, put } = await companion(async (patch) => {+ patches.push(patch);+ return { status: 200, body: { mistral: { configured: true } } };+ });+ expect(await put(JSON.stringify({ mistral: { key: "k1" } }))).toEqual({ status: 200, body: { mistral: { configured: true } } });+ expect(patches).toEqual([{ mistral: { key: "k1" } }]);++ expect((await put("{", TOKEN)).status).toBe(400);+ // Past the bound the reader drops the connection, whether or not its 400 got out first.+ await put(JSON.stringify({ mistral: { key: "k".repeat(9000) } })).catch(() => {});+ expect((await put(JSON.stringify({ mistral: { key: "k2" } }), "not-paired")).status).toBe(401);+ expect(patches).toHaveLength(1);+ expect(harness).toEqual([]);+ });++ it("passes the desktop's refusal through", async () => {+ const { put } = await companion(async () => ({ status: 403, body: { error: "only keys" } }));+ expect(await put(JSON.stringify({ signIn: {} }))).toEqual({ status: 403, body: { error: "only keys" } });+ });++ it("is forwarded as before by the standalone companion, which has no desktop save", async () => {+ const { harness, put } = await companion();+ expect(await put(JSON.stringify({ mistral: { key: "k1" } }))).toEqual({ status: 200, body: { from: "harness" } });+ expect(harness).toEqual([{ method: "PUT", url: "/api/config?secretStorage=external", body: JSON.stringify({ mistral: { key: "k1" } }) }]);+ });+});diff --git a/electron/companion.mjs b/electron/companion.mjsindex 77d3d41e3a..914ec09fe8 100644--- a/electron/companion.mjs+++ b/electron/companion.mjs@@ -162,6 +162,13 @@ export function setCompanionE2EHooks(hooks) {e2eHooks = { ...e2eHooks, ...hooks };}+let providerKeySaver = async () => ({ status: 503, body: { error: "This computer cannot save keys right now." } });++/** Main's key save for a phone's `PUT /api/config`: resolves `{ status, body }`, never throws. */+export function setCompanionProviderKeySaver(save) {+ providerKeySaver = save;+}+/** In-memory port only. False when no sidecar runs. */export function postCompanionMessage(message) {if (!proc) return false;@@ -255,6 +262,14 @@ async function start({ resourcesPath, harnessPort, mutationToken, hostedUrl = nu});child.on("message", (message) => {if (message?.type === "openmausbot:companion-e2e-token-rejected") e2eHooks.tokenRejected();+ if (message?.type === "openmausbot:companion-provider-key" && Number.isSafeInteger(message.id)) {+ void providerKeySaver(message.patch).then((reply) => {+ try {+ child.postMessage({ type: "openmausbot:companion-provider-key-result", id: message.id, status: reply.status, body: reply.body });+ } catch {+ }+ });+ }});child.stdout?.on("data", (d) => log?.(`[companion] ${String(d).trimEnd()}`));child.stderr?.on("data", (d) => log?.(`[companion err] ${String(d).trimEnd()}`));diff --git a/electron/credential-patch.mjs b/electron/credential-patch.mjsindex 06f83292f0..c42f85ae25 100644--- a/electron/credential-patch.mjs+++ b/electron/credential-patch.mjs@@ -31,6 +31,39 @@ export const CREDENTIAL_PATCH = {postizApiKey: (value) => ({ postiz: { key: value } }),};+/** The providers a paired phone may set a key for, by credential name. Never openaiCompat: its patch carries the URL the key goes to. */+const PHONE_KEY_CREDENTIALS = Object.freeze({+ openai: "openaiApiKey",+ anthropic: "anthropicApiKey",+ openrouter: "openrouterApiKey",+ mistral: "mistralApiKey",+ cerebras: "cerebrasApiKey",+ groq: "groqApiKey",+ greenference: "greenferenceApiKey",+ modelgo: "modelgoApiKey",+ meta: "metaApiKey",+ xai: "xaiApiKey",+});++const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);++/** A phone's `PUT /api/config` body as the one credential:set call it stands for, or null when it is anything but one provider's key. */+export function phoneKeyCredential(patch) {+ if (!isRecord(patch)) return null;+ const providers = Object.keys(patch);+ if (providers.length !== 1 || !Object.hasOwn(PHONE_KEY_CREDENTIALS, providers[0])) return null;+ const provider = providers[0];+ const entry = patch[provider];+ const fields = provider === "anthropic" ? ["key", "everyClaudeBot"] : ["key"];+ if (!isRecord(entry) || !Object.hasOwn(entry, "key") || typeof entry.key !== "string" || !Object.keys(entry).every((field) => fields.includes(field))) return null;+ if (Object.hasOwn(entry, "everyClaudeBot") && typeof entry.everyClaudeBot !== "boolean") return null;+ return {+ name: PHONE_KEY_CREDENTIALS[provider],+ value: entry.key,+ options: Object.hasOwn(entry, "everyClaudeBot") ? { everyClaudeBot: entry.everyClaudeBot } : undefined,+ };+}+const DECIDER_ERRORS = Object.freeze({"serverError.decider.accountRequired": "native.decider.accountRequired","serverError.decider.jevRejected": "native.decider.jevRejected",@@ -44,5 +77,6 @@ export function credentialSaveError(status, body, t = nativeText.englishText.t)const message = key && body?.error === nativeText.englishText.t(key) ? t(key) : body?.error;const error = new Error(message || `Could not save credential (HTTP ${status})`);if (body?.code === "key_rejected") error.name = "KeyRejected";+ error.status = status;return error;}diff --git a/electron/main.mjs b/electron/main.mjsindex bab140b99b..ac8b582fcf 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -449,12 +449,12 @@ const DESKTOP_CRASH_LOG_MAX_BYTES = 512 * 1024;let logStream = null;let desktopShutdownStarted = false;import { companionAdvertisedHostedUrl, companionEnabledAtRest, companionOriginTarget, companionPairing, companionPairingRenew, companionDeviceRoutes, companionStartsAtLaunch, companionCloudDesktopAccess, companionRouteOn, dismissCompanionNotice, rememberCompanionRoute, setCompanionMigrationFacts,- companionBrowserControlAccess, companionRevoke, companionRunning, companionSettings, companionState, rememberCompanionKeepAwake, setCompanionHostedUrl, setCompanionLifecycleListener, startCompanion, stopCompanion } from "./companion.mjs";+ companionBrowserControlAccess, companionRevoke, companionRunning, companionSettings, companionState, rememberCompanionKeepAwake, setCompanionHostedUrl, setCompanionLifecycleListener, setCompanionProviderKeySaver, startCompanion, stopCompanion } from "./companion.mjs";import { createDesktopCompanionE2E, deviceCounts } from "./companion-e2e-desktop.mjs"; import { startCheckedManagedConnection } from "./managed-companion-start.mjs";import { autoStartCompanion } from "./companion-autostart.mjs";import { createPhoneLinkRoutes } from "./phone-link-routes.mjs"; import { reachableForKeepAwake } from "./keep-awake.mjs";import { createRoutineWakeHold, rememberRoutineWake, routineWakeSettings } from "./routine-wake.mjs";-import { CREDENTIAL_PATCH, credentialSaveError } from "./credential-patch.mjs";+import { CREDENTIAL_PATCH, credentialSaveError, phoneKeyCredential } from "./credential-patch.mjs";/** Second wall after preload's reduced bridge: computer-controlling IPC answers only the local server's UI.* Declared before any handler registration (temporal dead zone). */@@ -2746,6 +2746,16 @@ async function saveWorkspaceCredential(name, value, options) {installCredentialStoreIpc({ ipcMain, localOnly, dialog, windowFor: (sender) => BrowserWindow.fromWebContents(sender), t: nativeT, appName: () => app.name, unreadable: () => credentialStoreUnavailable, quitting: () => desktopShutdownStarted, moveAside: () => fs.renameSync(CREDENTIALS_FILE, `${CREDENTIALS_FILE}.unreadable-${Date.now()}`), log: slog, relaunch: relaunchAfterDesktopRemoteChange });ipcMain.handle("credential:set", localOnly("credential:set", (_event, name, value, options) => saveWorkspaceCredential(name, value, options)));+// A paired phone's key takes this same save, so it persists, and clears, exactly like one set in Settings here.+setCompanionProviderKeySaver(async (patch) => {+ const credential = phoneKeyCredential(patch);+ if (!credential) return { status: 403, body: { error: "From a phone, only API keys can be changed. Change other settings on your computer." } };+ try {+ return { status: 200, body: await saveWorkspaceCredential(credential.name, credential.value, credential.options) };+ } catch (error) {+ return { status: Number.isInteger(error?.status) ? error.status : 503, body: { error: error instanceof Error ? error.message : String(error) } };+ }+});ipcMain.handle("approvals:set-trusted-mode", localOnly("approvals:set-trusted-mode", (_event, botId, mode, options) => {// A separately launched dev server is outside this trust path: never degrade this grant to loopback HTTP.diff --git a/electron/phone-key-credential.test.mjs b/electron/phone-key-credential.test.mjsnew file mode 100644index 0000000000..3a2038080a--- /dev/null+++ b/electron/phone-key-credential.test.mjs@@ -0,0 +1,49 @@+// A phone's key save goes through the desktop's own credential:set path; the harness guards the same set of providers+// when the phone reaches it directly (the standalone companion), so the two lists must not drift.+import { describe, expect, it } from "vitest";++import { isPhoneKeyPatch, PROVIDER_KEY_KINDS } from "../server/provider-key-check.ts";+import { CREDENTIAL_PATCH, phoneKeyCredential } from "./credential-patch.mjs";++describe("a phone's config write as a credential:set call", () => {+ it.each([+ [{ mistral: { key: "k" } }, { name: "mistralApiKey", value: "k", options: undefined }],+ [{ openai: { key: "" } }, { name: "openaiApiKey", value: "", options: undefined }],+ [{ anthropic: { key: "k", everyClaudeBot: false } }, { name: "anthropicApiKey", value: "k", options: { everyClaudeBot: false } }],+ ])("maps %j", (patch, credential) => {+ expect(phoneKeyCredential(patch)).toEqual(credential);+ });++ it("refuses anything but one phone-settable provider's key", () => {+ for (const patch of [+ null, "k", [], {},+ { openaiCompat: { key: "k" } },+ { deepseek: { key: "k" } },+ { treg: { key: "k" } },+ { openai: { key: "k", url: "http://elsewhere.test/v1" } },+ { mistral: { key: "k", everyClaudeBot: true } },+ { anthropic: { key: "k", everyClaudeBot: "no" } },+ { anthropic: { everyClaudeBot: false } },+ { mistral: {} },+ { mistral: { key: 5 } },+ { mistral: "k" },+ { mistral: { key: "k" }, openai: { key: "k" } },+ { mistral: { key: "k" }, signIn: { admins: [] } },+ JSON.parse('{"__proto__": {"key": "k"}}'),+ { toString: { key: "k" } },+ ]) expect(phoneKeyCredential(patch), JSON.stringify(patch)).toBeNull();+ });++ it("agrees with the harness on every provider, and saves exactly the patch the phone sent", () => {+ const sections = new Set([...PROVIDER_KEY_KINDS, ...Object.values(CREDENTIAL_PATCH).map((patchFor) => Object.keys(patchFor("k"))[0])]);+ for (const section of sections) {+ const patch = { [section]: { key: "k" } };+ const credential = phoneKeyCredential(patch);+ expect(credential !== null, section).toBe(isPhoneKeyPatch(patch));+ if (credential) expect(CREDENTIAL_PATCH[credential.name](credential.value, credential.options), section).toEqual(patch);+ }+ const anthropic = { anthropic: { key: "k", everyClaudeBot: false } };+ const credential = phoneKeyCredential(anthropic);+ expect(CREDENTIAL_PATCH[credential.name](credential.value, credential.options)).toEqual(anthropic);+ });+});