Skip to content

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

fix(openai-compat): address CodeRabbit review findings

jonathanwxh-cell3192c1128cfe
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index a228c2d809..ad5fbfff63 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -2,7 +2,7 @@ import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts"
import { createHash } from "node:crypto";
import type { DriverCreateInput, ModelCatalog, ProviderInstance, ProviderSnapshot, RuntimeEvent, RuntimeEventListener, SendTurnInput, TextGenerationOptions } from "../contracts.ts";
import { newEventId, newId } from "../contracts.ts";
-import { CustomHeaderError, customHeaderSecrets, resolveCustomHeaders, type OpenAICompatCustomHeadersConfig, type RuntimeHeaderContext } from "./openai-compat-headers.ts";
+import { CustomHeaderError, customHeaderSecrets, maskCustomSecrets, resolveCustomHeaders, scrubErrorSecrets, type OpenAICompatCustomHeadersConfig, type RuntimeHeaderContext } from "./openai-compat-headers.ts";
import { ASK_USER_TOOL, ASK_USER_TOOL_DEFINITION, askQuestionSummary, parseAskQuestions, questionChoices } from "../../shared/ask-question.ts";
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { redactSecretsInText } from "../redact.ts";
@@ -284,7 +284,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const customHeaders = options.customHeaders ? resolveCustomHeaders(options.customHeaders, headerContext ?? { threadId, providerInstanceId: input.instanceId }) : undefined;
const response = await send(`${options.apiUrl}/${route === "responses" ? "responses" : "chat/completions"}`, {
method: "POST",
- ...(messages.some(message => Array.isArray(message.content) && message.content.some(part => part.type === "image_url")) ? { redirect: "error" as const } : {}),
+ ...((Object.keys(customHeaders ?? {}).length || messages.some(message => Array.isArray(message.content) && message.content.some(part => part.type === "image_url"))) ? { redirect: "error" as const } : {}),
headers: { ...customHeaders, authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },
body: payload,
signal: activeSignal,
@@ -530,11 +530,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
}
}
- const safeText = (text: string) => {
- let safe = text;
- for (const secret of secrets) if (secret) safe = safe.split(secret).join("[redacted]");
- return redactSecretsInText(safe);
- };
+ const safeText = (text: string) => redactSecretsInText(maskCustomSecrets(text, secrets));
const preview = (value: unknown) => toolDetailPreview(JSON.parse(JSON.stringify(value, (_key, part) =>
typeof part === "string" ? safeText(part) : part)));
const native = (dir: "out" | "in", msg: unknown) => appendNative(turn.threadId, {
@@ -982,9 +978,14 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const model = named ?? options.generateModel?.() ?? options.models().default;
signal?.throwIfAborted();
checkModel?.(model);
- const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage, undefined, undefined, { providerInstanceId: input.instanceId });
- if (toolCalls.length) throw new ChatProtocolError("provider returned tool calls to a text-only helper");
- return text.trim() ? text : reasoning;
+ const headerSecrets = customHeaderSecrets(options.customHeaders, { providerInstanceId: input.instanceId });
+ try {
+ const { text, reasoning, toolCalls } = await complete([{ role: "user", content: prompt }], model, false, signal, undefined, [], onUsage, undefined, undefined, { providerInstanceId: input.instanceId });
+ if (toolCalls.length) throw new ChatProtocolError("provider returned tool calls to a text-only helper");
+ return maskCustomSecrets(text.trim() ? text : reasoning, headerSecrets);
+ } catch (error) {
+ throw scrubErrorSecrets(error, headerSecrets);
+ }
},
dispose: async () => {
const turns = [...active.values()];
diff --git a/server/drivers/openai-compat-headers.test.ts b/server/drivers/openai-compat-headers.test.ts
index 067c27fd7c..4f3b7bc903 100644
--- a/server/drivers/openai-compat-headers.test.ts
+++ b/server/drivers/openai-compat-headers.test.ts
@@ -5,8 +5,11 @@ import {
CustomHeaderValidationError,
customHeaderSecrets,
decodeCustomHeaders,
+ maskCustomSecrets,
mergeCustomHeadersPatch,
resolveCustomHeaders,
+ scrubErrorSecrets,
+ stripSensitiveCustomHeaders,
summarizeCustomHeaders,
} from "./openai-compat-headers.ts";
@@ -142,5 +145,24 @@ describe("OpenAI-compatible custom headers config & resolution", () => {
});
expect(customHeaderSecrets(dynamicSecrets, { threadId: "thread-99" })).toEqual(["tok-thread-99"]);
expect(customHeaderSecrets(dynamicSecrets, { threadId: "1" })).toEqual([]);
+
+ expect(mergeCustomHeadersPatch(
+ { enabled: true, headers: [{ name: "X-Gateway-Token", keepExisting: true, secret: true }] },
+ { enabled: true, headers: { "X-Gateway-Token": "gw-tok-map-123456" } },
+ )).toEqual({
+ enabled: true,
+ headers: [{ name: "X-Gateway-Token", value: "gw-tok-map-123456", required: true, secret: true }],
+ });
+ expect(() => mergeCustomHeadersPatch({ enabled: true, headers: [] }, { enabled: "bad", headers: 123 })).toThrow(CustomHeaderValidationError);
+
+ expect(stripSensitiveCustomHeaders(config)).toEqual({
+ enabled: true,
+ headers: [{ name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false }],
+ });
+ expect(stripSensitiveCustomHeaders(dynamicSecrets)).toBeUndefined();
+ expect(maskCustomSecrets("err tok-thread-99", ["tok-thread-99"])).toBe("err [redacted]");
+ const err = new Error("http 500: tok-thread-99");
+ expect(scrubErrorSecrets(err, ["tok-thread-99"])).toBe(err);
+ expect(err.message).toBe("http 500: [redacted]");
});
});
diff --git a/server/drivers/openai-compat-headers.ts b/server/drivers/openai-compat-headers.ts
index 5e1c2726b4..0c317d8a48 100644
--- a/server/drivers/openai-compat-headers.ts
+++ b/server/drivers/openai-compat-headers.ts
@@ -171,11 +171,12 @@ export function decodeCustomHeaders(raw: unknown): OpenAICompatCustomHeadersConf
export function mergeCustomHeadersPatch(
patch: unknown,
- previous?: OpenAICompatCustomHeadersConfig,
+ previous?: unknown,
): OpenAICompatCustomHeadersConfig {
if (!isPlainRecord(patch)) throw new CustomHeaderValidationError("customHeaders must be an object.");
if (typeof patch.enabled !== "boolean") throw new CustomHeaderValidationError("customHeaders.enabled must be a boolean.");
- const prevByName = new Map((previous?.headers ?? []).map((entry) => [entry.name.toLowerCase(), entry]));
+ const priorHeaders = previous === undefined ? [] : decodeCustomHeaders(previous).headers;
+ const prevByName = new Map(priorHeaders.map((entry) => [entry.name.toLowerCase(), entry]));
const rawEntries = normalizeEntries(patch.headers);
const resolved = rawEntries.map((entry) => {
const name = validateHeaderName(entry.name);
@@ -283,6 +284,37 @@ export function customHeaderSecrets(
return [...out];
}
+export function maskCustomSecrets(text: string, secrets: readonly string[]): string {
+ let masked = text;
+ for (const secret of secrets) if (secret) masked = masked.split(secret).join("[redacted]");
+ return masked;
+}
+
+export function scrubErrorSecrets(error: unknown, secrets: readonly string[]): unknown {
+ if (secrets.length === 0) return error;
+ if (typeof error === "string") return maskCustomSecrets(error, secrets);
+ if (!(error instanceof Error)) return error;
+ const masked = maskCustomSecrets(error.message, secrets);
+ if (masked === error.message) return error;
+ try {
+ error.message = masked;
+ return error;
+ } catch {
+ return new Error(masked, { cause: error });
+ }
+}
+
+export function stripSensitiveCustomHeaders(raw: unknown): OpenAICompatCustomHeadersConfig | undefined {
+ let decoded: OpenAICompatCustomHeadersConfig;
+ try {
+ decoded = decodeCustomHeaders(raw);
+ } catch {
+ return undefined;
+ }
+ const kept = decoded.headers.filter((rule) => !isSensitiveHeader(rule));
+ return kept.length ? { enabled: decoded.enabled, headers: kept } : undefined;
+}
+
export function applyOpenAiCompatHeaderDefaults(
merged: Record<string, unknown>,
defaults: OpenAICompatCustomHeadersConfig | undefined,
diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.ts
index 27533517eb..658db17982 100644
--- a/server/drivers/openai-compat.test.ts
+++ b/server/drivers/openai-compat.test.ts
@@ -1336,13 +1336,13 @@ describe("how long a turn waits for a reply", () => {
describe("opt-in custom OpenAI-compatible request headers", () => {
it("preserves standard headers when disabled and injects per-thread/bot/turn/provider headers consistently across threads, compaction, retries, non-streaming, and secret scrubbing", async () => {
- const seenRequests: Array<{ url: string; headers: Record<string, string>; body: Record<string, unknown> }> = [];
+ const seenRequests: Array<{ url: string; redirect?: RequestInit["redirect"]; headers: Record<string, string>; body: Record<string, unknown> }> = [];
let chatAttempt = 0;
vi.stubGlobal("fetch", vi.fn(async (url: string | URL, init?: RequestInit) => {
const target = String(url);
if (target.endsWith("/models")) return Response.json({ data: [] });
const rawHeaders = Object.fromEntries(new Headers(init?.headers).entries());
- seenRequests.push({ url: target, headers: rawHeaders, body: JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown> });
+ seenRequests.push({ url: target, redirect: init?.redirect, headers: rawHeaders, body: JSON.parse(String(init?.body ?? "{}")) as Record<string, unknown> });
chatAttempt++;
if (chatAttempt === 4) {
return new Response("", { status: 200, headers: { "content-type": "text/event-stream" } });
@@ -1370,6 +1370,7 @@ describe("opt-in custom OpenAI-compatible request headers", () => {
await offInst.adapter.sendTurn({ threadId: "t-off", botId: "b1", text: "hi" });
await recOff.until((e) => e.type === "turn.completed");
expect(seenRequests[0]!.headers["x-maus-thread-id"]).toBeUndefined();
+ expect(seenRequests[0]!.redirect).toBeUndefined();
recOff.stop();
await offInst.dispose();
@@ -1405,6 +1406,7 @@ describe("opt-in custom OpenAI-compatible request headers", () => {
expect(chatReqs[0]!.headers["x-maus-bot-id"]).toBe("bot-one");
expect(chatReqs[0]!.headers["x-provider-id"]).toBe("gw-on");
expect(chatReqs[0]!.headers["x-gateway-token"]).toBe("gw-secret-token-xyz");
+ expect(chatReqs[0]!.redirect).toBe("error");
expect(chatReqs[1]!.headers["x-maus-thread-id"]).toBe("thread-beta");
// chatAttempt === 4 was truncated, so retried once on attempt 5 for thread-alpha: same turnId!
expect(chatReqs[2]!.headers["x-maus-thread-id"]).toBe("thread-alpha");
@@ -1439,9 +1441,41 @@ describe("opt-in custom OpenAI-compatible request headers", () => {
const nonStreamReq = seenRequests.at(-1)!;
expect(nonStreamReq.headers["x-gateway-client"]).toBe("maus");
expect(nonStreamReq.headers["x-maus-thread-id"]).toBeUndefined();
+ expect(nonStreamReq.redirect).toBe("error");
await optInst.dispose();
recOn.stop();
await onInst.dispose();
});
+
+ it("masks secret custom header values in generateText replies, reasoning, and propagated errors", async () => {
+ let mode: "text" | "reasoning" | "error" | "clean" = "text";
+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL) => {
+ if (String(url).endsWith("/models")) return Response.json({ data: [] });
+ if (mode === "error") return new Response(JSON.stringify({ error: { message: "bad token gw-secret-helper-999" } }), { status: 500, headers: { "content-type": "application/json" } });
+ if (mode === "reasoning") return Response.json({ choices: [{ message: { content: null, reasoning_content: "think gw-secret-helper-999 done" }, finish_reason: "stop" }] });
+ if (mode === "clean") return Response.json({ choices: [{ message: { content: "plain clean output" }, finish_reason: "stop" }] });
+ return Response.json({ choices: [{ message: { content: "echo gw-secret-helper-999 ok" }, finish_reason: "stop" }] });
+ }));
+ const inst = await OpenAICompatDriver.create({
+ instanceId: "gw-helper", displayName: "Helper", enabled: true,
+ config: OpenAICompatDriver.decodeConfig({
+ url: "https://gw.example/v1", model: "m1",
+ customHeaders: {
+ enabled: true,
+ headers: [{ name: "X-Gateway-Token", value: "gw-secret-helper-999", secret: true }],
+ },
+ }),
+ environment: { OPENAI_COMPAT_API_KEY: "test-api-key-123456" },
+ });
+ mode = "text";
+ await expect(inst.generateText!("say hi")).resolves.toBe("echo [redacted] ok");
+ mode = "reasoning";
+ await expect(inst.generateText!("say hi")).resolves.toBe("think [redacted] done");
+ mode = "clean";
+ await expect(inst.generateText!("say hi")).resolves.toBe("plain clean output");
+ mode = "error";
+ await expect(inst.generateText!("say hi")).rejects.toThrow(/bad token \[redacted\]/);
+ await inst.dispose();
+ });
});
diff --git a/server/index.ts b/server/index.ts
index be83361f91..250651449e 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -11655,7 +11655,7 @@ function configForAccess(status: ReturnType<typeof configStatus>, admin: boolean
edition: { edition: status.edition.edition, features: status.edition.features },
signIn: { admins: [], members: [] }, live: liveSettingsForClient(status.live), everyBotRules: undefined,
vps: { configured: status.vps.configured, sshAlias: "", servers: [], memoryGb: status.vps.memoryGb, cpus: status.vps.cpus },
- opencodeGo: { configured: status.opencodeGo.configured, providerKeys: [] },
+ opencodeGo: { configured: status.opencodeGo.configured, providerKeys: [] }, openaiCompat: { configured: status.openaiCompat.configured, url: status.openaiCompat.url, ...(status.openaiCompat.customHeaders ? { customHeaders: { configured: status.openaiCompat.customHeaders.enabled && status.openaiCompat.customHeaders.headers.length > 0 } } : {}) },
...(CLOUD_TEAM ? { onboarding } : {}), profile: CLOUD_TEAM ? profile : { name: profile.name, email: "", ...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}) },
browserProfiles: status.browserProfiles.map((profile) => Object.fromEntries(Object.entries(profile).filter(([key]) => key !== "partitionId"))),
};
diff --git a/server/openai-compat-endpoints.ts b/server/openai-compat-endpoints.ts
index 7ba504b443..c7517949a8 100644
--- a/server/openai-compat-endpoints.ts
+++ b/server/openai-compat-endpoints.ts
@@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import type { InstanceConfig, InstanceConfigMap } from "./contracts.ts";
-import { customHeadersPatchSchema, decodeCustomHeaders, summarizeCustomHeaders } from "./drivers/openai-compat-headers.ts";
+import { customHeadersPatchSchema, decodeCustomHeaders, stripSensitiveCustomHeaders, summarizeCustomHeaders } from "./drivers/openai-compat-headers.ts";
import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, probeOllama } from "./drivers/ollama.ts";
export { summarizeCustomHeaders };
@@ -79,7 +79,8 @@ export function changeEndpointAddress(
if (change.apiKey !== undefined && /^https?:\/\//i.test(change.apiKey)) {
return { status: 400, error: "That API key looks like a URL. Paste the secret key itself, not a web address." };
}
- if (change.apiKey === undefined && config.key !== OLLAMA_PLACEHOLDER_KEY && (!saved || new URL(url).origin !== new URL(saved).origin)) {
+ const originChanged = !saved || new URL(url).origin !== new URL(saved).origin;
+ if (change.apiKey === undefined && config.key !== OLLAMA_PLACEHOLDER_KEY && originChanged) {
return { status: 400, error: "Enter the API key again: a saved key is only sent to the server it was entered for." };
}
if (config.catalog && url !== saved) {
@@ -87,7 +88,9 @@ export function changeEndpointAddress(
const duplicate = localServerAlreadyAdded(others, url);
if (duplicate) return { status: 409, error: duplicate };
}
- entry.config = { ...config, url, ...(change.apiKey !== undefined ? { key: change.apiKey } : {}) };
+ const { customHeaders: priorHeaders, ...restConfig } = config;
+ const nextHeaders = originChanged && priorHeaders !== undefined ? stripSensitiveCustomHeaders(priorHeaders) : priorHeaders;
+ entry.config = { ...restConfig, url, ...(change.apiKey !== undefined ? { key: change.apiKey } : {}), ...(nextHeaders !== undefined ? { customHeaders: nextHeaders } : {}) };
return { addressChanged: url !== saved };
}
diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.ts
index ceb4b1fc33..6ef0e5cec4 100644
--- a/server/routes/instances.test.ts
+++ b/server/routes/instances.test.ts
@@ -432,6 +432,22 @@ describe("a server's reply wait", () => {
await call("PATCH", "/api/instances/openai-compat-1", { customHeaders: null });
expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "https://gw.example/v1", key: "k" });
+ (cfg.instances["openai-compat-1"] as { config: Record<string, unknown> }).config = {
+ url: "https://gw.example/v1", key: "k",
+ customHeaders: { enabled: true, headers: { "X-Gateway-Token": "gw-map-secret-999" } },
+ };
+ await call("PATCH", "/api/instances/openai-compat-1", {
+ customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", keepExisting: true, secret: true }] },
+ });
+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toMatchObject({
+ customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", value: "gw-map-secret-999", required: true, secret: true }] },
+ });
+ (cfg.instances["openai-compat-1"] as { config: Record<string, unknown> }).config = {
+ url: "https://gw.example/v1", key: "k", customHeaders: { enabled: "bad", headers: 42 },
+ };
+ expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [] } })).toBe(400);
+ await call("PATCH", "/api/instances/openai-compat-1", { customHeaders: null });
+
const nonOwner = await serve(
{ cfg: cfg as unknown as AppConfig, persistProviderInstance: async () => {} },
{ kind: "loopback", scopes: ["admin"], trust: "service" },
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index f616ea9496..2d084ce421 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -29,7 +29,7 @@ import {
import { updateClaudeCli } from "../claude-update.ts";
import { persistableInstanceConfigs, saveConfig, withInstanceCli, type AppConfig } from "../config.ts";
import { addEndpoint, addEndpointSchema, changeEndpointAddress, endpointBaseUrl, endpointModelsReadable, isAddedEndpoint, localServerAlreadyAdded, withEndpointUrls } from "../openai-compat-endpoints.ts";
-import { CustomHeaderValidationError, mergeCustomHeadersPatch, type OpenAICompatCustomHeadersConfig } from "../drivers/openai-compat-headers.ts";
+import { CustomHeaderValidationError, mergeCustomHeadersPatch } from "../drivers/openai-compat-headers.ts";
import { findOllama, probeOllama } from "../drivers/ollama.ts";
import type { InstanceConfigMap, ModelSelection, ProviderInstance } from "../contracts.ts";
import { removeAntigravityProfile } from "../drivers/antigravity-acp.ts";
@@ -523,6 +523,15 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
const { replyWaitMinutes: _previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;
entry.config = body.replyWaitMinutes === null ? rest : { ...rest, replyWaitMinutes: body.replyWaitMinutes };
}
+ if (body.url !== undefined || body.apiKey !== undefined) {
+ if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin can change a server's address or key." });
+ if (!isAddedEndpoint(instanceId, entry)) return json(res, 400, { error: "The base URL and key can be changed here for added OpenAI-compatible servers only." });
+ const changed = changeEndpointAddress(instances, instanceId, { url: body.url, apiKey: body.apiKey });
+ if ("error" in changed) return json(res, changed.status, { error: changed.error });
+ // A model list read from the server's /models is read again from the new address or with the new key.
+ const config = entry.config as { url: string; key: string; catalog?: unknown; managedModels?: unknown };
+ if ((changed.addressChanged || body.apiKey !== undefined) && !Array.isArray(config.managedModels)) detect = { url: config.url, key: config.key, catalog: config.catalog };
+ }
if (body.customHeaders !== undefined) {
if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin can configure custom headers." });
if (entry.driver !== "openai-compat") return json(res, 400, { error: "Custom request headers are available for OpenAI-compatible instances only." });
@@ -530,7 +539,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
try {
entry.config = body.customHeaders === null
? rest
- : { ...rest, customHeaders: mergeCustomHeadersPatch(body.customHeaders, previous as OpenAICompatCustomHeadersConfig | undefined) };
+ : { ...rest, customHeaders: mergeCustomHeadersPatch(body.customHeaders, previous) };
} catch (error) {
if (error instanceof CustomHeaderValidationError) return json(res, 400, { error: error.message });
throw error;
@@ -546,15 +555,6 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
}
entry.config = models.length ? { ...rest, managedModels: models } : rest;
}
- if (body.url !== undefined || body.apiKey !== undefined) {
- if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the owner or an admin can change a server's address or key." });
- if (!isAddedEndpoint(instanceId, entry)) return json(res, 400, { error: "The base URL and key can be changed here for added OpenAI-compatible servers only." });
- const changed = changeEndpointAddress(instances, instanceId, { url: body.url, apiKey: body.apiKey });
- if ("error" in changed) return json(res, changed.status, { error: changed.error });
- // A model list read from the server's /models is read again from the new address or with the new key.
- const config = entry.config as { url: string; key: string; catalog?: unknown; managedModels?: unknown };
- if ((changed.addressChanged || body.apiKey !== undefined) && !Array.isArray(config.managedModels)) detect = { url: config.url, key: config.key, catalog: config.catalog };
- }
if (body.displayName !== undefined) entry.displayName = body.displayName;
if (body.configDir !== undefined) {
let previousDir: string | undefined;
diff --git a/server/routes/openai-compat-endpoints.test.ts b/server/routes/openai-compat-endpoints.test.ts
index 9f0ab631e0..dd8c1e4d24 100644
--- a/server/routes/openai-compat-endpoints.test.ts
+++ b/server/routes/openai-compat-endpoints.test.ts
@@ -218,6 +218,58 @@ describe("changing an added server's base URL", () => {
expect(cfg.instances?.[ID]?.config).toEqual({ key: "ollama", url: "http://192.168.1.20:11434", catalog: "ollama" });
});
+ it("drops saved secret custom headers on cross-origin edits while preserving same-origin and freshly entered headers", async () => {
+ const seededHeaders = {
+ enabled: true,
+ headers: [
+ { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
+ { name: "X-Gateway-Token", value: "gw-secret-origin-123", required: true, secret: true },
+ ],
+ };
+ const same = await serve();
+ seed(same.cfg, { key: SECRET, url: "https://old.example.com/v1", customHeaders: seededHeaders });
+ expect((await same.call("PATCH", `/api/instances/${ID}`, { url: "https://old.example.com/v2" })).status).toBe(200);
+ expect(same.cfg.instances?.[ID]?.config).toMatchObject({ customHeaders: seededHeaders });
+
+ const cross = await serve();
+ seed(cross.cfg, { key: SECRET, url: "https://old.example.com/v1", customHeaders: seededHeaders });
+ expect((await cross.call("PATCH", `/api/instances/${ID}`, { url: "https://new.example.com/v1", apiKey: "sk-new" })).status).toBe(200);
+ expect(cross.cfg.instances?.[ID]?.config).toMatchObject({
+ url: "https://new.example.com/v1",
+ key: "sk-new",
+ customHeaders: {
+ enabled: true,
+ headers: [{ name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false }],
+ },
+ });
+
+ const ollama = await serve();
+ seed(ollama.cfg, {
+ key: "ollama", url: "http://127.0.0.1:11434", catalog: "ollama",
+ customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", value: "gw-secret-origin-123", required: true, secret: true }] },
+ });
+ expect((await ollama.call("PATCH", `/api/instances/${ID}`, { url: "http://192.168.1.20:11434" })).status).toBe(200);
+ expect(ollama.cfg.instances?.[ID]?.config).not.toHaveProperty("customHeaders");
+
+ const keepCross = await serve();
+ seed(keepCross.cfg, { key: SECRET, url: "https://old.example.com/v1", customHeaders: seededHeaders });
+ expect((await keepCross.call("PATCH", `/api/instances/${ID}`, {
+ url: "https://new.example.com/v1",
+ apiKey: "sk-new",
+ customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", keepExisting: true, secret: true }] },
+ })).status).toBe(400);
+ expect((await keepCross.call("PATCH", `/api/instances/${ID}`, {
+ url: "https://new.example.com/v1",
+ apiKey: "sk-new",
+ customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", value: "gw-new-origin-456", secret: true }] },
+ })).status).toBe(200);
+ expect(keepCross.cfg.instances?.[ID]?.config).toMatchObject({
+ url: "https://new.example.com/v1",
+ key: "sk-new",
+ customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", value: "gw-new-origin-456", required: true, secret: true }] },
+ });
+ });
+
it("saves an address whose model list can't be read, says so, and reads it after the busy guard", async () => {
let busyWhileReading: boolean | undefined;
const asked: Array<{ url: string; key: string }> = [];
diff --git a/src/state/config-status.ts b/src/state/config-status.ts
index c6f3b5ac98..2987953460 100644
--- a/src/state/config-status.ts
+++ b/src/state/config-status.ts
@@ -12,6 +12,11 @@ export type NestedKeyName = "ttsKey" | "fishAudioKey" | "geminiTtsKey" | "jevApi
export interface ImageSlotStatus { provider: ImageProvider; model: string; configured: boolean }
+export interface OpenAiCompatCustomHeadersSummary {
+ enabled: boolean;
+ headers: Array<{ name: string; value?: string; configured: boolean; required: boolean; secret: boolean }>;
+}
+
/** GET /api/config — configured flags only; secrets are never echoed. */
export interface ConfigStatus {
/** The workspace's banner picture (GET /api/workspace/banner), by a version that changes with it; null without one. */
@@ -39,10 +44,7 @@ export interface ConfigStatus {
openrouter?: SavedKey;
openaiCompat?: SavedKey & {
url?: string;
- customHeaders?: {
- enabled: boolean;
- headers: Array<{ name: string; value?: string; configured: boolean; required: boolean; secret: boolean }>;
- };
+ customHeaders?: OpenAiCompatCustomHeadersSummary | { configured: boolean };
};
/** what this server is entitled to; Settings shows only what works here.
* `license` reaches admins only, and only while the key is inside its
diff --git a/src/state/store.tsx b/src/state/store.tsx
index d11af2fc0a..cc04b06319 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -404,8 +404,8 @@ function openedUnreadDivider(state: AppState, threadId: string, unread: boolean,
return unread ? unreadDividerFor(threadId, messages, lastReadMessageId, hasMore) : placeUnreadDivider(state.unreadDivider?.threadId === threadId ? state.unreadDivider : null, threadId, messages, Boolean(hasMore));
}
-import type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicySummary } from "./config-status";
-export type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicySummary };
+import type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicySummary, OpenAiCompatCustomHeadersSummary } from "./config-status";
+export type { BrowserEngineSummary, BrowserProfile, ConfigStatus, ManagedPolicySummary, OpenAiCompatCustomHeadersSummary };
import { configStatusFromFrame, type ConfigStatusFrame } from "@/lib/config-status-frame";
export { configStatusFromFrame, type ConfigStatusFrame };
@@ -462,7 +462,7 @@ export interface InstanceInfo extends InstanceEndpointInfo {
cliDefault?: string;
cliCandidates?: string[];
claudeAccount?: { configDir: string; signInCommand: string; signInShell: "powershell" | "sh"; isDefault: boolean };
- freeUpSpace?: boolean; replyWaitMinutes?: number; customHeaders?: NonNullable<ConfigStatus["openaiCompat"]>["customHeaders"]; modelsUnconfirmed?: true; /** Why the engine's last read of its list failed. */ modelsUnreadable?: "signedOut" | "timedOut" | "failed"; /** The app updated its own copy of this engine to this version lately. */ autoUpdated?: { version: string; at: number };
+ freeUpSpace?: boolean; replyWaitMinutes?: number; customHeaders?: OpenAiCompatCustomHeadersSummary; modelsUnconfirmed?: true; /** Why the engine's last read of its list failed. */ modelsUnreadable?: "signedOut" | "timedOut" | "failed"; /** The app updated its own copy of this engine to this version lately. */ autoUpdated?: { version: string; at: number };
}
/** A Settings page (`SettingsPageId`) or an older page name that `settings-index.ts` sends to its new page and section. */