Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(tts): verify Gemini API key on configuration save
agentboiledoceanc9720f10cd41
diff --git a/scripts/testing/key-readback.e2e.test.ts b/scripts/testing/key-readback.e2e.test.tsindex 1dbe578222..4e40b95a77 100644--- a/scripts/testing/key-readback.e2e.test.ts+++ b/scripts/testing/key-readback.e2e.test.ts@@ -74,6 +74,7 @@ beforeAll(async () => {wav.writeUInt16LE(16, 34); wav.write("data", 36); wav.writeUInt32LE(2, 40);return reply(200, { steps: [{ type: "model_output", content: [{ type: "audio", mime_type: "audio/wav", data: wav.toString("base64") }] }] });}+ if (url.startsWith("/gemini/models")) return reply(200, { models: [] });if (url.startsWith("/eleven/voices")) return reply(200, { voices: [] });if (url.startsWith("/fish/model")) return reply(200, { items: [], total: 0 });return reply(404, { error: "not in the stand-in" });diff --git a/server/routes/config.ts b/server/routes/config.tsindex 53f8a6a758..05f47eeea1 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -103,6 +103,11 @@ export interface ConfigRouteDeps {postiz?: Pick<Postiz, "configCheck" | "configSaved">;}+/**+ * Creates configuration and key management HTTP routes.+ * @param deps Injected dependencies for configuration management.+ * @returns Configured route handler function.+ */export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {const {store, cfg, registry, sessions, browserCleanup, browserLive, browserRuntime, usedBrowserSessions, decider,@@ -450,6 +455,10 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {const check = await tts.verifyKey("fish", newTts.fishKey.trim());if (!check.ok) return json(res, 400, { error: check.message });}+ if (newTts?.geminiKey?.trim()) {+ const check = await tts.verifyKey("gemini", newTts.geminiKey.trim());+ if (!check.ok) return json(res, 400, { error: check.message });+ }const deciderKey = patch.decider ? deciderPatchKey(patch.decider, cfg.decider) : null;if (deciderKey) {const check = await decider.testKey(deciderKey.check);diff --git a/server/tts/gemini.test.ts b/server/tts/gemini.test.tsindex 07b8340202..5a93d28a70 100644--- a/server/tts/gemini.test.ts+++ b/server/tts/gemini.test.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from "vitest";-import { describeVoice, listVoices, providerConfigured, speak, voiceConfigured, voiceReady } from "./index.ts";+import { describeVoice, listVoices, providerConfigured, speak, verifyKey, voiceConfigured, voiceReady } from "./index.ts";import type { AppConfig } from "../config.ts";const cfg: AppConfig = { tts: { provider: "gemini", geminiKey: "private-gemini-key", voice: "Kore" } };@@ -69,4 +69,37 @@ describe("Gemini speech", () => {vi.stubGlobal("fetch", vi.fn().mockImplementation(async () => Response.json(body)));await expect(speak(cfg, "hello")).rejects.toThrow(/Gemini/);});++ it("verifies a valid Gemini API key using the models endpoint", async () => {+ const request = vi.fn().mockResolvedValue(new Response(JSON.stringify({ models: [] })));+ vi.stubGlobal("fetch", request);+ const result = await verifyKey("gemini", "valid-gemini-key");+ expect(result).toEqual({ ok: true });+ const [url, init] = request.mock.calls[0];+ expect(url).toBe("https://generativelanguage.googleapis.com/v1beta/models?pageSize=1");+ expect(init.method).toBe("GET");+ expect(init.headers).toEqual({ "x-goog-api-key": "valid-gemini-key" });+ expect(init.redirect).toBe("error");+ });++ it.each([400, 401, 403])("returns refusal message when key is rejected (HTTP %i)", async (status) => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("error", { status })));+ const result = await verifyKey("gemini", "bad-key");+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.message).toMatch(/rejected the API key/i);+ });++ it("handles quota exceeded during key verification", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("quota", { status: 429 })));+ const result = await verifyKey("gemini", "rate-limited-key");+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.message).toMatch(/quota exceeded/i);+ });++ it("handles network failure during key verification", async () => {+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("Network offline")));+ const result = await verifyKey("gemini", "some-key");+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.message).toMatch(/Couldn't reach Gemini/i);+ });});diff --git a/server/tts/gemini.ts b/server/tts/gemini.tsindex 3bdee24283..9e79178e93 100644--- a/server/tts/gemini.ts+++ b/server/tts/gemini.ts@@ -1,5 +1,5 @@import { z } from "zod";-import type { Audio, Voice } from "./elevenlabs.ts";+import type { Audio, Voice, VerifyResult } from "./elevenlabs.ts";export const DEFAULT_GEMINI_MODEL = "gemini-3.8-flash-lite-tts";const API = (process.env.OMB_GEMINI_TTS_API || "https://generativelanguage.googleapis.com/v1beta").replace(/\/+$/, "");@@ -9,14 +9,58 @@ const outputSchema = z.object({ steps: z.array(z.object({content: z.array(z.object({ type: z.string(), data: z.string().optional(), mime_type: z.string().optional() })).optional(),})) });+/**+ * Lists available Gemini voices, returning the catalog of 30 prebuilt voices.+ * @returns Array of available Voice descriptors.+ */export function listVoices(): Voice[] {return VOICES.map((id) => ({ id, label: id }));}+/**+ * Checks whether a voice ID is in the supported Gemini prebuilt voice catalog.+ * @param voiceId Voice identifier to check.+ * @returns True if voice is supported, false otherwise.+ */export function isSupportedVoice(voiceId: string | undefined): boolean {return voiceId !== undefined && VOICES.includes(voiceId);}+/**+ * Verifies that the provided Gemini API key is valid by querying the models endpoint.+ * @param key The Gemini API key to verify.+ * @returns An object indicating whether the key is valid, with an error message if invalid.+ */+export async function verifyKey(key: string): Promise<VerifyResult> {+ try {+ const res = await fetch(`${API}/models?pageSize=1`, {+ method: "GET",+ redirect: "error",+ headers: { "x-goog-api-key": key },+ signal: AbortSignal.timeout(20_000),+ });+ await res.body?.cancel();+ if (res.ok) return { ok: true };+ if (res.status === 400 || res.status === 401 || res.status === 403) {+ return { ok: false, message: "Gemini rejected the API key or its speech permissions. Check the key in Settings." };+ }+ if (res.status === 429) {+ return { ok: false, message: "Gemini quota exceeded. Try again later." };+ }+ return { ok: false, message: `Couldn't verify Gemini API key (HTTP ${res.status}).` };+ } catch {+ return { ok: false, message: "Couldn't reach Gemini to check that key — check your connection." };+ }+}++/**+ * Synthesizes text to speech using the Gemini speech interactions API.+ * @param text The plain text to read aloud.+ * @param voiceId Prebuilt Gemini voice ID.+ * @param key The Gemini API key.+ * @param model Gemini model identifier.+ * @returns Synthesized Audio object containing bytes and MIME type.+ */export async function synthesize(text: string, voiceId: string, key: string, model = DEFAULT_GEMINI_MODEL): Promise<Audio> {if (!isSupportedVoice(voiceId)) throw new Error("Pick a Gemini voice from the voice list.");let response: Response;diff --git a/server/tts/index.ts b/server/tts/index.tsindex 4c427e77c7..4e301dc3bc 100644--- a/server/tts/index.ts+++ b/server/tts/index.ts@@ -26,11 +26,21 @@ export class NoVoiceConfigured extends Error {const elevenLabs = (cfg: AppConfig) => voiceCredential(cfg.tts?.key);+/**+ * Resolves the active voice synthesis provider from configuration.+ * @param cfg The application configuration.+ * @returns The resolved VoiceProvider name.+ */export function voiceProvider(cfg: AppConfig): VoiceProvider {const provider = cfg.tts?.provider;return provider === "gemini" || provider === "xai" || provider === "fish" || provider === "system" || provider === "chatterbox" ? provider : "elevenlabs";}+/**+ * Determines whether the credentials or requirements for the active voice provider are met.+ * @param cfg The application configuration.+ * @returns True if provider requirements are configured.+ */export function providerConfigured(cfg: AppConfig): boolean {const provider = voiceProvider(cfg);if (provider === "gemini") return Boolean(cfg.tts?.geminiKey);@@ -41,6 +51,11 @@ export function providerConfigured(cfg: AppConfig): boolean {return Boolean(elevenLabs(cfg));}+/**+ * Determines whether the active voice provider is fully configured with a valid voice selection.+ * @param cfg The application configuration.+ * @returns True if provider has both key and configured voice.+ */export function voiceConfigured(cfg: AppConfig): boolean {const provider = voiceProvider(cfg);if (provider === "gemini") return Boolean(cfg.tts?.geminiKey && gemini.isSupportedVoice(cfg.tts?.voice));@@ -53,6 +68,12 @@ export function voiceConfigured(cfg: AppConfig): boolean {return Boolean(elevenLabs(cfg) && cfg.tts?.voice);}+/**+ * Checks whether voice synthesis is ready to execute with an optional override voice.+ * @param cfg The application configuration.+ * @param voiceId Optional override voice ID.+ * @returns True if ready to synthesize speech.+ */export function voiceReady(cfg: AppConfig, voiceId?: string): boolean {const provider = voiceProvider(cfg);if (provider === "gemini") return Boolean(cfg.tts?.geminiKey && gemini.isSupportedVoice(voiceId || cfg.tts?.voice));@@ -65,7 +86,11 @@ export function voiceReady(cfg: AppConfig, voiceId?: string): boolean {return Boolean(elevenLabs(cfg) && (voiceId || cfg.tts?.voice));}-/** Never includes the key. */+/**+ * Returns a redacted voice configuration descriptor for status and UI display. Never includes the key.+ * @param cfg The application configuration.+ * @returns An object describing the current voice configuration status.+ */export function describeVoice(cfg: AppConfig) {const provider = voiceProvider(cfg);const included = provider === "elevenlabs" && elevenLabs(cfg)?.included === true;@@ -81,10 +106,25 @@ export function describeVoice(cfg: AppConfig) {};}-export function verifyKey(provider: "elevenlabs" | "fish", key: string) {- return provider === "fish" ? fish.verifyKey(key) : elevenlabs.verifyKey(key);+/**+ * Verifies an API key with the corresponding speech provider before saving.+ * @param provider The TTS provider name ("elevenlabs" | "fish" | "gemini").+ * @param key The API key to test.+ * @returns Result indicating whether the key is valid.+ */+export function verifyKey(provider: "elevenlabs" | "fish" | "gemini", key: string) {+ if (provider === "fish") return fish.verifyKey(key);+ if (provider === "gemini") return gemini.verifyKey(key);+ return elevenlabs.verifyKey(key);}+/**+ * Lists voices available for the configured TTS provider.+ * @param cfg The application configuration.+ * @param run Optional system runner for native system voices.+ * @param search Optional fish voice search filter.+ * @returns Array of available Voice descriptors.+ */export async function listVoices(cfg: AppConfig,run?: systemVoices.Runner,@@ -107,12 +147,28 @@ export async function listVoices(return elevenlabs.listVoices(credential.token, credential.api, search);}+/**+ * Adds a shared community voice from the Voice Library to the user's account.+ * @param cfg The application configuration.+ * @param publicOwnerId Public owner ID of the shared voice.+ * @param voiceId ID of the shared voice to add.+ * @param name Display name for the added voice.+ * @returns Added voice ID.+ */export async function addSharedVoice(cfg: AppConfig, publicOwnerId: string, voiceId: string, name: string): Promise<string> {const credential = voiceProvider(cfg) === "elevenlabs" ? elevenLabs(cfg) : null;if (!credential) throw new NoVoiceConfigured("key");return elevenlabs.addSharedVoice(credential.token, credential.api, publicOwnerId, voiceId, name);}+/**+ * Synthesizes text to speech using the currently configured provider.+ * @param cfg The application configuration.+ * @param text The plain text to synthesize into spoken audio.+ * @param voiceId Optional override voice ID.+ * @param run Optional runner for system voices.+ * @returns Synthesized audio buffer or stream promise.+ */export function speak(cfg: AppConfig, text: string, voiceId?: string, run?: systemVoices.Runner) {const provider = voiceProvider(cfg);if (provider === "gemini") {