Skip to content

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

Keep every AI provider key in the desktop's encrypted store (#5280)

Milind Soni5beba12766ff
diff --git a/README.md b/README.md
index ab96963faa..2d55cab4f3 100644
--- a/README.md
+++ b/README.md
@@ -503,8 +503,12 @@ installation and pairing.
Run `openmausbot setup` to reconfigure without resetting bots or conversations;
the saved model default applies only to new bots. Native setup confirms provider
-sign-in; API setup asks before a potentially billable test message. API keys are
-saved as plaintext, not encrypted, in private `config.json` (`0600` on Unix).
+sign-in; API setup asks before a potentially billable test message. API keys
+from `openmausbot setup` and the server are saved as plaintext, not encrypted,
+in private `config.json` (`0600` on Unix). The packaged desktop app keeps your
+AI provider and service keys encrypted through the operating system instead;
+its `config.json` still holds OpenCode provider keys, keys given to one engine,
+and MCP header values in plaintext.
See the [short setup guide](docs/cli-onboarding.md) for account differences,
phone choices, credential storage, and cancellation.
diff --git a/SECURITY.md b/SECURITY.md
index 5bd5b53fea..5ddc481e78 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -26,7 +26,10 @@ You'll get a response as soon as possible, normally within a few days.
shared Full access is on, and get Full-access work done without a card. A worker-only relay token
is the planned fix.
- API keys live in `~/.openmausbot/config.json` and are write-only through the API (`configured`
- booleans out, never values). Any path that echoes a stored secret back — API response, SSE event,
+ booleans out, never values). The packaged desktop app keeps AI provider and service keys in an
+ OS-encrypted store (`credentials.bin`) instead; OpenCode provider keys, per-engine `environment`
+ or `key` values, MCP header values and `mcp-oauth.json` stay plaintext on every install. Any path
+ that echoes a stored secret back — API response, SSE event,
log line, argv visible in `ps` — is a vulnerability.
- Agents run real CLIs (`claude`, `codex`) with the user's own privileges, and the permission broker
is the consent layer for risky actions. Bypasses of the broker (approving without a user decision,
diff --git a/docs/cli-onboarding.md b/docs/cli-onboarding.md
index e90ccc70a0..b55fe2a809 100644
--- a/docs/cli-onboarding.md
+++ b/docs/cli-onboarding.md
@@ -79,6 +79,8 @@ Setup needs an interactive terminal. Later starts can run without one once setup
API keys are hidden while typed or pasted. New API connections save their key in the data directory's `config.json` as **plaintext, not encrypted**, with owner-only permissions (`0600`) on Unix. Managed-access account credentials in `tunnel-account.json` are also plaintext with `0600` permissions on Unix. Keep these files and backups private. Native provider sign-in credentials are managed by the provider's own CLI.
+The packaged desktop app does not keep your AI provider and service keys there: it encrypts them with the operating system (Keychain on macOS, DPAPI on Windows, the system secret store on Linux, where a desktop without one gets only Electron's fixed-key obfuscation) in `credentials.bin` and moves keys it finds in `config.json` into that store at startup. Keys entered through this CLI setup, OpenCode provider keys, keys given to one engine (`environment` or `key`), and MCP header values stay plaintext in `config.json`, on desktop too. `mcp-oauth.json` is also plaintext.
+
Ctrl-C during AI setup leaves unsaved OMB changes unapplied. Installations and provider sign-ins already completed remain available. Ctrl-C during the later phone step keeps the AI setup you already saved, exits without starting a server, and does not undo an account sign-in already completed. Run `openmausbot setup` to continue; no destructive reset is needed.
For remote access and background deployment options, see [self-hosting](self-hosting.md) and [the VPS guide](deploy-vps.md).
diff --git a/electron/credential-patch.mjs b/electron/credential-patch.mjs
index 2b1096b372..e12e0a61ce 100644
--- a/electron/credential-patch.mjs
+++ b/electron/credential-patch.mjs
@@ -1,5 +1,16 @@
import nativeText from "./native-text.cjs";
export const CREDENTIAL_PATCH = {
+ openaiApiKey: (value) => ({ openai: { key: value } }),
+ // everyClaudeBot travels with the key, so no moment exists where a first key moves every signed-in Claude bot onto API billing.
+ anthropicApiKey: (value, options) => ({ anthropic: { key: value, ...(options?.everyClaudeBot === false ? { everyClaudeBot: false } : {}) } }),
+ openrouterApiKey: (value) => ({ openrouter: { key: value } }),
+ mistralApiKey: (value) => ({ mistral: { key: value } }),
+ cerebrasApiKey: (value) => ({ cerebras: { key: value } }),
+ groqApiKey: (value) => ({ groq: { key: value } }),
+ greenferenceApiKey: (value) => ({ greenference: { key: value } }),
+ metaApiKey: (value) => ({ meta: { key: value } }),
+ deepseekApiKey: (value) => ({ deepseek: { key: value } }),
+ openaiCompatApiKey: (value) => ({ openaiCompat: { key: value } }),
composioApiKey: (value) => ({ composio: { apiKey: value } }),
xaiApiKey: (value) => ({ xai: { key: value } }),
boxToken: (value) => ({ box: { token: value } }),
diff --git a/electron/main.mjs b/electron/main.mjs
index aa6d9e5f10..d36f70af1f 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -22,7 +22,7 @@ import {
installDesktopCrashListeners,
readSafeLogTail,
} from "./diagnostics.mjs";
-import { migrateWorkspaceCredentials, workspaceCredentialEnv } from "./workspace-credentials.mjs";
+import { migrateWorkspaceConfigFile, workspaceCredentialEnv } from "./workspace-credentials.mjs";
import { evictStartupCacheOnce } from "./startup-cache-eviction.mjs";
import { activateExistingWindow, releaseSingleInstanceLock } from "./single-instance.mjs";
import { bootFailureMessage, listeningSignal, pollServerIdentity, SERVER_BOOT_TIMEOUT_MS, SERVER_LISTENING_GRACE_MS } from "./server-boot-probe.mjs";
@@ -433,21 +433,9 @@ async function secureComposioConfig() {
}
async function secureWorkspaceConfig() {
- const dataDir = desktopDataDir();
- const configPath = path.join(dataDir, "config.json");
- try {
- const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
- const migrated = migrateWorkspaceCredentials(config, secureCredentials);
- // credentials.bin first, so a failed save never loses the only copy of a secret.
- if (migrated.credentialsChanged) await saveSecureCredentials(migrated.credentials);
- secureCredentials = migrated.credentials;
- if (!migrated.configChanged) return;
- const temporary = `${configPath}.${process.pid}.tmp`;
- fs.writeFileSync(temporary, JSON.stringify(migrated.config, null, 2), { mode: 0o600 });
- fs.renameSync(temporary, configPath);
- } catch (error) {
- if (error?.code !== "ENOENT") slog(`credential migration failed: ${error?.message ?? error}`);
- }
+ secureCredentials = await migrateWorkspaceConfigFile({
+ configPath: path.join(desktopDataDir(), "config.json"), credentials: secureCredentials, save: saveSecureCredentials, log: slog,
+ });
}
function composioBrokerUrl() {
@@ -2743,7 +2731,7 @@ ipcMain.handle("desktop:capabilities", async (event) =>
}),
);
-async function saveWorkspaceCredential(name, value) {
+async function saveWorkspaceCredential(name, value, options) {
const patchFor = CREDENTIAL_PATCH[name];
if (!patchFor || typeof value !== "string") {
throw new Error("Unsupported credential");
@@ -2761,7 +2749,7 @@ async function saveWorkspaceCredential(name, value) {
{ "content-type": "application/json" },
{ packaged: app.isPackaged, token: desktopMutationToken },
),
- body: JSON.stringify(patchFor(secret)),
+ body: JSON.stringify(patchFor(secret, options)),
});
const body = await response.json().catch(() => null);
if (!response.ok) throw credentialSaveError(response.status, body, nativeT);
@@ -2783,7 +2771,7 @@ async function saveWorkspaceCredential(name, value) {
}
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) => saveWorkspaceCredential(name, value)));
+ipcMain.handle("credential:set", localOnly("credential:set", (_event, name, value, options) => saveWorkspaceCredential(name, value, options)));
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/preload.cjs b/electron/preload.cjs
index 837e217195..fd7e15676f 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -420,7 +420,7 @@ const bridge = {
set: on => on !== true || isLocalPage || navigator.userActivation?.isActive === true
? ipcRenderer.invoke("open-at-login:set", on === true) : Promise.reject(new Error("Turn on the switch to open OpenMausBot at login.")),
},
- setCredential: (name, value) => ipcRenderer.invoke("credential:set", name, value),
+ setCredential: (name, value, options) => ipcRenderer.invoke("credential:set", name, value, options),
// Saved keys this launch could not read, and "Reset saved keys" (main asks the person first, then restarts).
credentialStore: {
unreadable: () => ipcRenderer.invoke("credential-store:unreadable"),
diff --git a/electron/workspace-credentials-save.node-test.mjs b/electron/workspace-credentials-save.node-test.mjs
index e264fb10d6..98b7be38a2 100644
--- a/electron/workspace-credentials-save.node-test.mjs
+++ b/electron/workspace-credentials-save.node-test.mjs
@@ -27,3 +27,8 @@ test("the external secret save never leaves a migrated secret in config.json", (
);
}
});
+
+test("a first Anthropic key leaves bots signed in to Claude on their sign-in, and only that option crosses", () => {
+ assert.deepEqual(CREDENTIAL_PATCH.anthropicApiKey("secret", { everyClaudeBot: false }), { anthropic: { key: "secret", everyClaudeBot: false } });
+ assert.deepEqual(CREDENTIAL_PATCH.anthropicApiKey("secret", { everyClaudeBot: true, url: "https://elsewhere.example.test" }), { anthropic: { key: "secret" } });
+});
diff --git a/electron/workspace-credentials.mjs b/electron/workspace-credentials.mjs
index 2baa116dcb..e1ed91b0d4 100644
--- a/electron/workspace-credentials.mjs
+++ b/electron/workspace-credentials.mjs
@@ -1,4 +1,16 @@
+import fs from "node:fs";
+
export const WORKSPACE_CREDENTIALS = [
+ { section: "openai", field: "key", name: "openaiApiKey", env: "OMB_OPENAI_API_KEY" },
+ { section: "anthropic", field: "key", name: "anthropicApiKey", env: "OMB_ANTHROPIC_API_KEY" },
+ { section: "openrouter", field: "key", name: "openrouterApiKey", env: "OMB_OPENROUTER_API_KEY" },
+ { section: "mistral", field: "key", name: "mistralApiKey", env: "MISTRAL_API_KEY" },
+ { section: "cerebras", field: "key", name: "cerebrasApiKey", env: "CEREBRAS_API_KEY" },
+ { section: "groq", field: "key", name: "groqApiKey", env: "OMB_GROQ_API_KEY" },
+ { section: "greenference", field: "key", name: "greenferenceApiKey", env: "OMB_GREENFERENCE_API_KEY" },
+ { section: "meta", field: "key", name: "metaApiKey", env: "OMB_META_API_KEY" },
+ { section: "deepseek", field: "key", name: "deepseekApiKey", env: "OMB_DEEPSEEK_API_KEY" },
+ { section: "openaiCompat", field: "key", name: "openaiCompatApiKey", env: "OPENAI_COMPAT_API_KEY" },
{ section: "xai", field: "key", name: "xaiApiKey", env: "XAI_API_KEY" },
{ section: "box", field: "token", name: "boxToken", env: "BOX_TOKEN" },
{ section: "tts", field: "key", name: "ttsKey", env: "OMB_TTS_KEY" },
@@ -40,6 +52,24 @@ export function migrateWorkspaceCredentials(config, credentials) {
return { config: nextConfig, credentials: nextCredentials, configChanged, credentialsChanged };
}
+/** Security: the encrypted write comes first, so a store that cannot save leaves every plaintext key in config.json and the app working. */
+export async function migrateWorkspaceConfigFile({ configPath, credentials, save, log }) {
+ let current = credentials;
+ try {
+ const migrated = migrateWorkspaceCredentials(JSON.parse(fs.readFileSync(configPath, "utf8")), current);
+ if (migrated.credentialsChanged) await save(migrated.credentials);
+ current = migrated.credentials;
+ if (migrated.configChanged) {
+ const temporary = `${configPath}.${process.pid}.tmp`;
+ fs.writeFileSync(temporary, JSON.stringify(migrated.config, null, 2), { mode: 0o600 });
+ fs.renameSync(temporary, configPath);
+ }
+ } catch (error) {
+ if (error?.code !== "ENOENT") log(`credential migration failed: ${error?.message ?? error}`);
+ }
+ return current;
+}
+
export function workspaceCredentialEnv(credentials) {
const env = {};
for (const { name, env: envName } of WORKSPACE_CREDENTIALS) {
diff --git a/electron/workspace-credentials.test.mjs b/electron/workspace-credentials.test.mjs
index 60959ab387..80e503ed3f 100644
--- a/electron/workspace-credentials.test.mjs
+++ b/electron/workspace-credentials.test.mjs
@@ -1,6 +1,10 @@
-import { describe, expect, it } from "vitest";
+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
import {
+ migrateWorkspaceConfigFile,
migrateWorkspaceCredentials,
workspaceCredentialEnv,
WORKSPACE_CREDENTIALS,
@@ -52,12 +56,13 @@ describe("workspace credential migration", () => {
decider: { provider: "openrouter", openrouterModel: "openai/gpt-4o-mini", key: "jev-secret", openrouterKey: "sk-or-secret", enabled: true },
openrouter: { key: "engine-openrouter-key" },
}, {});
- expect(result.credentials).toEqual({ jevApiKey: "jev-secret", openrouterDeciderKey: "sk-or-secret" });
+ expect(result.credentials).toEqual({ jevApiKey: "jev-secret", openrouterDeciderKey: "sk-or-secret", openrouterApiKey: "engine-openrouter-key" });
expect(result.config.decider).toEqual({ provider: "openrouter", openrouterModel: "openai/gpt-4o-mini", enabled: true });
- expect(result.config.openrouter).toEqual({ key: "engine-openrouter-key" });
+ expect(result.config.openrouter).toEqual({});
expect(workspaceCredentialEnv(result.credentials)).toEqual({
OMB_JEV_API_KEY: "jev-secret",
OMB_OPENROUTER_DECIDER_KEY: "sk-or-secret",
+ OMB_OPENROUTER_API_KEY: "engine-openrouter-key",
});
});
@@ -156,3 +161,88 @@ describe("workspace credential env", () => {
expect(Object.keys(env).sort()).toEqual(WORKSPACE_CREDENTIALS.map((c) => c.env).sort());
});
});
+
+const AI_PROVIDER_KEYS = [
+ ["openai", "openaiApiKey", "OMB_OPENAI_API_KEY"],
+ ["anthropic", "anthropicApiKey", "OMB_ANTHROPIC_API_KEY"],
+ ["openrouter", "openrouterApiKey", "OMB_OPENROUTER_API_KEY"],
+ ["mistral", "mistralApiKey", "MISTRAL_API_KEY"],
+ ["cerebras", "cerebrasApiKey", "CEREBRAS_API_KEY"],
+ ["groq", "groqApiKey", "OMB_GROQ_API_KEY"],
+ ["greenference", "greenferenceApiKey", "OMB_GREENFERENCE_API_KEY"],
+ ["meta", "metaApiKey", "OMB_META_API_KEY"],
+ ["deepseek", "deepseekApiKey", "OMB_DEEPSEEK_API_KEY"],
+ ["openaiCompat", "openaiCompatApiKey", "OPENAI_COMPAT_API_KEY"],
+];
+
+describe("AI provider keys in the encrypted store", () => {
+ it.each(AI_PROVIDER_KEYS)("moves %s into its slot and hands it to the server under its own variable", (section, name, env) => {
+ const result = migrateWorkspaceCredentials({ [section]: { key: `fixture-${section}` } }, {});
+ expect(result.credentials).toEqual({ [name]: `fixture-${section}` });
+ expect(result.config).toEqual({ [section]: {} });
+ expect(workspaceCredentialEnv(result.credentials)).toEqual({ [env]: `fixture-${section}` });
+ });
+
+ it("keeps the Anthropic and OpenAI-compatible settings that are not secrets", () => {
+ const { config } = migrateWorkspaceCredentials({
+ anthropic: { key: "ant", url: "https://claude.example.test", everyClaudeBot: false },
+ openaiCompat: { key: "compat", url: "http://127.0.0.1:1234/v1", model: "local", provider: "pin" },
+ }, {});
+ expect(config).toEqual({
+ anthropic: { url: "https://claude.example.test", everyClaudeBot: false },
+ openaiCompat: { url: "http://127.0.0.1:1234/v1", model: "local", provider: "pin" },
+ });
+ });
+});
+
+describe("migrating config.json on disk", () => {
+ const folders = [];
+ const configFile = (config) => {
+ const folder = mkdtempSync(join(tmpdir(), "omb-workspace-credentials-"));
+ folders.push(folder);
+ const path = join(folder, "config.json");
+ writeFileSync(path, JSON.stringify(config));
+ return path;
+ };
+ afterEach(() => { for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true }); });
+
+ it("writes the encrypted store before it blanks the file", async () => {
+ const path = configFile({ openai: { key: "openai-secret" }, profile: { name: "Ada" } });
+ const save = vi.fn(async () => { expect(readFileSync(path, "utf8")).toContain("openai-secret"); });
+ const credentials = await migrateWorkspaceConfigFile({ configPath: path, credentials: { boxToken: "kept" }, save, log: vi.fn() });
+ expect(save).toHaveBeenCalledExactlyOnceWith({ boxToken: "kept", openaiApiKey: "openai-secret" });
+ expect(credentials).toEqual({ boxToken: "kept", openaiApiKey: "openai-secret" });
+ expect(readFileSync(path, "utf8")).not.toContain("openai-secret");
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual({ openai: {}, profile: { name: "Ada" } });
+ expect(readdirSync(join(path, ".."))).toEqual(["config.json"]);
+ });
+
+ it("leaves every key in the file and the store unchanged when encryption is unavailable", async () => {
+ const before = { anthropic: { key: "ant-secret" }, groq: { key: "gsk-secret" } };
+ const path = configFile(before);
+ const log = vi.fn();
+ const stored = { boxToken: "kept" };
+ const save = vi.fn().mockRejectedValue(new Error("The operating-system credential store is unavailable"));
+ const credentials = await migrateWorkspaceConfigFile({ configPath: path, credentials: stored, save, log });
+ expect(credentials).toBe(stored);
+ expect(JSON.parse(readFileSync(path, "utf8"))).toEqual(before);
+ expect(log).toHaveBeenCalledExactlyOnceWith("credential migration failed: The operating-system credential store is unavailable");
+ });
+
+ it("keeps the encrypted copy when the file cannot be rewritten afterwards, so no key is lost", async () => {
+ const path = configFile({ mistral: { key: "mistral-secret" } });
+ const save = vi.fn(async () => { rmSync(join(path, ".."), { recursive: true, force: true }); });
+ const credentials = await migrateWorkspaceConfigFile({ configPath: path, credentials: {}, save, log: vi.fn() });
+ expect(save).toHaveBeenCalledOnce();
+ expect(credentials).toEqual({ mistralApiKey: "mistral-secret" });
+ });
+
+ it("changes nothing when there is no config.json yet", async () => {
+ const path = join(configFile({}), "..", "absent", "config.json");
+ const log = vi.fn();
+ const save = vi.fn();
+ await expect(migrateWorkspaceConfigFile({ configPath: path, credentials: { boxToken: "kept" }, save, log })).resolves.toEqual({ boxToken: "kept" });
+ expect(save).not.toHaveBeenCalled();
+ expect(log).not.toHaveBeenCalled();
+ });
+});
diff --git a/scripts/testing/key-readback.e2e.test.ts b/scripts/testing/key-readback.e2e.test.ts
index b475f5bfe3..25e8941148 100644
--- a/scripts/testing/key-readback.e2e.test.ts
+++ b/scripts/testing/key-readback.e2e.test.ts
@@ -135,6 +135,7 @@ it("saves every kind of credential, reads it back and shows it masked to its las
const config = (await call("GET", "/api/config")).body;
expect(savedState(entry, config as never), `${entry.id}${storage}`).toEqual({ configured: true, last4 });
+ if (storage) expect(readFileSync(join(fixture.info.dataDir, "config.json"), "utf8"), `${entry.id} config.json`).not.toContain(key);
expect(JSON.stringify(config), entry.id).not.toContain(key);
view.config = config;
const html = renderToStaticMarkup(createElement(KeyCatalogRow, { entry }));
diff --git a/server/config.test.ts b/server/config.test.ts
index ba5c827a9b..55def9d46b 100644
--- a/server/config.test.ts
+++ b/server/config.test.ts
@@ -2437,3 +2437,23 @@ describe("DATA_DIR outside the suite's throwaway home", () => {
}
});
});
+
+describe("a key the desktop app hands the server as an environment variable", () => {
+ afterEach(() => vi.unstubAllEnvs());
+
+ it.each([
+ ["OMB_OPENAI_API_KEY", "openai", "OMB_OPENAI_API_KEY"],
+ ["OMB_ANTHROPIC_API_KEY", "claudeApi", "ANTHROPIC_API_KEY"],
+ ["OMB_OPENROUTER_API_KEY", "openrouter", "OMB_OPENROUTER_API_KEY"],
+ ["MISTRAL_API_KEY", "mistral", "MISTRAL_API_KEY"],
+ ["CEREBRAS_API_KEY", "cerebras", "CEREBRAS_API_KEY"],
+ ["OMB_GROQ_API_KEY", "groq", "GROQ_API_KEY"],
+ ["OMB_GREENFERENCE_API_KEY", "greenference", "GREENFERENCE_API_KEY"],
+ ["OMB_META_API_KEY", "meta", "META_API_KEY"],
+ ["OMB_DEEPSEEK_API_KEY", "deepseek", "DEEPSEEK_API_KEY"],
+ ["OPENAI_COMPAT_API_KEY", "openaiCompat", "OPENAI_COMPAT_API_KEY"],
+ ])("reaches its engine: %s", (variable, instanceId, engineEnv) => {
+ vi.stubEnv(variable, `fixture-${variable}`);
+ expect(instanceConfigs(loadConfig())[instanceId]?.environment?.[engineEnv]).toBe(`fixture-${variable}`);
+ });
+});
diff --git a/server/credential-env.ts b/server/credential-env.ts
index 7a7c4a7c33..bd7815a2c9 100644
--- a/server/credential-env.ts
+++ b/server/credential-env.ts
@@ -57,6 +57,14 @@ export function stripWorkspaceCredentialEnv(env: Record<string, string | undefin
stripControlPlaneEnv(env);
}
+const DESKTOP_STORE_KEY_ENV: ReadonlySet<string> = new Set(["MISTRAL_API_KEY", "CEREBRAS_API_KEY", "OPENAI_COMPAT_API_KEY", "OMB_OPENAI_API_KEY", "OMB_OPENROUTER_API_KEY"]);
+
+/** A key an operator set on the server. Security: under the desktop app these variables hold workspace keys from its
+ * encrypted store, which reach only the instances the workspace routes, never one with a URL of its own. */
+export function operatorEnvKey(name: string, env: NodeJS.ProcessEnv = process.env): string | undefined {
+ return env.OMB_DESKTOP_PARENT === "1" && DESKTOP_STORE_KEY_ENV.has(name) ? undefined : env[name];
+}
+
/** Env a provider CLI may read as its billing identity; a foreign key must never move a subscription CLI onto API billing. */
export const PROVIDER_CREDENTIAL_ENV = [
"CLINE_API_KEY",
diff --git a/server/credential-request.test.ts b/server/credential-request.test.ts
index 30ce1f4dbd..691841723d 100644
--- a/server/credential-request.test.ts
+++ b/server/credential-request.test.ts
@@ -70,13 +70,10 @@ describe("credential request allowlist", () => {
expect(Object.keys(CREDENTIAL_TARGETS)).toHaveLength(18);
});
- // The desktop's encrypted store has a slot only for these; a provider key goes to the server's config, as Settings does.
- it("names the desktop slot a key is saved in, and none for a provider key or the 1Password token", () => {
- expect(Object.keys(CREDENTIAL_TARGETS).filter((id) => desktopCredentialSlot(id as never)).sort()).toEqual(
- ["boxToken", "composioApiKey", "fishAudioKey", "geminiTtsKey", "openaiImageApiKey", "opencodeGoApiKey", "ttsKey", "xaiApiKey"],
- );
- expect(desktopCredentialSlot("anthropicApiKey")).toBeNull();
- expect(desktopCredentialSlot("onePasswordToken")).toBeNull();
+ it("names the desktop slot a key is saved in, and none for the 1Password token", () => {
+ expect(Object.keys(CREDENTIAL_TARGETS).filter((id) => !desktopCredentialSlot(id as never))).toEqual(["onePasswordToken"]);
+ expect(desktopCredentialSlot("anthropicApiKey")).toBe("anthropicApiKey");
+ expect(desktopCredentialSlot("xaiApiKey")).toBe("xaiApiKey");
});
it("supersedes a bot's own pending custom secret of the same name only", () => {
diff --git a/server/drivers/cerebras.test.ts b/server/drivers/cerebras.test.ts
index 729238dc4b..1ea9d7e390 100644
--- a/server/drivers/cerebras.test.ts
+++ b/server/drivers/cerebras.test.ts
@@ -26,6 +26,17 @@ describe("Cerebras provider", () => {
expect(CerebrasDriver.decodeConfig({ url: "http://127.0.0.1:1234/v1/" }).url).toBe("http://127.0.0.1:1234/v1");
});
+ it("keeps the desktop store's workspace key away from an instance with its own URL", async () => {
+ vi.stubEnv("OMB_DESKTOP_PARENT", "1");
+ vi.stubEnv("CEREBRAS_API_KEY", "fixture-workspace-key");
+ const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher);
+ const instance = await CerebrasDriver.create({ instanceId: "own-url", displayName: "Mine", enabled: true,
+ config: CerebrasDriver.decodeConfig({ url: "https://mine.example.test/v1" }), environment: {} });
+ expect(await instance.snapshot()).toMatchObject({ state: "unavailable" });
+ expect(fetcher).not.toHaveBeenCalled();
+ await instance.dispose();
+ });
+
it("does not contact the provider without a key", async () => {
vi.stubEnv("CEREBRAS_API_KEY", "");
const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher);
diff --git a/server/drivers/cerebras.ts b/server/drivers/cerebras.ts
index 67275cefde..bd2b5d99ab 100644
--- a/server/drivers/cerebras.ts
+++ b/server/drivers/cerebras.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import type { ModelCatalog, ProviderDriver } from "../contracts.ts";
+import { operatorEnvKey } from "../credential-env.ts";
import { createOpenAIChatRuntime } from "./openai-chat.ts";
const DEFAULT_URL = "https://api.cerebras.ai/v1";
@@ -48,7 +49,7 @@ export const CerebrasDriver: ProviderDriver<CerebrasConfig> = {
defaultConfig: () => decodeConfig({}),
async create(input) {
const { config } = input;
- const apiKey = (input.environment.CEREBRAS_API_KEY ?? process.env.CEREBRAS_API_KEY ?? "").trim();
+ const apiKey = (input.environment.CEREBRAS_API_KEY ?? operatorEnvKey("CEREBRAS_API_KEY") ?? "").trim();
const known = new Map(DEFAULT_MODELS.options.map((option) => [option.id, option]));
const withConfiguredModel = (options: ModelCatalog["options"]): ModelCatalog => {
const preferred = config.model ?? DEFAULT_MODELS.default;
diff --git a/server/drivers/mistral.test.ts b/server/drivers/mistral.test.ts
index c2fba04297..56ee5d78d1 100644
--- a/server/drivers/mistral.test.ts
+++ b/server/drivers/mistral.test.ts
@@ -28,6 +28,17 @@ describe("Mistral provider", () => {
await instance.dispose();
});
+ it("keeps the desktop store's workspace key away from an instance with its own URL", async () => {
+ vi.stubEnv("OMB_DESKTOP_PARENT", "1");
+ vi.stubEnv("MISTRAL_API_KEY", "fixture-workspace-key");
+ const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher);
+ const instance = await MistralDriver.create({ instanceId: "own-url", displayName: "Mine", enabled: true,
+ config: MistralDriver.decodeConfig({ url: "https://mine.example.test/v1" }), environment: {} });
+ expect(await instance.snapshot()).toMatchObject({ state: "unavailable" });
+ expect(fetcher).not.toHaveBeenCalled();
+ await instance.dispose();
+ });
+
it("discovers versioned chat models and aliases while excluding archived and non-chat entries", async () => {
let data: unknown = { data: [
{ id: "mistral-large-2512", name: "Mistral Large 3", aliases: ["mistral-large-latest", "mistral-large-2512"], max_context_length: 262144, capabilities: { completion_chat: true } },
diff --git a/server/drivers/mistral.ts b/server/drivers/mistral.ts
index 1c04738402..908f4909d4 100644
--- a/server/drivers/mistral.ts
+++ b/server/drivers/mistral.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import type { ModelCatalog, ProviderDriver } from "../contracts.ts";
+import { operatorEnvKey } from "../credential-env.ts";
import { createOpenAIChatRuntime } from "./openai-chat.ts";
const DEFAULT_URL = "https://api.mistral.ai/v1";
@@ -57,7 +58,7 @@ export const MistralDriver: ProviderDriver<MistralConfig> = {
defaultConfig: () => decodeConfig({}),
async create(input) {
const { config } = input;
- const apiKey = (input.environment.MISTRAL_API_KEY ?? process.env.MISTRAL_API_KEY ?? "").trim();
+ const apiKey = (input.environment.MISTRAL_API_KEY ?? operatorEnvKey("MISTRAL_API_KEY") ?? "").trim();
const withConfiguredModel = (options: ModelCatalog["options"]): ModelCatalog => {
const preferred = config.model ?? DEFAULT_MODELS.default;
if (config.model && !options.some((option) => option.id === config.model)) {
diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.ts
index af64a1bcc0..0722c5fade 100644
--- a/server/drivers/openai-compat.test.ts
+++ b/server/drivers/openai-compat.test.ts
@@ -220,6 +220,24 @@ describe("OpenAICompatDriver", () => {
await inst.dispose();
});
+ it("keeps the desktop store's workspace key away from an instance with its own URL", async () => {
+ vi.stubEnv("OMB_DESKTOP_PARENT", "1");
+ process.env.OPENAI_COMPAT_API_KEY = "sk-or-STORE";
+ const seen: string[] = [];
+ vi.stubGlobal("fetch", vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
+ seen.push(JSON.stringify(init?.headers ?? {}));
+ return new Response('{"data":[]}', { headers: { "content-type": "application/json" } });
+ }));
+ const inst = await OpenAICompatDriver.create({
+ instanceId: "router", displayName: "Router", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({ url: "https://third-party.example.test/v1" }), environment: {},
+ });
+ await inst.refreshModels?.();
+ await inst.snapshot();
+ expect(JSON.stringify(seen)).not.toContain("STORE");
+ await inst.dispose();
+ });
+
it("rejects remote HTTP computer use before starting tools or a completion request", async () => {
const request = vi.fn(async (_url: string | URL | Request) => new Response('{"data":[]}', { headers: { "content-type": "application/json" } }));
vi.stubGlobal("fetch", request);
diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.ts
index 606e3b5bd9..0c7bd56807 100644
--- a/server/drivers/openai-compat.ts
+++ b/server/drivers/openai-compat.ts
@@ -1,6 +1,7 @@
// Transcript-replay driver for OpenRouter, Groq, Together, llama.cpp, and
// other endpoints that speak the OpenAI chat-completions contract.
import type { ModelCatalog, ProviderDriver } from "../contracts.ts";
+import { operatorEnvKey } from "../credential-env.ts";
import { isLoopback } from "../provider-key-check.ts";
import { lmStudioV1Catalog } from "./local-inject.ts";
import { isContextName, isOllama, serveWithWindow } from "./ollama-context.ts";
@@ -187,8 +188,8 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {
config.key ??
input.environment[config.apiKeyEnv] ??
(ownKeyVariable ? undefined : input.environment[DEFAULT_KEY_ENV]) ??
- process.env[config.apiKeyEnv] ??
- (ownKeyVariable ? undefined : process.env[DEFAULT_KEY_ENV]) ??
+ operatorEnvKey(config.apiKeyEnv) ??
+ (ownKeyVariable ? undefined : operatorEnvKey(DEFAULT_KEY_ENV)) ??
"";
// A server someone gave a fixed model list to is not asked what else it might be, unless it is on Ollama's own port.
const ollamaCandidate = config.catalog === "ollama" || (config.catalog === undefined && (onOllamaPort(config.url) || (onThisNetwork(config.url) && !config.managedModels)));
diff --git a/server/phone-secret.ts b/server/phone-secret.ts
index 3d893d1f00..1ff6f3a022 100644
--- a/server/phone-secret.ts
+++ b/server/phone-secret.ts
@@ -1,6 +1,6 @@
import { createECDH, createHash, type webcrypto } from "node:crypto";
-import { desktopCredentialSlot, isCredentialTargetId } from "../shared/credential-request.ts";
+import { isCredentialTargetId, isProviderCredentialTarget } from "../shared/credential-request.ts";
import type { CipherSuite } from "@hpke/core";
export const PHONE_SECRET_PROTOCOL_VERSION = 1 as const;
@@ -139,7 +139,7 @@ export function assertPhoneSecretRequestMatches(
throw new PhoneSecretError("Paste the 1Password token in OpenMausBot on your computer, or in My Cloud: a phone cannot save it yet.", 409);
}
// An AI provider key lives in the server's settings, which only the computer's own app writes.
- if (isCredentialTargetId(expected.target) && !desktopCredentialSlot(expected.target)) {
+ if (isCredentialTargetId(expected.target) && isProviderCredentialTarget(expected.target)) {
throw new PhoneSecretError("Paste this key in OpenMausBot on your computer, or in My Cloud: a phone cannot save it yet.", 409);
}
if (
diff --git a/server/routes/config.ts b/server/routes/config.ts
index 853180f865..ddf69df1d0 100644
--- a/server/routes/config.ts
+++ b/server/routes/config.ts
@@ -540,6 +540,16 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {
if (externalSecretStorage) {
// Supplied credentials are already in the OS-encrypted store: tombstone them so no older plaintext survives the merge.
const persisted = structuredClone(patch);
+ if (persisted.openai?.key !== undefined) persisted.openai.key = "";
+ if (persisted.anthropic?.key !== undefined) persisted.anthropic.key = "";
+ if (persisted.openrouter?.key !== undefined) persisted.openrouter.key = "";
+ if (persisted.mistral?.key !== undefined) persisted.mistral.key = "";
+ if (persisted.cerebras?.key !== undefined) persisted.cerebras.key = "";
+ if (persisted.groq?.key !== undefined) persisted.groq.key = "";
+ if (persisted.greenference?.key !== undefined) persisted.greenference.key = "";
+ if (persisted.meta?.key !== undefined) persisted.meta.key = "";
+ if (persisted.deepseek?.key !== undefined) persisted.deepseek.key = "";
+ if (persisted.openaiCompat?.key !== undefined) persisted.openaiCompat.key = "";
if (persisted.xai?.key !== undefined) persisted.xai.key = "";
if (persisted.composio?.apiKey !== undefined) persisted.composio.apiKey = "";
if (persisted.box?.token !== undefined) persisted.box.token = "";
diff --git a/shared/credential-request.ts b/shared/credential-request.ts
index b47de02684..471b2a8645 100644
--- a/shared/credential-request.ts
+++ b/shared/credential-request.ts
@@ -118,11 +118,11 @@ export type CredentialTargetId = keyof typeof CREDENTIAL_TARGETS;
/** Saved in the sealed login store, not the settings file. */
export type LoginCredentialTargetId = "onePasswordToken";
export type ConfigCredentialTargetId = Exclude<CredentialTargetId, LoginCredentialTargetId>;
-/** AI provider keys: the server's config only, like Settings → Keys, and refused where Admin manages the models. */
+/** AI provider keys: refused where Admin manages the models, and typed only in the computer's own app or a desktop paired to it, never on a phone. */
export const PROVIDER_CREDENTIAL_TARGETS = [
"openaiApiKey", "anthropicApiKey", "openrouterApiKey", "mistralApiKey", "cerebrasApiKey", "groqApiKey", "greenferenceApiKey", "metaApiKey", "deepseekApiKey",
] as const satisfies readonly ConfigCredentialTargetId[];
-export type DesktopCredentialSlot = Exclude<ConfigCredentialTargetId, (typeof PROVIDER_CREDENTIAL_TARGETS)[number]>;
+export type DesktopCredentialSlot = ConfigCredentialTargetId;
export type CredentialConfig = {
xai?: { key?: string };
box?: { token?: string };
@@ -162,10 +162,9 @@ export function isProviderCredentialTarget(id: CredentialTargetId): boolean {
return (PROVIDER_CREDENTIAL_TARGETS as readonly string[]).includes(id);
}
-/** The desktop's encrypted-store slot that holds this key, where Settings saves it; null for a key Settings keeps in the
- * server's config. A paired phone can save only a key with a slot. */
+/** The desktop's encrypted-store slot that holds this key, where Settings saves it; null for the 1Password token, which Logins keeps. */
export function desktopCredentialSlot(id: CredentialTargetId): DesktopCredentialSlot | null {
- return isConfigCredentialTarget(id) && !isProviderCredentialTarget(id) ? id as DesktopCredentialSlot : null;
+ return isConfigCredentialTarget(id) ? id : null;
}
/** Where a card saves what the person typed: the 1Password token goes to Logins, which checks it reaches 1Password. */
diff --git a/src/components/SecretRequestCard.test.ts b/src/components/SecretRequestCard.test.ts
index 50a898e72c..390ea484cc 100644
--- a/src/components/SecretRequestCard.test.ts
+++ b/src/components/SecretRequestCard.test.ts
@@ -329,15 +329,23 @@ describe("SecretRequestCard key analytics", () => {
expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "xai", via: "chat_request", result: "unverified" }]]);
});
- // Settings keeps an AI provider key in the server's settings, not the desktop's store: the card does the same.
- it("saves an Anthropic key where Settings does, never through the desktop store, keeping Claude sign-ins", async () => {
- const setCredential = vi.fn();
+ it("saves an Anthropic key in the desktop store as Settings does, keeping Claude sign-ins", async () => {
+ const setCredential = vi.fn().mockResolvedValue({ anthropic: { configured: true } });
vi.stubGlobal("window", { ogb: { setCredential } });
+ fixture.api.mockResolvedValueOnce({ ok: true });
+ await submit("anthropicApiKey", "sk-ant-ZZtestSECRET0123456789");
+ expect(setCredential).toHaveBeenCalledExactlyOnceWith("anthropicApiKey", "sk-ant-ZZtestSECRET0123456789", { everyClaudeBot: false });
+ expect(fixture.api.mock.calls.map(([path]) => path)).toEqual(["/api/bots/bot-1/secret-cards/secret-card/provided"]);
+ expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "anthropic", via: "chat_request", result: "unverified" }]]);
+ });
+
+ it("sends a provider key typed on a desktop paired to another computer to that computer's server", async () => {
+ const setCredential = vi.fn();
+ vi.stubGlobal("window", { ogb: { setCredential, remoteClient: { active: true } } });
fixture.api.mockResolvedValueOnce({ anthropic: { configured: true } }).mockResolvedValueOnce({ ok: true });
await submit("anthropicApiKey", "sk-ant-ZZtestSECRET0123456789");
expect(setCredential).not.toHaveBeenCalled();
expect(fixture.api.mock.calls[0]).toEqual(["/api/config", { method: "PUT", body: JSON.stringify({ anthropic: { key: "sk-ant-ZZtestSECRET0123456789", everyClaudeBot: false } }) }]);
- expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "anthropic", via: "chat_request", result: "unverified" }]]);
});
it("saves the Composio key in the desktop store's slot, as Settings does", async () => {
diff --git a/src/components/SecretRequestCard.tsx b/src/components/SecretRequestCard.tsx
index 9effa958e4..a6816aec6f 100644
--- a/src/components/SecretRequestCard.tsx
+++ b/src/components/SecretRequestCard.tsx
@@ -1,7 +1,7 @@
import { useState, type FormEvent } from "react";
import { ExternalLink, KeyRound, Loader2, LockKeyhole, RefreshCw, X } from "lucide-react";
-import { CUSTOM_SECRET_TARGET, credentialResumeOutcome, credentialSaveRequest, desktopCredentialSlot, isConfigCredentialTarget } from "../../shared/credential-request";
+import { CUSTOM_SECRET_TARGET, credentialResumeOutcome, credentialSaveRequest, desktopCredentialSlot, isConfigCredentialTarget, isProviderCredentialTarget } from "../../shared/credential-request";
import { credentialProvider } from "@/lib/analytics-allowlist";
import { cn } from "@/lib/cn";
import { activeLocale, t } from "@/lib/i18n";
@@ -13,6 +13,7 @@ import { EmailOutgoingRequestForm, EmailRequestSettled } from "./EmailRequestCar
import type { EmailConnectRequest, EmailOutgoingFields } from "../../shared/email";
import { productName } from "@/lib/brand";
import { VaultChoices } from "./VaultChoices";
+import { desktopStore } from "./keys/key-save";
// Security: the value goes straight to the host's settings, never into the chat.
@@ -50,7 +51,7 @@ export function SecretRequestCard({
const custom = secret.target === CUSTOM_SECRET_TARGET;
// A page reached through a desktop paired to another computer: a key that computer keeps in its own encrypted store can
// only be typed there. Anything its server keeps, a custom secret or a provider key, is typed here like on any page.
- const onlyOnHost = window.ogb?.remoteClient?.active === true && secret.target !== CUSTOM_SECRET_TARGET && desktopCredentialSlot(secret.target) !== null;
+ const onlyOnHost = window.ogb?.remoteClient?.active === true && secret.target !== CUSTOM_SECRET_TARGET && desktopCredentialSlot(secret.target) !== null && !isProviderCredentialTarget(secret.target);
const outcome = credentialResumeOutcome(secret);
const provided = outcome === "provided";
const declined = outcome === "dismissed";
@@ -156,10 +157,10 @@ export function SecretRequestCard({
const target = secret.target;
// The 1Password token goes to this server's Logins, which checks it with 1Password first, never the settings file.
const request = credentialSaveRequest(target, next);
- const slot = desktopCredentialSlot(target);
+ const store = desktopStore(desktopCredentialSlot(target));
if (isConfigCredentialTarget(target)) {
- const status: ConfigStatus = slot && window.ogb?.setCredential
- ? await window.ogb.setCredential(slot, next)
+ const status: ConfigStatus = store
+ ? await store(next, target === "anthropicApiKey" ? { everyClaudeBot: false } : undefined)
: await api(request.path, { method: request.method, body: JSON.stringify(request.body) });
dispatch({ type: "configStatus", config: status });
} else await api(request.path, { method: request.method, body: JSON.stringify(request.body) });
diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts
index ae05b8219a..7c6127c125 100644
--- a/src/components/keys/key-catalog.ts
+++ b/src/components/keys/key-catalog.ts
@@ -20,12 +20,14 @@ export const KEY_SECTIONS: ReadonlyArray<{ id: KeySectionId; titleKey: LocaleKey
export type TestableProvider = "anthropic" | "openai" | "openrouter" | "openaiCompat" | "xai" | "mistral" | "cerebras" | "groq" | "greenference" | "meta" | "treg";
export type DesktopSlot = Parameters<NonNullable<NonNullable<Window["ogb"]>["setCredential"]>>[0];
+export type DesktopSlotOptions = NonNullable<Parameters<NonNullable<NonNullable<Window["ogb"]>["setCredential"]>>[2]>;
export interface SavedState { configured: boolean; last4?: string; included?: boolean }
export interface KeyTarget {
patch: (value: string, firstKey: boolean) => Record<string, unknown>;
slot?: DesktopSlot;
+ storeOptions?: (value: string, firstKey: boolean) => DesktopSlotOptions | undefined;
saved: (config: ConfigStatus) => SavedState;
placeholder: string;
placeholderKey?: LocaleKey;
@@ -78,35 +80,36 @@ const provider = (driverKind: string, preset?: ProviderIconPreset): KeyMark => (
export const KEY_CATALOG: readonly KeyEntry[] = [
{ id: "openai", section: "ai", labelKey: "keys.openai.label", purposeKey: "keys.purpose.openaiModelsVoice", name: "OpenAI", env: ["OMB_OPENAI_API_KEY"],
words: ["openai", "chatgpt", "gpt", "live calls"], mark: provider("openai-compat", "openai"), kind: "key",
- target: providerKey("openai", { placeholder: "sk-…", href: "https://platform.openai.com/api-keys", test: "openai", analytics: "openai", shape: OPENAI_SHAPE, noteKey: "keys.openai.note" }) },
+ target: providerKey("openai", { slot: "openaiApiKey", placeholder: "sk-…", href: "https://platform.openai.com/api-keys", test: "openai", analytics: "openai", shape: OPENAI_SHAPE, noteKey: "keys.openai.note" }) },
{ id: "anthropic", section: "ai", labelKey: "keys.anthropic.label", purposeKey: "keys.purpose.anthropic", name: "Anthropic", env: ["OMB_ANTHROPIC_API_KEY"],
words: ["anthropic", "claude"], mark: provider("claudeAgent", "anthropic"), kind: "key",
target: { patch: (value, firstKey) => ({ anthropic: { key: value, ...(firstKey && value ? { everyClaudeBot: false } : {}) } }), saved: (config) => flag(config.anthropic),
+ slot: "anthropicApiKey", storeOptions: (value, firstKey) => firstKey && value ? { everyClaudeBot: false } : undefined,
placeholder: "sk-ant-…", href: "https://console.anthropic.com/settings/keys", test: "anthropic", analytics: "anthropic", shape: /^sk-ant-/ } },
{ id: "xai", section: "ai", labelKey: "keys.xai.label", purposeKey: "keys.purpose.xai", name: "xAI", env: ["XAI_API_KEY"],
words: ["xai", "grok", "pictures", "images"], mark: provider("grok", "xai"), kind: "key",
target: providerKey("xai", { slot: "xaiApiKey", placeholder: "xai-…", href: "https://console.x.ai", test: "xai", analytics: "xai", shape: /^xai-/ }) },
{ id: "openrouter", section: "ai", labelKey: "keys.openrouter.label", purposeKey: "keys.purpose.openrouter", name: "OpenRouter", env: ["OMB_OPENROUTER_API_KEY"],
words: ["openrouter", "router", "models"], mark: provider("openai-compat", "openrouter"), kind: "key",
- target: providerKey("openrouter", { placeholder: "sk-or-v1-…", href: "https://openrouter.ai/keys", test: "openrouter", analytics: "openrouter", shape: /^sk-or-/ }) },
+ target: providerKey("openrouter", { slot: "openrouterApiKey", placeholder: "sk-or-v1-…", href: "https://openrouter.ai/keys", test: "openrouter", analytics: "openrouter", shape: /^sk-or-/ }) },
{ id: "mistral", section: "ai", labelKey: "keys.mistral.label", purposeKey: "keys.purpose.mistral", name: "Mistral", env: ["MISTRAL_API_KEY"],
words: ["mistral"], mark: provider("mistral", "mistral"), kind: "key",
- target: providerKey("mistral", { placeholder: "…", placeholderKey: "keys.mistral.placeholder", href: "https://console.mistral.ai/api-keys", test: "mistral", analytics: "mistral" }) },
+ target: providerKey("mistral", { slot: "mistralApiKey", placeholder: "…", placeholderKey: "keys.mistral.placeholder", href: "https://console.mistral.ai/api-keys", test: "mistral", analytics: "mistral" }) },
{ id: "cerebras", section: "ai", labelKey: "keys.cerebras.label", purposeKey: "keys.purpose.cerebras", name: "Cerebras", env: ["CEREBRAS_API_KEY"],
words: ["cerebras", "fast"], mark: provider("cerebras"), kind: "key",
- target: providerKey("cerebras", { placeholder: "csk-…", href: "https://cloud.cerebras.ai/", test: "cerebras", analytics: "cerebras", shape: /^csk-/ }) },
+ target: providerKey("cerebras", { slot: "cerebrasApiKey", placeholder: "csk-…", href: "https://cloud.cerebras.ai/", test: "cerebras", analytics: "cerebras", shape: /^csk-/ }) },
{ id: "groq", section: "ai", labelKey: "keys.groq.label", purposeKey: "keys.purpose.groq", name: "Groq", env: ["OMB_GROQ_API_KEY"],
words: ["groq", "fast"], mark: provider("groq"), kind: "key",
- target: providerKey("groq", { placeholder: "gsk_…", href: "https://console.groq.com/keys", test: "groq", analytics: "groq", shape: /^gsk_/ }) },
+ target: providerKey("groq", { slot: "groqApiKey", placeholder: "gsk_…", href: "https://console.groq.com/keys", test: "groq", analytics: "groq", shape: /^gsk_/ }) },
{ id: "greenference", section: "ai", labelKey: "keys.greenference.label", purposeKey: "keys.purpose.greenference", name: "Greenference", env: ["OMB_GREENFERENCE_API_KEY"],
words: ["greenference", "green", "open models"], mark: provider("greenference"), kind: "key",
- target: providerKey("greenference", { placeholder: "…", placeholderKey: "keys.greenference.placeholder", href: "https://greenference.com/dashboard/tokens", test: "greenference", analytics: "greenference" }) },
+ target: providerKey("greenference", { slot: "greenferenceApiKey", placeholder: "…", placeholderKey: "keys.greenference.placeholder", href: "https://greenference.com/dashboard/tokens", test: "greenference", analytics: "greenference" }) },
{ id: "meta", section: "ai", labelKey: "keys.meta.label", purposeKey: "keys.purpose.meta", name: "Meta", env: ["OMB_META_API_KEY"],
words: ["meta", "muse", "llama"], mark: provider("meta", "meta"), kind: "key",
- target: providerKey("meta", { placeholder: "LLM|…", href: "https://dev.meta.ai/docs/authentication", test: "meta", analytics: "meta", shape: /^LLM\|/ }) },
+ target: providerKey("meta", { slot: "metaApiKey", placeholder: "LLM|…", href: "https://dev.meta.ai/docs/authentication", test: "meta", analytics: "meta", shape: /^LLM\|/ }) },
{ id: "deepseek", section: "ai", labelKey: "keys.deepseek.label", purposeKey: "keys.purpose.deepseek", name: "DeepSeek", env: ["OMB_DEEPSEEK_API_KEY"],
words: ["deepseek", "dsh", "harness"], mark: provider("deepseekAgent", "deepseek"), kind: "key",
- target: providerKey("deepseek", { placeholder: "sk-…", href: "https://platform.deepseek.com/api_keys", analytics: "deepseek" }) },
+ target: providerKey("deepseek", { slot: "deepseekApiKey", placeholder: "sk-…", href: "https://platform.deepseek.com/api_keys", analytics: "deepseek" }) },
{ id: "opencodeGo", section: "ai", labelKey: "keys.opencode.label", purposeKey: "keys.purpose.opencodeGo", name: "OpenCode", env: ["OPENCODE_API_KEY"],
words: ["opencode", "zen", "go"], mark: provider("opencodeGo"), kind: "key",
target: { patch: (value) => ({ opencodeGo: { apiKey: value } }), slot: "opencodeGoApiKey", saved: (config) => flag(config.opencodeGo),
@@ -118,7 +121,7 @@ export const KEY_CATALOG: readonly KeyEntry[] = [
words: ["lm studio", "lmstudio", "llm studio", "local", "bionic"], mark: { icon: Server }, kind: "panel" },
{ id: "openaiCompat", section: "servers", labelKey: "keys.openaiCompat.label", purposeKey: "keys.purpose.openaiCompat", name: "OpenAI-compatible", env: ["OPENAI_COMPAT_API_KEY", "OPENAI_COMPAT_URL"],
words: ["openai-compatible", "openai compatible", "ollama", "together", "gemini", "google ai studio", "base url", "server", "endpoint"], mark: { icon: Server }, kind: "key",
- target: { patch: (value) => ({ openaiCompat: { key: value } }), saved: (config) => flag(config.openaiCompat), placeholder: "…", placeholderKey: "keys.openaiCompat.placeholder",
+ target: { patch: (value) => ({ openaiCompat: { key: value } }), slot: "openaiCompatApiKey", saved: (config) => flag(config.openaiCompat), placeholder: "…", placeholderKey: "keys.openaiCompat.placeholder",
href: "https://platform.openai.com/docs/api-reference", test: "openaiCompat", analytics: "openai_compat" } },
{ id: "liveCalls", section: "voice", labelKey: "call.live.key", purposeKey: "keys.purpose.liveCalls", name: "OpenAI", env: [],
words: ["openai", "live calls", "calls", "voice", "talk", "gpt-live", "read aloud", "speech", "tts"], mark: { icon: Phone }, kind: "uses", uses: "openai" },
diff --git a/src/components/keys/key-save.test.ts b/src/components/keys/key-save.test.ts
new file mode 100644
index 0000000000..ea44abae79
--- /dev/null
+++ b/src/components/keys/key-save.test.ts
@@ -0,0 +1,49 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const fixture = vi.hoisted(() => ({ api: vi.fn() }));
+vi.mock("@/state/store", async (original) => ({ ...await original<typeof import("@/state/store")>(), api: fixture.api }));
+
+import { keyEntry, type KeyId } from "./key-catalog";
+import { saveKey } from "./key-save";
+
+const SLOTS: Array<[KeyId, string]> = [
+ ["openai", "openaiApiKey"], ["anthropic", "anthropicApiKey"], ["openrouter", "openrouterApiKey"], ["mistral", "mistralApiKey"], ["cerebras", "cerebrasApiKey"],
+ ["groq", "groqApiKey"], ["greenference", "greenferenceApiKey"], ["meta", "metaApiKey"], ["deepseek", "deepseekApiKey"], ["openaiCompat", "openaiCompatApiKey"],
+];
+
+beforeEach(() => fixture.api.mockReset().mockResolvedValue({}));
+afterEach(() => vi.unstubAllGlobals());
+
+describe("saving an AI provider key", () => {
+ it.each(SLOTS)("keeps %s in the desktop's encrypted store, and removes it there too", async (id, slot) => {
+ const setCredential = vi.fn().mockResolvedValue({});
+ vi.stubGlobal("window", { ogb: { setCredential } });
+ await saveKey(keyEntry(id).target!, "fixture-key", false);
+ await saveKey(keyEntry(id).target!, "", false);
+ expect(setCredential.mock.calls).toEqual([[slot, "fixture-key"], [slot, ""]]);
+ expect(fixture.api).not.toHaveBeenCalled();
+ });
+
+ it("carries the first Anthropic key's choice to leave Claude sign-ins alone", async () => {
+ const setCredential = vi.fn().mockResolvedValue({});
+ vi.stubGlobal("window", { ogb: { setCredential } });
+ await saveKey(keyEntry("anthropic").target!, "fixture-key", true);
+ expect(setCredential).toHaveBeenCalledExactlyOnceWith("anthropicApiKey", "fixture-key", { everyClaudeBot: false });
+ });
+
+ it.each(SLOTS)("uses the server's config for %s with no desktop store, as a Cloud page or a browser has none", async (id) => {
+ vi.stubGlobal("window", {});
+ await saveKey(keyEntry(id).target!, "fixture-key", false);
+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/config", { method: "PUT", body: JSON.stringify(keyEntry(id).target!.patch("fixture-key", false)) });
+ });
+
+ it("sends a provider key to the host's server from a desktop paired to it, but not a key the host keeps encrypted", async () => {
+ const setCredential = vi.fn().mockResolvedValue({});
+ vi.stubGlobal("window", { ogb: { setCredential, remoteClient: { active: true } } });
+ await saveKey(keyEntry("openai").target!, "fixture-key", false);
+ expect(setCredential).not.toHaveBeenCalled();
+ expect(fixture.api).toHaveBeenCalledOnce();
+ await saveKey(keyEntry("box").target!, "fixture-key", false);
+ expect(setCredential).toHaveBeenCalledExactlyOnceWith("boxToken", "fixture-key");
+ });
+});
diff --git a/src/components/keys/key-save.ts b/src/components/keys/key-save.ts
index f0db6763d2..b836566dc0 100644
--- a/src/components/keys/key-save.ts
+++ b/src/components/keys/key-save.ts
@@ -3,14 +3,26 @@ import { api, type ConfigStatus } from "@/state/store";
import { t } from "@/lib/i18n";
import { keyTestResult } from "@/lib/product-events";
import type { KeyResult } from "@/lib/analytics-allowlist";
-import { keyEntry, type KeyId, type KeyTarget, type TestableProvider } from "./key-catalog";
+import { PROVIDER_CREDENTIAL_TARGETS } from "../../../shared/credential-request";
+import { keyEntry, type DesktopSlot, type DesktopSlotOptions, type KeyId, type KeyTarget, type TestableProvider } from "./key-catalog";
+
+const HOST_SERVER_KEEPS: ReadonlySet<string> = new Set([...PROVIDER_CREDENTIAL_TARGETS, "openaiCompatApiKey"]);
+
+/** Saves into the desktop's encrypted store, or undefined when this page must use the server's config instead: an AI
+ * provider key typed through a desktop paired to another computer belongs to that computer's server, not this store. */
+export function desktopStore(slot: DesktopSlot | null | undefined) {
+ const ogb = window.ogb;
+ if (!slot || !ogb?.setCredential || (ogb.remoteClient?.active === true && HOST_SERVER_KEEPS.has(slot))) return undefined;
+ return (value: string, options?: DesktopSlotOptions) => options ? ogb.setCredential!(slot, value, options) : ogb.setCredential!(slot, value);
+}
/** Saves one credential where this app keeps it ("" removes it): the desktop's encrypted store when the key has a slot
* there, so Remove also clears the stored copy its boot migration made, else the server's own config, which on a Cloud
* home stays outside every bot's box. */
export function saveKey(target: KeyTarget, value: string, firstKey: boolean): Promise<ConfigStatus> {
- return window.ogb?.setCredential && target.slot
- ? window.ogb.setCredential(target.slot, value)
+ const store = desktopStore(target.slot);
+ return store
+ ? store(value, target.storeOptions?.(value, firstKey))
: api("/api/config", { method: "PUT", body: JSON.stringify(target.patch(value, firstKey)) });
}
diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.ts
index 0325030100..01fc4beb51 100644
--- a/src/types/ogb.d.ts
+++ b/src/types/ogb.d.ts
@@ -455,8 +455,9 @@ const __APP_VERSION__: string;
credentialStore?: { unreadable(): Promise<boolean>; reset(): Promise<"reset" | "cancelled" | "quitting" | "failed" | "readable"> };
/** Save a provider credential through Electron's OS-backed store. */
setCredential?(
- name: "composioApiKey" | "xaiApiKey" | "boxToken" | "opencodeGoApiKey" | "ttsKey" | "fishAudioKey" | "geminiTtsKey" | "jevApiKey" | "openrouterDeciderKey" | "workersAiToken" | "openaiImageApiKey" | "customImageApiKey" | "openaiLiveKey" | "tregApiKey" | "postizApiKey" | "geminiImageApiKey",
+ name: "openaiApiKey" | "anthropicApiKey" | "openrouterApiKey" | "mistralApiKey" | "cerebrasApiKey" | "groqApiKey" | "greenferenceApiKey" | "metaApiKey" | "deepseekApiKey" | "openaiCompatApiKey" | "composioApiKey" | "xaiApiKey" | "boxToken" | "opencodeGoApiKey" | "ttsKey" | "fishAudioKey" | "geminiTtsKey" | "jevApiKey" | "openrouterDeciderKey" | "workersAiToken" | "openaiImageApiKey" | "customImageApiKey" | "openaiLiveKey" | "tregApiKey" | "postizApiKey" | "geminiImageApiKey",
value: string,
+ options?: { everyClaudeBot?: false },
): Promise<ConfigStatus>;
/** In-app auto-update (packaged app only; dormant in dev). Updates
* download by themselves. On this computer's page and the person's own