Skip to content

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

fix(images): address the review: a Custom key never leaves without its URL, a key is never a model

Fabio Nunes Cerqueira914eba5d4013
diff --git a/server/config.test.ts b/server/config.test.ts
index 34ab8226ed..9685e90695 100644
--- a/server/config.test.ts
+++ b/server/config.test.ts
@@ -190,6 +190,7 @@ describe("configuration boundaries", () => {
for (const pasted of ["sk-or-v1-0123456789abcdef0123456789abcdef", "sk-proj-abcdefghijklmnop", "xai-abcdefghijklmnopqrstuvwx", "AIzaSyA-abcdefghijklmnopqrstuvwxyz012"]) {
expect(() => parseConfigPatch({ imageGen: { primary: { provider: "openrouter", model: pasted } } })).toThrow("API key");
expect(() => parseConfigPatch({ imageGen: { fallback: { provider: "openai", model: pasted } } })).toThrow("API key");
+ expect(() => parseConfigPatch({ imageGen: { provider: "custom", customModel: pasted } })).toThrow("API key");
}
expect(parseConfigPatch({ imageGen: { primary: { provider: "openrouter", model: "openai/gpt-image-2" } } }).imageGen).toEqual({ primary: { provider: "openrouter", model: "openai/gpt-image-2" } });
expect(() => parseConfigPatch({ imageGen: { customUrl: "https://user:[email protected]/v1" } })).toThrow("customUrl");
diff --git a/server/image-generation-config.ts b/server/image-generation-config.ts
index 85827c65c7..8fe1c1a16b 100644
--- a/server/image-generation-config.ts
+++ b/server/image-generation-config.ts
@@ -1,17 +1,14 @@
import { z } from "zod";
-import { IMAGE_PROVIDERS, normalizeImageGenerationUrl, type ImageGenerationConfig } from "../shared/image-generation.ts";
+import { IMAGE_PROVIDERS, looksLikeApiKey, normalizeImageGenerationUrl, type ImageGenerationConfig } from "../shared/image-generation.ts";
-const API_KEY_SHAPE = /^(sk-|sk_|xai-|gsk_|AIza)[A-Za-z0-9_-]{12,}$/;
const imageModelIdSchema = z.string().trim().max(200).refine(
(value) => !["\r", "\n", "\0"].some((character) => value.includes(character)),
"Use a model ID without control characters",
);
const imageSlotSchema = z.object({ provider: z.enum(IMAGE_PROVIDERS), model: imageModelIdSchema.optional() }).strict();
// Stored configs keep loading; only a new save is refused, so a pasted key is never kept as a model.
-const savedImageSlotSchema = z.object({
- provider: z.enum(IMAGE_PROVIDERS),
- model: imageModelIdSchema.refine((value) => !API_KEY_SHAPE.test(value), "This looks like an API key, not a model ID: paste the key in the key field instead").optional(),
-}).strict();
+const savedModelIdSchema = imageModelIdSchema.refine((value) => !looksLikeApiKey(value), "This looks like an API key, not a model ID: paste the key in the key field instead");
+const savedImageSlotSchema = z.object({ provider: z.enum(IMAGE_PROVIDERS), model: savedModelIdSchema.optional() }).strict();
export const imageGenConfigSchema = z.object({
primary: imageSlotSchema.optional(),
fallback: imageSlotSchema.optional(),
@@ -30,7 +27,7 @@ export const imageGenConfigSchema = z.object({
customModel: imageModelIdSchema.optional(),
});
/** A patch from an older client names one `provider`; it becomes the base, so only `primary` decides it. */
-export const imageGenPatchSchema = imageGenConfigSchema.extend({ primary: savedImageSlotSchema.optional(), fallback: savedImageSlotSchema.nullable().optional() })
+export const imageGenPatchSchema = imageGenConfigSchema.extend({ primary: savedImageSlotSchema.optional(), fallback: savedImageSlotSchema.nullable().optional(), customModel: savedModelIdSchema.optional() })
.transform(({ provider, customModel, ...patch }) => {
const typed = [patch.primary, patch.fallback].find((slot) => slot?.provider === "custom" && slot.model)?.model;
const remembered = typed ?? (provider && provider !== "custom" ? undefined : customModel);
diff --git a/server/image-generation.test.ts b/server/image-generation.test.ts
index c9ab1b026d..018ab387f6 100644
--- a/server/image-generation.test.ts
+++ b/server/image-generation.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from "vitest";
-import { generateImage, imageSlots } from "./image-generation.ts";
+import { IMAGE_DEFAULT_MODELS } from "../shared/image-generation.ts";
+import { generateImage, imageGenerationReady, imageSlots } from "./image-generation.ts";
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64");
const BOTH = {
@@ -184,4 +185,13 @@ describe("what the person learns when a provider fails", () => {
expect(imageSlots({ imageGen: { customModel: "local/image", primary: { provider: "openai" }, fallback: { provider: "custom" } } }).fallback).toEqual({ provider: "custom", model: "local/image" });
expect(imageSlots({ imageGen: { customModel: "local/image", primary: { provider: "custom", model: "other/image" } } }).primary.model).toBe("other/image");
});
+
+ it("never uses an API key that was saved as a model, so it is never sent or shown as one", () => {
+ const gateway = { customUrl: "http://127.0.0.1:4000/v1", customApiKey: "my-private-gateway-key" };
+ const pasted = imageSlots({ imageGen: { ...gateway, customModel: "my-private-gateway-key", primary: { provider: "custom" } } });
+ expect(pasted.primary).toEqual({ provider: "custom", model: "" });
+ expect(imageGenerationReady({ imageGen: { ...gateway, customModel: "my-private-gateway-key", primary: { provider: "custom" } } })).toBe(false);
+ expect(imageSlots({ imageGen: { ...gateway, primary: { provider: "custom", model: "sk-proj-abcdefghijklmnop" } } }).primary.model).toBe("");
+ expect(imageSlots({ openrouter: { key: "or-key" }, imageGen: { primary: { provider: "openrouter", model: "or-key" } } }).primary.model).toBe(IMAGE_DEFAULT_MODELS.openrouter);
+ });
});
diff --git a/server/image-generation.ts b/server/image-generation.ts
index 8fdc12517a..82bdb0897e 100644
--- a/server/image-generation.ts
+++ b/server/image-generation.ts
@@ -1,7 +1,7 @@
import type { ReadableStreamReadResult } from "node:stream/web";
import { z } from "zod";
-import { IMAGE_DEFAULT_MODELS, normalizeImageGenerationUrl, type ImageGenerationConfig, type ImageProvider } from "../shared/image-generation.ts";
+import { IMAGE_DEFAULT_MODELS, IMAGE_PROVIDERS, looksLikeApiKey, normalizeImageGenerationUrl, type ImageGenerationConfig, type ImageProvider } from "../shared/image-generation.ts";
import { decodeGeneratedImage } from "./generated-image.ts";
export const IMAGE_GENERATION_TIMEOUT_MS = 120_000;
@@ -118,10 +118,16 @@ export function customImageUrl(cfg: ImageCredentials): string {
}
export function imageSlots(cfg: ImageCredentials): { primary: ImageSlot; fallback: ImageSlot | null } {
+ // A key saved as a model before saves were checked is never sent or shown: the slot acts as if no model was typed.
+ const keys = new Set(IMAGE_PROVIDERS.map((provider) => imageProviderKey(cfg, provider)).filter(Boolean));
+ const usable = (model?: string) => {
+ const id = model?.trim() ?? "";
+ return id && !keys.has(id) && !looksLikeApiKey(id) ? id : "";
+ };
// Custom has no default model, so a Custom slot saved without one uses the last model typed for Custom.
const resolveSlot = (provider: ImageProvider, model?: string): ImageSlot => ({
provider,
- model: model?.trim() || (provider === "custom" ? cfg.imageGen?.customModel?.trim() : "") || IMAGE_DEFAULT_MODELS[provider],
+ model: usable(model) || (provider === "custom" ? usable(cfg.imageGen?.customModel) : "") || IMAGE_DEFAULT_MODELS[provider],
});
const saved = cfg.imageGen?.primary;
const primary = saved ? resolveSlot(saved.provider, saved.model) : resolveSlot(cfg.imageGen?.provider ?? "openai");
diff --git a/server/key-hint.test.ts b/server/key-hint.test.ts
index b48b104d25..8abaa9928e 100644
--- a/server/key-hint.test.ts
+++ b/server/key-hint.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
-import { keyHint, keyStatus, withoutKeyHints } from "./key-hint.ts";
+import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";
describe("a saved key's hint", () => {
it("is the last four characters of a key long enough to spare them, and nothing for a short one", () => {
@@ -10,6 +10,13 @@ describe("a saved key's hint", () => {
expect(keyStatus(undefined)).toEqual({ configured: false });
});
+ it("is given for every saved picture key, Gemini included", () => {
+ const saved = nestedKeyStatus({ imageGen: { key: "openai-image-1111", customApiKey: "gateway-key-2222", geminiKey: "gemini-image-3333" } });
+ expect([saved.openaiImageApiKey, saved.customImageApiKey, saved.geminiImageApiKey]).toEqual([
+ { configured: true, last4: "1111" }, { configured: true, last4: "2222" }, { configured: true, last4: "3333" },
+ ]);
+ });
+
it("comes off everything a client session is sent, at any depth", () => {
const status = {
openai: { configured: true, last4: "a1b2" },
diff --git a/server/key-hint.ts b/server/key-hint.ts
index f94608356d..f2b5a2f470 100644
--- a/server/key-hint.ts
+++ b/server/key-hint.ts
@@ -22,6 +22,7 @@ export function nestedKeyStatus(cfg: AppConfig) {
workersAiToken: keyStatus(cfg.decider?.workersAiToken),
openaiImageApiKey: keyStatus(cfg.imageGen?.key),
customImageApiKey: keyStatus(cfg.imageGen?.customApiKey),
+ geminiImageApiKey: keyStatus(cfg.imageGen?.geminiKey),
openaiLiveKey: keyStatus(cfg.live?.key),
};
}
diff --git a/server/routes/image-settings.test.ts b/server/routes/image-settings.test.ts
index 23abef40e7..6c7fbeafaf 100644
--- a/server/routes/image-settings.test.ts
+++ b/server/routes/image-settings.test.ts
@@ -66,6 +66,18 @@ describe("the OpenRouter image model list in Settings", () => {
});
});
+describe("previewing a bot avatar from Settings", () => {
+ it("draws the avatar with the image provider and answers it as a data URL", async () => {
+ const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64");
+ const fetchImpl = vi.fn<typeof fetch>(async () => Response.json({ data: [{ b64_json: png.toString("base64") }] }));
+ const route = createImageSettingsRoutes({ config: () => ({ imageGen: { key: "openai-image-key", primary: { provider: "openai" } } }), fetch: fetchImpl });
+ const { answer } = await call(route, "/api/bot-defaults/avatar", "POST", { profile: { name: "Scout" }, prompt: "a blue owl" });
+ expect(answer).toEqual({ status: 200, body: { dataUrl: `data:image/png;base64,${png.toString("base64")}` } });
+ expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("https://api.openai.com/v1/images/generations");
+ expect(String(fetchImpl.mock.calls[0]?.[1]?.body)).toContain("a blue owl");
+ });
+});
+
describe("testing an image provider from Settings, without making an image", () => {
const openrouter = (model?: string): ImageCredentials => ({ openrouter: { key: "or-key" }, imageGen: { primary: { provider: "openrouter", ...(model ? { model } : {}) } } });
const answers = (routes: Record<string, () => Response>) => vi.fn<typeof fetch>(async (url) => {
@@ -104,6 +116,15 @@ describe("testing an image provider from Settings, without making an image", ()
expect((await test({ imageGen: { geminiKey: "AIza-key" } }, "gemini", fetchImpl)).verdict).toEqual({ ok: true, check: "models" });
});
+ it("never sends a Custom key anywhere while Custom has no usable URL", async () => {
+ const none = vi.fn<typeof fetch>();
+ for (const customUrl of [undefined, "not a url"]) {
+ const cfg: ImageCredentials = { imageGen: { customApiKey: "private-gateway-key", customUrl, primary: { provider: "custom", model: "local/image" } } };
+ expect((await test(cfg, "custom", none)).verdict).toEqual({ ok: false, reason: "no_url" });
+ }
+ expect(none).not.toHaveBeenCalled();
+ });
+
it("refuses a request that names no known provider", async () => {
const { answer } = await call(createImageSettingsRoutes({ config: () => ({}), fetch: vi.fn<typeof fetch>() }), "/api/images/test", "POST", { provider: "acme" });
expect(answer?.status).toBe(400);
diff --git a/server/routes/image-settings.ts b/server/routes/image-settings.ts
index c5dfa9eaad..d35a719b11 100644
--- a/server/routes/image-settings.ts
+++ b/server/routes/image-settings.ts
@@ -12,9 +12,13 @@ import { PASS, type RouteHandler } from "./table.ts";
const GEMINI_OPENAI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai";
const testSchema = z.object({ provider: z.enum(IMAGE_PROVIDERS) });
-function keyCheckTarget(cfg: ImageCredentials, provider: ImageProvider): { provider: ProviderKeyKind; url?: string } {
+/** Every openaiCompat target carries its own URL: without one, the key check would fall back to OpenRouter. */
+function keyCheckTarget(cfg: ImageCredentials, provider: ImageProvider): { provider: ProviderKeyKind; url?: string } | null {
if (provider === "gemini") return { provider: "openaiCompat", url: GEMINI_OPENAI_BASE };
- if (provider === "custom") return { provider: "openaiCompat", url: customImageUrl(cfg) };
+ if (provider === "custom") {
+ const url = customImageUrl(cfg);
+ return url ? { provider: "openaiCompat", url } : null;
+ }
return { provider };
}
@@ -33,9 +37,11 @@ async function openrouterHasModel(model: string, fetchImpl: typeof fetch): Promi
}
export async function testImageProvider(cfg: ImageCredentials, provider: ImageProvider, fetchImpl: typeof fetch = fetch): Promise<ImageProviderTest> {
+ const target = keyCheckTarget(cfg, provider);
+ if (!target) return { ok: false, reason: "no_url" };
const key = imageProviderKey(cfg, provider);
if (!key) return { ok: false, reason: "no_key" };
- const verdict = await checkProviderKey({ ...keyCheckTarget(cfg, provider), key }, fetchImpl);
+ const verdict = await checkProviderKey({ ...target, key }, fetchImpl);
if (!verdict.ok) return verdict;
if (provider === "openrouter") {
const { primary, fallback } = imageSlots(cfg);
@@ -58,7 +64,7 @@ export function createImageSettingsRoutes(deps: { config: () => ImageCredentials
if (!checked.success) return json(res, 400, { error: checked.error.message });
const generated = await generateAvatarImage(deps.config(), {
name: profile.patch.name ?? "", title: profile.patch.title ?? "", description: profile.patch.description ?? "",
- }, checked.data.prompt);
+ }, checked.data.prompt, deps.fetch);
return json(res, 200, { dataUrl: `data:${generated.mime};base64,${generated.bytes.toString("base64")}` });
}
if (path === "/api/images/openrouter-models" && method === "GET") {
diff --git a/server/testing/fake-image-api.ts b/server/testing/fake-image-api.ts
index 49ba99755b..e331bb9fbf 100644
--- a/server/testing/fake-image-api.ts
+++ b/server/testing/fake-image-api.ts
@@ -23,7 +23,6 @@ export async function startFakeImageApi(options: { port?: number } = {}): Promis
let parsed: Record<string, unknown> = {};
try { parsed = JSON.parse(body) as Record<string, unknown>; } catch {}
requests.push(parsed);
- process.stderr.write(`${JSON.stringify(parsed)}\n`);
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ data: [{ b64_json: PNG_1X1 }] }));
});
});
diff --git a/shared/image-generation.ts b/shared/image-generation.ts
index e9ffb8b136..bf9da56853 100644
--- a/shared/image-generation.ts
+++ b/shared/image-generation.ts
@@ -10,7 +10,7 @@ export const IMAGE_DEFAULT_MODELS: Record<ImageProvider, string> = {
/** What Settings' Test learns about a provider; no image is made. */
export type ImageProviderTest =
| { ok: true; check: "authentication" | "models"; freeTier?: boolean }
- | { ok: false; reason: "no_key" | "rejected" | "unreachable" | "unexpected"; status?: number }
+ | { ok: false; reason: "no_key" | "no_url" | "rejected" | "unreachable" | "unexpected"; status?: number }
| { ok: false; reason: "model_missing"; model: string };
export interface ImageModelChoice {
@@ -60,6 +60,13 @@ export interface ImageGenerationConfig {
/** A deliberately configured Images API endpoint, not a provider-returned URL.
* Local HTTP is useful for self-hosted routers; internet endpoints require TLS. */
+const API_KEY_SHAPE = /^(sk-|sk_|xai-|gsk_|AIza)[A-Za-z0-9_-]{12,}$/;
+
+/** A value pasted into a model field that has the shape of a provider's API key. */
+export function looksLikeApiKey(value: string): boolean {
+ return API_KEY_SHAPE.test(value.trim());
+}
+
export function normalizeImageGenerationUrl(value: string): string {
const message = "Use an HTTPS API base URL, or HTTP for a local router, without passwords, query parameters or fragments";
let url: URL;
diff --git a/src/components/ImageGenerationSettings.test.ts b/src/components/ImageGenerationSettings.test.ts
index 943fd5bdc6..01cf3ac984 100644
Binary files a/src/components/ImageGenerationSettings.test.ts and b/src/components/ImageGenerationSettings.test.ts differ
diff --git a/src/components/ImageGenerationSettings.tsx b/src/components/ImageGenerationSettings.tsx
index d0b1035c3a..abec4be0d3 100644
--- a/src/components/ImageGenerationSettings.tsx
+++ b/src/components/ImageGenerationSettings.tsx
@@ -45,6 +45,7 @@ function imageTestText(provider: ImageProvider, result: ImageProviderTest): { ok
if (result.reason === "rejected") return { ok: false, text: t("imageGen.test.rejected") };
if (result.reason === "unreachable") return { ok: false, text: t("imageGen.test.unreachable") };
if (result.reason === "no_key") return { ok: false, text: t("imageGen.key.missing") };
+ if (result.reason === "no_url") return { ok: false, text: t("imageGen.test.noUrl") };
return { ok: false, text: t("imageGen.test.unexpected") };
}
type ImageGenStatus = NonNullable<ConfigStatus["imageGen"]>;
diff --git a/src/locales/en.json b/src/locales/en.json
index e3e29ebe75..cc843d2ee4 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -7431,6 +7431,7 @@
"imageGen.test.rejected": "The provider refused this key. Check it or paste a new one.",
"imageGen.test.unreachable": "Could not reach the provider. Check the connection or the URL.",
"imageGen.test.unexpected": "The provider gave an unexpected answer.",
+ "imageGen.test.noUrl": "Add the base URL first, so the key is only sent to your endpoint.",
"imageGen.maxPerTurn.label": "Images per reply",
"imageGen.maxPerTurn.help": "The most images a bot may create in one reply.",
"imageGen.key.openai": "OpenAI API key",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 12209a2766..bbb1ef7b0a 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -6403,6 +6403,7 @@
"imageGen.test.rejected": "O provedor recusou esta chave. Confira ou cole uma nova.",
"imageGen.test.unreachable": "Não foi possível falar com o provedor. Confira a conexão ou a URL.",
"imageGen.test.unexpected": "O provedor deu uma resposta inesperada.",
+ "imageGen.test.noUrl": "Adicione a URL base primeiro, para que a chave vá só para o seu endpoint.",
"imageGen.maxPerTurn.label": "Imagens por resposta",
"imageGen.maxPerTurn.help": "O máximo de imagens que um bot pode criar numa resposta.",
"imageGen.key.openai": "Chave de API da OpenAI",