Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Live calls: tie a saved key to where it may go, and refuse redirects on Azure
milind-soni0d4e3c5cb457
diff --git a/apps/docs/content/docs/features/voice-and-memory.mdx b/apps/docs/content/docs/features/voice-and-memory.mdxindex c7fcc7e913..173b579a59 100644--- a/apps/docs/content/docs/features/voice-and-memory.mdx+++ b/apps/docs/content/docs/features/voice-and-memory.mdx@@ -70,7 +70,7 @@ A Live call hangs up after 5 minutes in which nobody speaks and the bot is not wLive calls are free for everyone, from the desktop app, a web browser or your phone; no plan is needed. They use your own OpenAI API key, from a project with GPT-Live access: the OpenAI key in **Settings → API keys**, or a separate key for Live calls set from the call's settings, which wins when both are saved. Without a key, the **Live** button says "Live calls use your own OpenAI key. Add it in Settings → API keys." and offers **Open API keys**; a phone shows the same message, since keys are added on your computer. The key stays where you saved it, on This computer or on My Cloud; phones never receive it. OpenAI bills Live audio at about $0.05 per minute; the bot's own work is billed as usual. Live calls work in any desktop build with a microphone (no on-device dictation needed), and are for one bot at a time. Room calls always take turns.-**Live calls through Azure OpenAI.** If your organisation runs OpenAI models on Azure, a Live call can use a GPT-Live deployment on your own Azure OpenAI or Microsoft Foundry resource instead of OpenAI. Deploy `gpt-live-1` on the resource, then in the call's settings (or the prompt the **Live** button shows when a call is not set up) choose **Azure OpenAI** as the **Service**, paste the resource endpoint (for example `https://my-resource.openai.azure.com`) and the deployment name (empty means `gpt-live-1`), and add a key of that resource. The OpenAI API key is never used for Azure, and the key is only ever sent to an `https` Azure OpenAI host (`*.openai.azure.com`, `*.services.ai.azure.com`, `*.cognitiveservices.azure.com`, Azure Government and Azure China, or an API Management gateway on `*.azure-api.net`). Azure bills the call to that resource. On a server you can set the same thing with `OMB_LIVE_PROVIDER=azure`, `OMB_AZURE_OPENAI_LIVE_ENDPOINT`, `OMB_AZURE_OPENAI_LIVE_DEPLOYMENT` and `OMB_OPENAI_LIVE_KEY` (the resource key). With Azure, everything below that goes to OpenAI goes to your Azure resource instead.+**Live calls through Azure OpenAI.** If your organisation runs OpenAI models on Azure, a Live call can use a GPT-Live deployment on your own Azure OpenAI or Microsoft Foundry resource instead of OpenAI. Deploy `gpt-live-1` on the resource, then in the call's settings (or the prompt the **Live** button shows when a call is not set up) choose **Azure OpenAI** as the **Service**, paste the resource endpoint (for example `https://my-resource.openai.azure.com`) and the deployment name (empty means `gpt-live-1`), and add a key of that resource. Azure bills the call to that resource. The OpenAI API key is never used for Azure. A saved Live key goes only to the service it was saved for and, on Azure, to that endpoint's host: changing the **Service** or the endpoint's host asks for the key again, even if you change it back. Calls go only to an `https` address on `*.openai.azure.com`, `*.services.ai.azure.com`, `*.cognitiveservices.azure.com`, `*.openai.azure.us`, `*.openai.azure.cn` or `*.azure-api.net` (API Management); any other address is refused, and so is a redirect. On a server you can set the same thing with `OMB_LIVE_PROVIDER=azure`, `OMB_AZURE_OPENAI_LIVE_ENDPOINT`, `OMB_AZURE_OPENAI_LIVE_DEPLOYMENT` and `OMB_OPENAI_LIVE_KEY` (the resource key); set together there, the key belongs to that endpoint. With Azure, everything below that goes to OpenAI goes to your Azure resource instead.**Who can make a call through Azure.** Only an admin, or the owner of a server one person uses. Azure does not accept the setting that limits the caller's app to hanging up, so on an Azure call that app's connection to the voice is wider, and could carry the bot's instructions. Everyone else, such as a User on a Team Cloud or someone who is not an admin on a shared company workspace, reads "Live calls here go through Azure OpenAI, so only an admin or the owner of this server can start one. Ask an admin if you need a call." No call starts, and it never goes through OpenAI instead.diff --git a/docs/verification/live-calls.md b/docs/verification/live-calls.mdindex 126657cb31..43a929ca05 100644--- a/docs/verification/live-calls.md+++ b/docs/verification/live-calls.md@@ -61,11 +61,28 @@ GPT-Live session on the person's Azure OpenAI / Foundry resource:(`live.azureDeployment`, `OMB_AZURE_OPENAI_LIVE_DEPLOYMENT`, default`gpt-live-1`) as `session.model`, and the sideband attaches to`wss://{endpoint}/openai/v1/live/sessions/{id}/attach`. Both send the resource-key as `api-key`, never as a bearer token. The key is only `live.key`; the-OpenAI API key is never used for Azure. `live.azureEndpoint`+key as `api-key`, never as a bearer token, and the session request refuses a+redirect, since `fetch` would carry `api-key` to another host. The key is only+`live.key`; the OpenAI API key is never used for Azure. `live.azureEndpoint`(`OMB_AZURE_OPENAI_LIVE_ENDPOINT`) must be `https` on an Azure OpenAI host(`azureOpenAiRoot` in `server/live-call.ts`), and `PATCH /api/live/settings`-refuses any other. Without the key, or with a missing or invalid endpoint,+refuses any other.++`live.key` goes only where it was saved for. Saving a key records `live.keyFor`:+`openai` or `azure:<host>` (`liveKeyTarget` in `server/live-config.ts`), and+`usableLiveKey` hands the key out only while calls go there. Switching the+Service or changing the endpoint's host, through `PATCH /api/live/settings` or+`PUT /api/config`, forgets the key and asks for it again, even after changing+back (`liveSavePatch`). A new path or deployment on the same host keeps it.+`keyFor` is never taken from a request. A key saved with Azure chosen and no+endpoint answers `400`. A key with no `keyFor` is from before Azure was offered,+so OpenAI's. In the environment, `OMB_OPENAI_LIVE_KEY` with `OMB_LIVE_PROVIDER=azure`+and `OMB_AZURE_OPENAI_LIVE_ENDPOINT` is the operator's own pairing, unless the+file already says where the key may go. So a key the app forgot stays forgotten+until one is saved again, including the desktop's copy in the OS store, and a+different key in the environment takes no pairing from the file.++Without the key, or with a missing or invalid endpoint,`POST /api/live/session` answers `409` with `needsKey` and the Azure setupsentence before anything leaves the harness. A call keeps the endpoint itstarted with even if the settings change mid-call.diff --git a/server/index.ts b/server/index.tsindex 6859710f32..77b833f608 100644--- a/server/index.ts+++ b/server/index.ts@@ -313,7 +313,7 @@ import { createDecider, deciderReady, describeDecider } from "./decider/index.tsimport { decideRoomResponder } from "./decider/room-routing.ts"; import { roomRoutingInput } from "./host/room-routing-input.ts";import { createLiveSession, liveAttachUrl, liveHistoryFrom, LiveSessionError, type LiveBot, type LiveHistoryMessage } from "./live-call.ts";import { LiveCallController, LiveCallSignedOutError, openLiveSocket } from "./live-call-controller.ts";-import { liveCallSettings, liveSettingsFor, liveSettingsForClient } from "./live-settings.ts"; import { azureLiveCallRefusal, liveScopeRefusal } from "./live-access.ts";+import { liveCallSettings, liveSettingsFor, liveSettingsForClient, saveLiveSettings } from "./live-settings.ts"; import { azureLiveCallRefusal, liveScopeRefusal } from "./live-access.ts";import { recordLiveCall, spokenLineFields, titleLiveCall } from "./live-call-record.ts";import { narrateTool, toUtterances } from "./tts/speech-text.ts";import { createTtsRoutes } from "./routes/tts.ts";@@ -12671,7 +12671,7 @@ ROUTES.push(createLiveRoutes({settings: () => liveSettingsFor(cfg),saveSettings: async (patch) => {if (providerConfigBusy) throw Object.assign(new Error("Settings are already being updated. Try again in a moment."), { status: 409 });- saveConfig({ live: patch });+ saveLiveSettings(cfg, patch);Object.assign(cfg, loadConfig());broadcast({ kind: "config", ...configStatus() });return liveSettingsFor(cfg);diff --git a/server/key-hint.ts b/server/key-hint.tsindex f94608356d..6f5a7a7c15 100644--- a/server/key-hint.ts+++ b/server/key-hint.ts@@ -1,4 +1,5 @@import type { AppConfig } from "./config.ts";+import { usableLiveKey } from "./live-config.ts";/** Security: a hint is the last four characters of a key long enough that four reveal nothing useful, and only admins* receive one; withoutKeyHints() takes every hint off what a client session is sent. */@@ -22,7 +23,7 @@ export function nestedKeyStatus(cfg: AppConfig) {workersAiToken: keyStatus(cfg.decider?.workersAiToken),openaiImageApiKey: keyStatus(cfg.imageGen?.key),customImageApiKey: keyStatus(cfg.imageGen?.customApiKey),- openaiLiveKey: keyStatus(cfg.live?.key),+ openaiLiveKey: keyStatus(usableLiveKey(cfg.live)),};}diff --git a/server/live-azure-access.e2e.test.ts b/server/live-azure-access.e2e.test.tsindex 38527877a1..e9a80079e9 100644--- a/server/live-azure-access.e2e.test.ts+++ b/server/live-azure-access.e2e.test.ts@@ -11,6 +11,8 @@ import { fileURLToPath } from "node:url";import { afterEach, expect, it } from "vitest";import { cloudPairingSignature } from "./cloud-home.ts";import { LIVE_AZURE_REFUSAL } from "./live-access.ts";+import { LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY } from "./live-call.ts";+import { LIVE_KEY_NEEDS_ENDPOINT } from "./live-config.ts";import { removeTempDir, waitForExit } from "./testing/cleanup.ts";import { freePortBlock } from "./testing/ports.ts";@@ -45,14 +47,14 @@ async function boot(env: NodeJS.ProcessEnv, config: Record<string, unknown> = {}...Object.fromEntries(["codex", "cursor", "githubCopilot", "openaiCompat", "qwen", "hermes", "pi"].map((id) => [id, { driver: "not-a-real-driver" }])),claude: { driver: "claudeAgent", config: { cli: FAKE_CLAUDE, permissionMode: "bypassPermissions" } },},- live: { provider: "azure", azureEndpoint: ENDPOINT, azureDeployment: "fixture-dep", key: "fixture-not-a-key" },+ live: { provider: "azure", azureEndpoint: ENDPOINT, azureDeployment: "fixture-dep", key: "fixture-not-a-key", keyFor: "azure:fixture.openai.azure.com" },// There to fall back on: a refused caller must not get a call through OpenAI instead.openai: { key: "fixture-not-a-key-either" },...config,}));const port = await freePortBlock([0, 1]);const base = `http://127.0.0.1:${port}`;- const prelude = `data:text/javascript,${encodeURIComponent(`import { appendFileSync } from "node:fs"; globalThis.fetch = async (url) => { appendFileSync(${JSON.stringify(fetches)}, String(url) + "\\n"); return new Response("offline fixture", { status: 503 }); };`)}`;+ const prelude = `data:text/javascript,${encodeURIComponent(`import { appendFileSync } from "node:fs"; globalThis.fetch = async (url, init) => { const headers = new Headers(init?.headers); appendFileSync(${JSON.stringify(fetches)}, JSON.stringify({ url: String(url), apiKey: headers.get("api-key"), authorization: headers.get("authorization") }) + "\\n"); return new Response("offline fixture", { status: 503 }); };`)}`;const child: ChildProcess = spawn(process.execPath, ["--import", prelude, join(SERVER_DIR, "index.ts")], {cwd: join(SERVER_DIR, ".."),env: {@@ -101,9 +103,13 @@ async function boot(env: NodeJS.ProcessEnv, config: Record<string, unknown> = {}expect(created.status, JSON.stringify(created.body)).toBe(201);return created.body.bot.id as string;};- const liveSessions = () => (existsSync(fetches) ? readFileSync(fetches, "utf8") : "").split("\n").filter((url) => url.includes("/live/sessions"));+ /** Each session request the server tried: where it went, and with which key. */+ const sent = () => (existsSync(fetches) ? readFileSync(fetches, "utf8") : "").split("\n").filter(Boolean)+ .map((line) => JSON.parse(line) as { url: string; apiKey: string | null; authorization: string | null }).filter(({ url }) => url.includes("/live/sessions"));+ const liveSessions = () => sent().map(({ url }) => url);+ const savedLive = () => JSON.parse(readFileSync(join(dataDir, "config.json"), "utf8")).live as Record<string, unknown>;const start = (botId: string, headers: Headers = {}) => call("POST", "/api/live/session", { botId, sdp: "v=0\r\n", client: "web" }, headers);- return { call, redeem, signedSession, newBot, liveSessions, start };+ return { call, redeem, signedSession, newBot, liveSessions, sent, savedLive, start };}const CLOUD_ENV = {@@ -182,3 +188,149 @@ it("on a Team Cloud: a Super admin and an Admin get through; a User is refused iexpect(seen).not.toHaveProperty("azureEndpoint");expect(seen).not.toHaveProperty("azureDeployment");}, 90_000);++type Fixture = Awaited<ReturnType<typeof boot>>;+const GATEWAY = "https://gw.azure-api.net/team-a";+const OTHER = "https://other.openai.azure.com";+const OPENAI_SESSIONS = "https://api.openai.com/v1/live/sessions";++/** Asks and checks: a call that reaches `url` with exactly this key, or a call that asks for a key and sends nothing. */+function keyChecks(s: Fixture, botId: string) {+ return {+ reaches: async (url: string, apiKey: string | null, authorization: string | null = null) => {+ const before = s.sent().length;+ expect((await s.start(botId)).status).toBe(502);+ expect(s.sent().slice(before)).toEqual([{ url, apiKey, authorization }]);+ },+ asksForKey: async (error: string) => {+ const before = s.sent().length;+ expect(await s.start(botId)).toEqual({ status: 409, body: { error, needsKey: true } });+ expect(s.sent()).toHaveLength(before);+ },+ saveKey: async (key: string) => {+ const saved = await s.call("PUT", "/api/config", { live: { key } });+ expect(saved.status, JSON.stringify(saved.body)).toBe(200);+ },+ };+}++it.each([+ ["PATCH /api/live/settings", (s: Fixture, settings: Record<string, unknown>) => s.call("PATCH", "/api/live/settings", settings)],+ ["PUT /api/config", (s: Fixture, settings: Record<string, unknown>) => s.call("PUT", "/api/config", { live: settings })],+] as const)("through %s, a saved key goes only to the service and host it was saved for, and changing either asks for it again", async (_route, change) => {+ const s = await boot({}, { live: { provider: "azure", azureEndpoint: ENDPOINT }, openai: {} });+ const botId = await s.newBot();+ const { reaches, asksForKey, saveKey } = keyChecks(s, botId);+ const changed = async (settings: Record<string, unknown>) => {+ const answer = await change(s, settings);+ expect(answer.status, JSON.stringify(answer.body)).toBe(200);+ return answer.body.live as Record<string, unknown>;+ };++ await asksForKey(LIVE_NEEDS_AZURE);+ await saveKey("key-for-fixture");+ await reaches(SESSIONS, "key-for-fixture");++ // A new path or deployment on the same host keeps it.+ await changed({ azureEndpoint: `${ENDPOINT}/openai/v1`, azureDeployment: "other-dep" });+ await reaches(SESSIONS, "key-for-fixture");++ // Another host does not, and changing back does not bring it back.+ const afterMove = await changed({ azureEndpoint: OTHER });+ expect(afterMove).toMatchObject({ provider: "azure", configured: false });+ expect(afterMove).not.toHaveProperty("keySource");+ await asksForKey(LIVE_NEEDS_AZURE);+ expect(s.savedLive()).toMatchObject({ key: "", keyFor: "nowhere" });+ expect((await s.call("GET", "/api/config")).body.savedKeys.openaiLiveKey.configured).toBe(false);+ await changed({ azureEndpoint: ENDPOINT });+ await asksForKey(LIVE_NEEDS_AZURE);++ // An API Management gateway stays allowed, with a key saved for it.+ await changed({ azureEndpoint: GATEWAY });+ await asksForKey(LIVE_NEEDS_AZURE);+ await saveKey("key-for-gateway");+ await reaches(`${GATEWAY}/openai/v1/live/sessions`, "key-for-gateway");++ // Switching Service: the Azure key never goes to OpenAI.+ await changed({ provider: "openai" });+ await asksForKey(LIVE_NEEDS_KEY);+ await saveKey("key-for-openai");+ await reaches(OPENAI_SESSIONS, null, "Bearer key-for-openai");++ // And an OpenAI key never goes to Azure, even to a host a key was saved for before.+ await changed({ provider: "azure" });+ await asksForKey(LIVE_NEEDS_AZURE);+ await changed({ provider: "openai" });+ await asksForKey(LIVE_NEEDS_KEY);++ // The OpenAI API key is OpenAI's, for a call through OpenAI only.+ expect((await s.call("PUT", "/api/config", { openai: { key: "openai-api-key" } })).status).toBe(200);+ await reaches(OPENAI_SESSIONS, null, "Bearer openai-api-key");+ await changed({ provider: "azure" });+ await asksForKey(LIVE_NEEDS_AZURE);++ const keysAt = (key: string) => [...new Set(s.sent().filter(({ apiKey, authorization }) => apiKey === key || authorization === `Bearer ${key}`).map(({ url }) => url))];+ expect(keysAt("key-for-fixture")).toEqual([SESSIONS]);+ expect(keysAt("key-for-gateway")).toEqual([`${GATEWAY}/openai/v1/live/sessions`]);+ expect(keysAt("key-for-openai")).toEqual([OPENAI_SESSIONS]);+ expect(keysAt("openai-api-key")).toEqual([OPENAI_SESSIONS]);+}, 90_000);++it("takes no keyFor from a request, and refuses a key with Azure chosen and no endpoint to tie it to", async () => {+ const s = await boot({}, { live: { provider: "azure" } });+ const botId = await s.newBot();+ const { reaches, asksForKey, saveKey } = keyChecks(s, botId);+ expect(await s.call("PUT", "/api/config", { live: { key: "too-soon" } })).toEqual({ status: 400, body: { error: LIVE_KEY_NEEDS_ENDPOINT } });+ expect(s.savedLive()).not.toHaveProperty("key");++ expect((await s.call("PUT", "/api/config", { live: { azureEndpoint: ENDPOINT } })).status).toBe(200);+ await saveKey("key-for-fixture");+ await reaches(SESSIONS, "key-for-fixture");++ // Claiming the key is for the new host changes nothing.+ expect((await s.call("PUT", "/api/config", { live: { azureEndpoint: OTHER, keyFor: "azure:other.openai.azure.com", key: "" } })).status).toBe(200);+ await asksForKey(LIVE_NEEDS_AZURE);+ expect((await s.call("PUT", "/api/config", { live: { keyFor: "azure:other.openai.azure.com" } })).status).toBe(200);+ await asksForKey(LIVE_NEEDS_AZURE);+ expect(s.savedLive().keyFor).toBe("nowhere");+ expect((await s.call("PATCH", "/api/live/settings", { keyFor: "azure:other.openai.azure.com" })).status).toBe(400);+}, 60_000);++it("the desktop's way of saving, with the key kept outside the file, ties it just the same", async () => {+ const s = await boot({}, { live: { provider: "azure", azureEndpoint: ENDPOINT } });+ const botId = await s.newBot();+ const { reaches, asksForKey } = keyChecks(s, botId);+ expect((await s.call("PUT", "/api/config?secretStorage=external", { live: { key: "from-the-store" } })).status).toBe(200);+ expect(s.savedLive()).toMatchObject({ key: "", keyFor: "azure:fixture.openai.azure.com" });+ await reaches(SESSIONS, "from-the-store");+ expect((await s.call("PATCH", "/api/live/settings", { azureEndpoint: OTHER })).status).toBe(200);+ await asksForKey(LIVE_NEEDS_AZURE);+ expect((await s.call("PATCH", "/api/live/settings", { azureEndpoint: ENDPOINT })).status).toBe(200);+ await asksForKey(LIVE_NEEDS_AZURE);+}, 60_000);++it("a server set up in the environment: the key goes to the endpoint set beside it, until an admin changes the endpoint", async () => {+ const s = await boot({ OMB_LIVE_PROVIDER: "azure", OMB_AZURE_OPENAI_LIVE_ENDPOINT: ENDPOINT, OMB_OPENAI_LIVE_KEY: "operators-key" }, { live: {} });+ const botId = await s.newBot();+ const { reaches, asksForKey } = keyChecks(s, botId);+ await reaches(SESSIONS, "operators-key");+ expect((await s.call("PATCH", "/api/live/settings", { azureEndpoint: OTHER })).status).toBe(200);+ await asksForKey(LIVE_NEEDS_AZURE);+}, 60_000);++it.each([+ ["the environment", { OMB_LIVE_PROVIDER: "azure", OMB_AZURE_OPENAI_LIVE_ENDPOINT: ENDPOINT }, null],+ ["PUT /api/config", {}, { provider: "azure", azureEndpoint: ENDPOINT }],+] as const)("a provider set by %s gives way to a later PATCH /api/live/settings", async (_from, env, viaConfig) => {+ const s = await boot({ ...env }, { live: {} });+ if (viaConfig) expect((await s.call("PUT", "/api/config", { live: viaConfig })).status).toBe(200);+ expect((await s.call("GET", "/api/config")).body.live.provider).toBe("azure");++ const patched = await s.call("PATCH", "/api/live/settings", { provider: "openai" });+ expect(patched.status).toBe(200);+ expect(patched.body.live).not.toHaveProperty("provider");+ expect((await s.call("GET", "/api/config")).body.live).not.toHaveProperty("provider");+ expect(s.savedLive().provider).toBe("openai");++ expect((await s.call("PATCH", "/api/live/settings", { azureEndpoint: OTHER, provider: "azure" })).body.live).toMatchObject({ provider: "azure", azureEndpoint: OTHER });+}, 60_000);diff --git a/server/live-call.test.ts b/server/live-call.test.tsindex a7a67cc6f4..b8d5923fec 100644--- a/server/live-call.test.ts+++ b/server/live-call.test.ts@@ -1,5 +1,9 @@-import { describe, expect, it, vi } from "vitest";+import { createServer, type IncomingMessage, type RequestListener, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import type { Duplex } from "node:stream";+import { afterEach, describe, expect, it, vi } from "vitest";+import { openLiveSocket } from "./live-call-controller.ts";import {azureLiveEndpoint,azureOpenAiRoot,@@ -16,6 +20,7 @@ import {liveSessionsUrl,MAX_SDP_BYTES,openAiLiveEndpoint,+ type LiveEndpoint,} from "./live-call.ts";import { CLOUD_HOME_PLACE } from "./system-prompt.ts";@@ -276,6 +281,69 @@ describe("azureOpenAiRoot", () => {});});+describe("the key on real connections, to a loopback server", () => {+ const servers: Server[] = [];+ afterEach(() => {+ for (const server of servers.splice(0)) {+ server.closeAllConnections();+ server.close();+ }+ });+ const listen = async (onRequest: RequestListener, onUpgrade?: (req: IncomingMessage, socket: Duplex) => void) => {+ const server = createServer(onRequest);+ if (onUpgrade) server.on("upgrade", onUpgrade);+ servers.push(server);+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));+ return (server.address() as AddressInfo).port;+ };+ const azureAt = (port: number): LiveEndpoint => ({ provider: "azure", apiBase: `http://127.0.0.1:${port}/openai/v1`, model: "dep" });+ const openAiAt = (port: number): LiveEndpoint => ({ provider: "openai", apiBase: `http://127.0.0.1:${port}/v1`, model: "dep" });+ const sessionAt = (endpoint: LiveEndpoint) => createLiveSession({ key: "made-up-key", endpoint, sdp: OFFER, bot: BOT, history: [], cloudHome: false });++ it("refuses a redirect on Azure, so api-key never reaches another host", async () => {+ const reached: IncomingMessage[] = [];+ const other = await listen((req, res) => { reached.push(req); res.end("{}"); });+ const first = await listen((_req, res) => { res.writeHead(307, { location: `http://127.0.0.1:${other}/elsewhere` }).end(); });+ await expect(sessionAt(azureAt(first))).rejects.toMatchObject({ status: 502 });+ expect(reached).toEqual([]);+ });++ it("asks fetch to refuse redirects on Azure, and leaves OpenAI's request as it was", async () => {+ const fetchImpl = okFetch();+ const session = { key: "k", sdp: OFFER, bot: BOT, history: [], cloudHome: false, fetchImpl };+ await createLiveSession({ ...session, endpoint: azureLiveEndpoint("https://my-res.openai.azure.com", "dep")! });+ await createLiveSession({ ...session, endpoint: openAiLiveEndpoint({}) });+ expect(fetchImpl.mock.calls.map(([, init]) => init?.redirect)).toEqual(["error", undefined]);+ });++ const attempt = (url: string, endpoint: LiveEndpoint) => new Promise<void>((settled) => {+ const socket = openLiveSocket(url, "made-up-key", endpoint);+ socket.onerror = () => settled();+ socket.onclose = () => settled();+ });++ it("sends the sideband's key as api-key on Azure and as a bearer token on OpenAI", async () => {+ const heard: IncomingMessage["headers"][] = [];+ const port = await listen(() => {}, (req, socket) => {+ heard.push(req.headers);+ socket.end("HTTP/1.1 403 Forbidden\r\n\r\n");+ });+ await attempt(liveAttachUrl("sess_1", azureAt(port)), azureAt(port));+ await attempt(liveAttachUrl("sess_1", openAiAt(port)), openAiAt(port));+ expect(heard.map((headers) => [headers["api-key"], headers.authorization])).toEqual([["made-up-key", undefined], [undefined, "Bearer made-up-key"]]);+ });++ it("never follows a redirect on the sideband, so its api-key stays with the first host", async () => {+ const reached: string[] = [];+ const other = await listen((req, res) => { reached.push(String(req.url)); res.end(); }, (req, socket) => { reached.push(String(req.url)); socket.destroy(); });+ const first = await listen(() => {}, (_req, socket) => {+ socket.end(`HTTP/1.1 307 Temporary Redirect\r\nLocation: ws://127.0.0.1:${other}/elsewhere\r\nConnection: close\r\n\r\n`);+ });+ await attempt(liveAttachUrl("sess_1", azureAt(first)), azureAt(first));+ expect(reached).toEqual([]);+ });+});+describe("createLiveSession on Azure", () => {it("sends the resource key as api-key, never as a bearer token, and the deployment as the model", async () => {const fetchImpl = okFetch();diff --git a/server/live-call.ts b/server/live-call.tsindex f38c47cc0c..93c316b6c3 100644--- a/server/live-call.ts+++ b/server/live-call.ts@@ -28,7 +28,7 @@ export const LIVE_DATA_CHANNEL = {],};-/** Hosts an Azure OpenAI or Foundry resource answers on, including Azure Government, Azure China and API Management gateways. The key is only ever sent to one of these. */+/** The hosts an Azure call may use: Azure OpenAI and Foundry resources, Azure OpenAI on Azure Government (.us) and Azure China (.cn), and API Management gateways on .azure-api.net. The key is only ever sent to one of these, and to the one it was saved for. */const AZURE_HOST_SUFFIXES = [".openai.azure.com",".services.ai.azure.com",@@ -231,6 +231,8 @@ export async function createLiveSession(input: CreateLiveSessionInput): Promise<response = await (input.fetchImpl ?? fetch)(liveSessionsUrl(endpoint), {method: "POST",headers: { ...liveAuthHeaders(endpoint.provider, key), "content-type": "application/json" },+ // fetch drops `authorization` on a redirect to another host, but keeps `api-key`.+ ...(endpoint.provider === "azure" ? { redirect: "error" as const } : {}),body: JSON.stringify(body),signal: AbortSignal.timeout(input.timeoutMs ?? CREATE_TIMEOUT_MS),});diff --git a/server/live-config.ts b/server/live-config.tsindex ee2413047a..4ec8d893ef 100644--- a/server/live-config.ts+++ b/server/live-config.ts@@ -1,9 +1,13 @@// Live calls' settings in config.json: schema, type and environment overrides, kept out of server/config.ts.import { z } from "zod";-/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required. `azureEndpoint` is the resource URL and `azureDeployment` the gpt-live-1 deployment name. `voice` is a GPT-Live voice. */+export const LIVE_KEY_NEEDS_ENDPOINT = "Save the Azure endpoint first: a Live key works only with the endpoint it was saved for.";+const NOWHERE = "nowhere";++/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required. `keyFor` says where `key` may go (`liveKeyTarget`): the server sets it when the key is saved and never takes it from a request; absent, the key is from before Azure was offered, so OpenAI's. `azureEndpoint` is the resource URL and `azureDeployment` the gpt-live-1 deployment name. `voice` is a GPT-Live voice. */export const liveConfigSchema = z.object({key: z.string().optional(),+ keyFor: z.string().max(300).optional(),provider: z.enum(["openai", "azure"]).optional(),azureEndpoint: z.string().trim().max(300).optional(),azureDeployment: z.string().trim().max(64).optional(),@@ -14,6 +18,7 @@ export const liveConfigSchema = z.object({export interface LiveConfig {key?: string;+ keyFor?: string;provider?: "openai" | "azure";azureEndpoint?: string;azureDeployment?: string;@@ -22,13 +27,52 @@ export interface LiveConfig {idleMinutes?: number;}+/** Where a key saved now may go: "openai", or "azure:<host>"; null while Azure is chosen with no endpoint to tie it to. */+export function liveKeyTarget(live: LiveConfig | undefined): string | null {+ if (live?.provider !== "azure") return "openai";+ try {+ const host = new URL(live.azureEndpoint?.trim() ?? "").host.toLowerCase();+ return host ? `azure:${host}` : null;+ } catch {+ return null;+ }+}++/** The saved key, only while calls go where it was saved for. */+export function usableLiveKey(live: LiveConfig | undefined): string | undefined {+ const key = live?.key?.trim();+ const target = liveKeyTarget(live);+ return key && target && (live?.keyFor ?? "openai") === target ? key : undefined;+}++/** What to save for a change to `live`: a new key is tied to where calls now go, and any other change of where they go+ * forgets the old one. On the desktop the OS store keeps a copy the server cannot delete, which comes back as+ * OMB_OPENAI_LIVE_KEY at the next launch: "nowhere" keeps that copy unusable until a key is saved again. */+export function liveSavePatch(current: LiveConfig | undefined, patch: LiveConfig): LiveConfig {+ const { keyFor: _fromRequest, ...asked } = patch;+ const target = liveKeyTarget({ ...current, ...asked });+ if (asked.key?.trim()) {+ if (!target) throw Object.assign(new Error(LIVE_KEY_NEEDS_ENDPOINT), { status: 400 });+ return { ...asked, keyFor: target };+ }+ return asked.key !== undefined || target !== liveKeyTarget(current) ? { ...asked, key: "", keyFor: NOWHERE } : asked;+}+export function liveConfigWithEnv(live: LiveConfig | undefined, env: NodeJS.ProcessEnv = process.env): LiveConfig {const next = { ...live };- if (env.OMB_OPENAI_LIVE_KEY !== undefined) next.key = env.OMB_OPENAI_LIVE_KEY;+ const envKey = env.OMB_OPENAI_LIVE_KEY;+ if (envKey !== undefined) {+ // A different key from the environment is not the one `keyFor` was saved for.+ if (next.key?.trim() && next.key.trim() !== envKey.trim()) delete next.keyFor;+ next.key = envKey;+ }const provider = env.OMB_LIVE_PROVIDER?.trim().toLowerCase();if (provider === "openai" || provider === "azure") next.provider = provider;if (env.OMB_AZURE_OPENAI_LIVE_ENDPOINT !== undefined) next.azureEndpoint = env.OMB_AZURE_OPENAI_LIVE_ENDPOINT.trim();if (env.OMB_AZURE_OPENAI_LIVE_DEPLOYMENT !== undefined) next.azureDeployment = env.OMB_AZURE_OPENAI_LIVE_DEPLOYMENT.trim();+ // Set together in the environment, the key and the Azure endpoint are the operator's own pairing. A `keyFor` from the+ // file stands: saves mirror settings into the environment, so they must not be able to pair a forgotten key.+ if (envKey?.trim() && provider === "azure" && env.OMB_AZURE_OPENAI_LIVE_ENDPOINT?.trim() && next.keyFor === undefined) next.keyFor = liveKeyTarget(next) ?? NOWHERE;return next;}diff --git a/server/live-settings.test.ts b/server/live-settings.test.tsindex 5fc8bc652f..5c2e313d6d 100644--- a/server/live-settings.test.ts+++ b/server/live-settings.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from "vitest";import type { AppConfig } from "./config.ts";+import { nestedKeyStatus } from "./key-hint.ts";import { LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY } from "./live-call.ts";+import { LIVE_KEY_NEEDS_ENDPOINT, liveConfigWithEnv, liveKeyTarget, liveSavePatch, usableLiveKey, type LiveConfig } from "./live-config.ts";import { LIVE_IDLE_MINUTES_DEFAULT, liveCallEndpoint, liveCallKey, liveCallSettings, liveSettingsFor, liveSettingsForClient, liveSetupProblem } from "./live-settings.ts";describe("live settings", () => {@@ -41,6 +43,7 @@ describe("the key a Live call uses", () => {describe("Live calls through Azure OpenAI", () => {const azure = { provider: "azure" as const, azureEndpoint: "https://my-res.openai.azure.com", azureDeployment: "live-prod" };+ const keyFor = "azure:my-res.openai.azure.com";it("never use the OpenAI API key as the Azure resource key", () => {const cfg = { live: azure, openai: { key: "sk-openai" } } as AppConfig;@@ -50,7 +53,7 @@ describe("Live calls through Azure OpenAI", () => {});it("are ready with the Live key, a valid endpoint and a deployment, and report none of the key", () => {- const cfg = { live: { ...azure, key: "azure-secret" } } as AppConfig;+ const cfg = { live: { ...azure, key: "azure-secret", keyFor } } as AppConfig;expect(liveCallKey(cfg)).toEqual({ key: "azure-secret", source: "live" });expect(liveCallEndpoint(cfg)).toEqual({ provider: "azure", apiBase: "https://my-res.openai.azure.com/openai/v1", model: "live-prod" });expect(liveSetupProblem(cfg)).toBeNull();@@ -68,12 +71,12 @@ describe("Live calls through Azure OpenAI", () => {it("name the provider in what a call start reads, so the limit on Azure sees it even before setup is done", () => {expect(liveCallSettings({ live: { provider: "azure" } } as AppConfig)).toMatchObject({ provider: "azure", endpoint: null, key: "", setupProblem: LIVE_NEEDS_AZURE });- expect(liveCallSettings({ live: { ...azure, key: "k" } } as AppConfig)).toMatchObject({ provider: "azure", key: "k", setupProblem: null, endpoint: { provider: "azure" } });+ expect(liveCallSettings({ live: { ...azure, key: "k", keyFor } } as AppConfig)).toMatchObject({ provider: "azure", key: "k", setupProblem: null, endpoint: { provider: "azure" } });expect(liveCallSettings({ openai: { key: "sk" } } as AppConfig).provider).toBeUndefined();});it("tell a caller without the admin scope the service, not which resource", () => {- const client = liveSettingsForClient(liveSettingsFor({ live: { ...azure, key: "azure-secret" } } as AppConfig));+ const client = liveSettingsForClient(liveSettingsFor({ live: { ...azure, key: "azure-secret", keyFor } } as AppConfig));expect(client).toEqual({ configured: true, keySource: "live", provider: "azure", voice: "", readTypedReplies: true, idleMinutes: 5 });expect(JSON.stringify(client)).not.toContain("my-res");expect(JSON.stringify(client)).not.toContain("live-prod");@@ -88,3 +91,142 @@ describe("Live calls through Azure OpenAI", () => {expect(liveSetupProblem({} as AppConfig)).toBe(LIVE_NEEDS_KEY);});});++describe("a saved Live key", () => {+ const A = "https://a.openai.azure.com", B = "https://b.openai.azure.com";+ const onA: LiveConfig = { provider: "azure", azureEndpoint: A, key: "k", keyFor: "azure:a.openai.azure.com" };++ it("is tied to the service and the endpoint's host, not its path", () => {+ expect(liveKeyTarget(undefined)).toBe("openai");+ expect(liveKeyTarget({ provider: "openai", azureEndpoint: A })).toBe("openai");+ expect(liveKeyTarget({ provider: "azure", azureEndpoint: A })).toBe("azure:a.openai.azure.com");+ expect(liveKeyTarget({ provider: "azure", azureEndpoint: " https://A.OpenAI.Azure.com/openai/v1?x=1 " })).toBe("azure:a.openai.azure.com");+ expect(liveKeyTarget({ provider: "azure", azureEndpoint: "https://gw.azure-api.net/team-a" })).toBe("azure:gw.azure-api.net");+ expect(liveKeyTarget({ provider: "azure", azureEndpoint: `${A}:8443` })).toBe("azure:a.openai.azure.com:8443");+ for (const azureEndpoint of [undefined, "", "a.openai.azure.com"]) expect(liveKeyTarget({ provider: "azure", azureEndpoint }), String(azureEndpoint)).toBeNull();+ });++ it("goes only where it was saved for", () => {+ expect(usableLiveKey(onA)).toBe("k");+ expect(usableLiveKey({ ...onA, azureEndpoint: `${A}/openai/v1` })).toBe("k");+ expect(usableLiveKey({ ...onA, azureEndpoint: B })).toBeUndefined();+ expect(usableLiveKey({ ...onA, azureEndpoint: `${A}:8443` })).toBeUndefined();+ expect(usableLiveKey({ ...onA, provider: "openai" })).toBeUndefined();+ expect(usableLiveKey({ key: "k", keyFor: "openai" })).toBe("k");+ expect(usableLiveKey({ key: "k", keyFor: "openai", provider: "azure", azureEndpoint: A })).toBeUndefined();+ expect(usableLiveKey({ key: "k", keyFor: "nowhere" })).toBeUndefined();+ expect(usableLiveKey({ key: "k", keyFor: "nowhere", provider: "azure", azureEndpoint: A })).toBeUndefined();+ expect(usableLiveKey({ ...onA, key: " " })).toBeUndefined();+ });++ it("from before Azure was offered is OpenAI's", () => {+ expect(usableLiveKey({ key: "old" })).toBe("old");+ expect(usableLiveKey({ key: "old", provider: "azure", azureEndpoint: A })).toBeUndefined();+ });++ it("never reaches the wrong provider through liveCallKey, whatever else is saved", () => {+ const openai = { key: "sk-openai" };+ expect(liveCallKey({ live: onA, openai } as AppConfig)).toEqual({ key: "k", source: "live" });+ expect(liveCallKey({ live: { ...onA, azureEndpoint: B }, openai } as AppConfig)).toBeNull();+ // Back on OpenAI the Azure key stays behind, and OpenAI's own key is OpenAI's to use.+ expect(liveCallKey({ live: { ...onA, provider: "openai" }, openai } as AppConfig)).toEqual({ key: "sk-openai", source: "openai" });+ expect(liveCallKey({ live: { ...onA, provider: "openai" } } as AppConfig)).toBeNull();+ });++ it("counts as saved only while it can be used", () => {+ expect(nestedKeyStatus({ live: onA } as AppConfig).openaiLiveKey.configured).toBe(true);+ expect(nestedKeyStatus({ live: { ...onA, azureEndpoint: B } } as AppConfig).openaiLiveKey.configured).toBe(false);+ expect(nestedKeyStatus({ live: { ...onA, keyFor: "nowhere" } } as AppConfig).openaiLiveKey.configured).toBe(false);+ });++ describe("saving", () => {+ const forgotten = { key: "", keyFor: "nowhere" };++ it("ties a new key to where calls go after this same save", () => {+ expect(liveSavePatch(undefined, { key: "new" })).toEqual({ key: "new", keyFor: "openai" });+ expect(liveSavePatch(onA, { key: "new" })).toEqual({ key: "new", keyFor: "azure:a.openai.azure.com" });+ expect(liveSavePatch(onA, { key: "new", azureEndpoint: B })).toEqual({ key: "new", azureEndpoint: B, keyFor: "azure:b.openai.azure.com" });+ expect(liveSavePatch(undefined, { key: "new", provider: "azure", azureEndpoint: B })).toEqual({ key: "new", provider: "azure", azureEndpoint: B, keyFor: "azure:b.openai.azure.com" });+ });++ it("refuses a key with Azure chosen and no endpoint to tie it to", () => {+ expect(() => liveSavePatch({ provider: "azure" }, { key: "new" })).toThrow(LIVE_KEY_NEEDS_ENDPOINT);+ expect(() => liveSavePatch(undefined, { provider: "azure", key: "new" })).toThrow(expect.objectContaining({ status: 400 }));+ });++ it("forgets the key when the service or the endpoint's host changes", () => {+ expect(liveSavePatch(onA, { azureEndpoint: B })).toEqual({ azureEndpoint: B, ...forgotten });+ expect(liveSavePatch(onA, { provider: "openai" })).toEqual({ provider: "openai", ...forgotten });+ expect(liveSavePatch(onA, { azureEndpoint: "" })).toEqual({ azureEndpoint: "", ...forgotten });+ expect(liveSavePatch(onA, { azureEndpoint: `${A}:8443` })).toEqual({ azureEndpoint: `${A}:8443`, ...forgotten });+ expect(liveSavePatch({ key: "old" }, { provider: "azure", azureEndpoint: A })).toEqual({ provider: "azure", azureEndpoint: A, ...forgotten });+ });++ it("keeps the key for anything else, including a new path or deployment on the same host", () => {+ for (const patch of [{ voice: "cedar" }, { idleMinutes: 9 }, { azureDeployment: "other" }, { provider: "azure" as const }, { azureEndpoint: `${A}/openai/v1` }]) {+ expect(liveSavePatch(onA, patch), JSON.stringify(patch)).toEqual(patch);+ }+ expect(liveSavePatch({ key: "old" }, { voice: "cedar" })).toEqual({ voice: "cedar" });+ });++ it("forgets it when asked to, so a copy in the desktop's store stays unusable", () => {+ expect(liveSavePatch(onA, { key: "" })).toEqual(forgotten);+ });++ it("never takes keyFor from a request", () => {+ expect(liveSavePatch(onA, { keyFor: "azure:evil.azure-api.net", voice: "cedar" })).toEqual({ voice: "cedar" });+ expect(liveSavePatch(onA, { keyFor: "azure:b.openai.azure.com", azureEndpoint: B })).toEqual({ azureEndpoint: B, ...forgotten });+ expect(liveSavePatch(onA, { keyFor: "azure:evil.azure-api.net", key: "new" })).toEqual({ key: "new", keyFor: "azure:a.openai.azure.com" });+ });+ });++ describe("from the environment", () => {+ const usable = (live: LiveConfig | undefined, env: NodeJS.ProcessEnv) => usableLiveKey(liveConfigWithEnv(live, env));++ it("is the desktop's copy from its store, usable where it was saved for and nowhere else", () => {+ const env = { OMB_OPENAI_LIVE_KEY: "from-the-store" };+ expect(usable({ ...onA, key: "" }, env)).toBe("from-the-store");+ expect(usable({ ...onA, key: "", azureEndpoint: B }, env)).toBeUndefined();+ expect(usable({ provider: "openai", key: "", keyFor: "nowhere" }, env)).toBeUndefined();+ expect(usable({ provider: "azure", azureEndpoint: A, key: "", keyFor: "nowhere" }, env)).toBeUndefined();+ });++ it("pairs a key and an Azure endpoint set together there, as an operator does", () => {+ const env = { OMB_OPENAI_LIVE_KEY: "operators", OMB_LIVE_PROVIDER: "azure", OMB_AZURE_OPENAI_LIVE_ENDPOINT: A };+ expect(usable(undefined, env)).toBe("operators");+ expect(liveConfigWithEnv(undefined, env).keyFor).toBe("azure:a.openai.azure.com");+ });++ it("cannot be paired by settings saved later: a save mirrors them into the environment", () => {+ // Repoint the endpoint (the key is forgotten), wait for a restart (the desktop's copy returns as OMB_OPENAI_LIVE_KEY),+ // then save the same service and endpoint again, which puts both in the environment beside that copy.+ const evil = "https://evil.azure-api.net";+ const afterMove: LiveConfig = { provider: "azure", azureEndpoint: evil, key: "", keyFor: "nowhere" };+ const mirrored = { OMB_OPENAI_LIVE_KEY: "from-the-store", OMB_LIVE_PROVIDER: "azure", OMB_AZURE_OPENAI_LIVE_ENDPOINT: evil };+ expect(liveSavePatch(liveConfigWithEnv(afterMove, { OMB_OPENAI_LIVE_KEY: "from-the-store" }), { provider: "azure" })).toEqual({ provider: "azure" });+ expect(usable(afterMove, mirrored)).toBeUndefined();+ });++ it("re-pairs an operator's different key with the endpoint set beside it", () => {+ expect(usable(onA, { OMB_OPENAI_LIVE_KEY: "operators", OMB_LIVE_PROVIDER: "azure", OMB_AZURE_OPENAI_LIVE_ENDPOINT: B })).toBe("operators");+ });++ it("does not pair a key there with an endpoint or service only the file names", () => {+ expect(usable({ provider: "azure", azureEndpoint: A }, { OMB_OPENAI_LIVE_KEY: "operators" })).toBeUndefined();+ expect(usable({ azureEndpoint: A }, { OMB_OPENAI_LIVE_KEY: "operators", OMB_LIVE_PROVIDER: "azure" })).toBeUndefined();+ expect(usable({ provider: "azure" }, { OMB_OPENAI_LIVE_KEY: "operators", OMB_AZURE_OPENAI_LIVE_ENDPOINT: A })).toBeUndefined();+ expect(usable(onA, { OMB_LIVE_PROVIDER: "azure", OMB_AZURE_OPENAI_LIVE_ENDPOINT: B })).toBeUndefined();+ });++ it("takes no binding from the file when it is a different key from the one saved there", () => {+ expect(usable(onA, { OMB_OPENAI_LIVE_KEY: "another" })).toBeUndefined();+ expect(usable({ ...onA, provider: "openai", keyFor: "openai" }, { OMB_OPENAI_LIVE_KEY: "another" })).toBe("another");+ expect(usable(onA, { OMB_OPENAI_LIVE_KEY: "k" })).toBe("k");+ });++ it("keeps OpenAI working as it did with only a key set", () => {+ expect(usable(undefined, { OMB_OPENAI_LIVE_KEY: "sk-env" })).toBe("sk-env");+ expect(usable({ voice: "cedar" }, { OMB_OPENAI_LIVE_KEY: "sk-env", OMB_LIVE_PROVIDER: "openai" })).toBe("sk-env");+ });+ });+});diff --git a/server/live-settings.ts b/server/live-settings.tsindex 8de18514ba..a4f29feb4c 100644--- a/server/live-settings.ts+++ b/server/live-settings.ts@@ -1,14 +1,15 @@import type { LiveKeySource, LiveSettings } from "../shared/wire.ts";-import type { AppConfig } from "./config.ts";+import { saveConfig, syncCredentialEnv, type AppConfig } from "./config.ts";import { azureLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.ts";+import { liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";export const LIVE_IDLE_MINUTES_DEFAULT = 5;type LiveConfig = Pick<AppConfig, "live" | "openai">;-/** An Azure resource key is never stood in for by the OpenAI API key, nor the other way round. */+/** A saved Live key goes only to the provider and host it was saved for (`usableLiveKey`), and the OpenAI API key only ever to OpenAI. */export function liveCallKey(cfg: LiveConfig): { key: string; source: LiveKeySource } | null {- const live = cfg.live?.key?.trim();+ const live = usableLiveKey(cfg.live);if (live) return { key: live, source: "live" };if (cfg.live?.provider === "azure") return null;const openai = cfg.openai?.key?.trim();@@ -28,6 +29,13 @@ export function liveSetupProblem(cfg: LiveConfig): string | null {return liveCallEndpoint(cfg) ? null : LIVE_NEEDS_AZURE;}+/** The environment follows the save, as for PUT /api/config: loadConfig prefers it over the file. */+export function saveLiveSettings(cfg: Pick<AppConfig, "live">, patch: LiveConfigSection): void {+ const live = liveSavePatch(cfg.live, patch);+ saveConfig({ live });+ syncCredentialEnv({ live });+}+/** What a call start reads, once: its key, endpoint and provider all come from this one reading. */export function liveCallSettings(cfg: AppConfig) {return { key: liveCallKey(cfg)?.key ?? "", endpoint: liveCallEndpoint(cfg), setupProblem: liveSetupProblem(cfg), ...liveSettingsFor(cfg) };diff --git a/server/routes/config.ts b/server/routes/config.tsindex c14e71de29..52d29725cc 100644--- a/server/routes/config.ts+++ b/server/routes/config.ts@@ -1,3 +1,4 @@+import { liveSavePatch } from "../live-config.ts";import * as boat from "../boat.ts";import { boatCreateRecoverySnapshot, retireDeletedBoatCreate } from "../boat-create-idempotency.ts";import { boatDeletionSnapshot } from "../boat-delete-journal.ts";@@ -513,6 +514,7 @@ export function createConfigRoutes(deps: ConfigRouteDeps): RouteHandler {const enginesBefore = engineLaunches(providerConfigs());const externalSecretStorage = url.searchParams.get("secretStorage") === "external";try {+ if (patch.live) patch.live = liveSavePatch(cfg.live, patch.live);// Before the provider commit, so a failed write never leaves a foreign voice id to speak.if (changingVoiceProvider) store.clearVoiceSelections();if (externalSecretStorage) {diff --git a/src/components/LiveKeyNeeded.test.ts b/src/components/LiveKeyNeeded.test.tsindex 10c73b9af9..14d578484f 100644--- a/src/components/LiveKeyNeeded.test.ts+++ b/src/components/LiveKeyNeeded.test.ts@@ -53,3 +53,10 @@ it("with Azure chosen, asks for the endpoint, deployment and resource key in plaexpect(html).not.toContain("Open API keys");expect(html).not.toContain("OpenAI key stays");});++it("with Azure chosen and no endpoint yet, asks for the endpoint first: a key is tied to it", () => {+ f.live = { configured: false, provider: "azure", voice: "", readTypedReplies: true, idleMinutes: 5 };+ const html = renderToStaticMarkup(createElement(LiveKeyNeeded));+ expect(html).toContain('placeholder="https://my-resource.openai.azure.com"');+ expect(html).not.toContain('aria-label="Azure OpenAI key for Live calls"');+});diff --git a/src/components/LiveKeyNeeded.tsx b/src/components/LiveKeyNeeded.tsxindex e16ff524eb..a6593a1140 100644--- a/src/components/LiveKeyNeeded.tsx+++ b/src/components/LiveKeyNeeded.tsx@@ -14,7 +14,8 @@ export function LiveKeyNeeded() {const titleId = useId();const live = state.config?.live;const azure = live?.provider === "azure";- const keyForm = azure && live?.keySource !== "live";+ // A key is tied to the endpoint it is saved for, so the endpoint comes first.+ const keyForm = azure && Boolean(live?.azureEndpoint) && live?.keySource !== "live";return <section aria-labelledby={titleId} className="flex flex-col gap-2.5 rounded-xl border border-hairline bg-panel p-4 text-left text-[13px]"><div className="flex items-start gap-2.5"><KeyRound size={16} className="mt-0.5 shrink-0 text-ink-secondary" aria-hidden="true" />diff --git a/src/components/keys/KeyRow.tsx b/src/components/keys/KeyRow.tsxindex 14cba1d196..4b3bf17bb0 100644--- a/src/components/keys/KeyRow.tsx+++ b/src/components/keys/KeyRow.tsx@@ -7,7 +7,7 @@ import { t } from "@/lib/i18n";import type { KeyResult, KeyVia } from "@/lib/analytics-allowlist";import { keyRemoved, keySaved, keySaveFailure, savedKeyResult } from "@/lib/product-events";import { InstanceProviderMark } from "../ProviderIcons";-import { keyEntry, keyForInstance, looksLikeOtherKey, savedState, type KeyEntry, type KeyId, type SavedState } from "./key-catalog";+import { keyEntry, keyForInstance, looksLikeOtherKey, savedState, shownKeyEntry, type KeyEntry, type KeyId, type SavedState } from "./key-catalog";import { checkKey, cleanKey, looksLikeKey, saveKey } from "./key-save";export const KEY_FIELD = "h-8 w-full min-w-0 rounded-lg border border-hairline/60 bg-inset px-3 font-mono text-[13px] leading-8 text-ink placeholder:text-ink-tertiary focus:outline-none focus-visible:ring-2 focus-visible:ring-focus/60 disabled:opacity-60";@@ -123,8 +123,8 @@ export function KeyRow({(goal === "input" ? inputRef.current : replaceRef.current)?.focus();});- const entry = keyEntry(id);- const row = rowId ? keyEntry(rowId) : entry;+ const entry = shownKeyEntry(id, state.config);+ const row = rowId ? shownKeyEntry(rowId, state.config) : entry;const target = entry.target;if (!target) throw new Error(`${id} is not saved by a key row`);const pointer = row.id !== entry.id;diff --git a/src/components/keys/KeysPage.dom.test.ts b/src/components/keys/KeysPage.dom.test.tsindex 88defdb030..97b6aa81ef 100644--- a/src/components/keys/KeysPage.dom.test.ts+++ b/src/components/keys/KeysPage.dom.test.ts@@ -102,6 +102,28 @@ describe("the keys page", () => {expect(row("liveKey")!.querySelector('input[type="url"]')).not.toBeNull();});+ it("with Azure chosen, the Live key row asks for an Azure key: required, no OpenAI wording, and no row saying Live uses the OpenAI key", () => {+ const live = { configured: false, voice: "", readTypedReplies: true, idleMinutes: 5 };+ setConfig({ ...fx.config, live: { ...live, provider: "azure", azureEndpoint: "https://my-res.openai.azure.com" } });+ page();+ const azure = row("liveKey")!;+ expect(azure.textContent).toContain("Azure OpenAI key for Live calls");+ expect(azure.textContent).toContain("Required");+ expect(azure.textContent).not.toContain("Optional");+ expect(azure.textContent).not.toContain("Separate key");+ expect(azure.textContent).not.toContain("instead of your OpenAI key");+ expect([...azure.querySelectorAll("input")].map((input) => input.placeholder)).not.toContain("sk-…");+ expect(azure.querySelector<HTMLAnchorElement>('a[href*="platform.openai.com"]')).toBeNull();+ expect(row("liveCalls")).toBeNull();++ setConfig({ ...fx.config, live });+ page();+ const openAi = row("liveKey")!;+ expect(openAi.textContent).toContain("Optional");+ expect([...openAi.querySelectorAll("input")].map((input) => input.placeholder)).toContain("sk-…");+ expect(row("liveCalls")).not.toBeNull();+ });+it("opens a section that holds a saved key, and counts what is connected", () => {setConfig({ ...fx.config, box: { configured: true, last4: "c3d4" } });page();diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsxindex ab09a40a2c..573671c768 100644--- a/src/components/keys/KeysPage.tsx+++ b/src/components/keys/KeysPage.tsx@@ -145,7 +145,9 @@ export function KeysPage() {return () => window.cancelAnimationFrame(frame);}, [focus]);- const rows = KEY_CATALOG.filter((entry) => keyMatches(entry, q));+ // With Azure chosen, Live calls do not use the OpenAI key that row points at.+ const azureLive = state.config?.live?.provider === "azure";+ const rows = KEY_CATALOG.filter((entry) => keyMatches(entry, q) && !(azureLive && entry.id === "liveCalls"));const sections = KEY_SECTIONS.flatMap((section) => {const own = rows.filter((entry) => entry.section === section.id);return own.length > 0 ? [{ id: section.id, rows: own }] : [];diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.tsindex 032b836db1..f275f95ee7 100644--- a/src/components/keys/key-catalog.ts+++ b/src/components/keys/key-catalog.ts@@ -193,6 +193,14 @@ export function keyEntry(id: KeyId): KeyEntry {return entry;}+/** With Azure OpenAI chosen for Live calls, the row for their key is about the Azure resource: required, and no OpenAI key. */+export function shownKeyEntry(id: KeyId, config: ConfigStatus | null | undefined): KeyEntry {+ const entry = keyEntry(id);+ if (id !== "liveKey" || config?.live?.provider !== "azure" || !entry.target) return entry;+ const { shape: _openAiShape, ...target } = entry.target;+ return { ...entry, name: "Azure OpenAI", labelKey: "call.live.azureKeyField", purposeKey: "keys.purpose.liveKeyAzure", target: { ...target, placeholder: "…", href: "https://portal.azure.com" } };+}+export function keySection(entry: KeyEntry) {return KEY_SECTIONS.find((section) => section.id === entry.section)!;}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 57f057476c..3bf3db279c 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6273,7 +6273,7 @@"call.live.provider.azure": "Azure OpenAI","call.live.azureEndpoint": "Azure resource endpoint","call.live.azureDeployment": "GPT-Live deployment name",- "call.live.azureHint": "Deploy gpt-live-1 on your Azure OpenAI or Foundry resource, then paste the resource endpoint and the deployment name. An empty name means gpt-live-1.",+ "call.live.azureHint": "Deploy gpt-live-1 on your Azure OpenAI or Foundry resource, then paste the resource endpoint and the deployment name. An empty name means gpt-live-1. A key works only with the endpoint it was saved for: changing the Service or the endpoint's host asks for the key again.","call.live.azureKey": "Azure key","call.live.azureNeedsKey": "Add the key of your Azure OpenAI resource with Change key.","call.live.azureKeyTitle": "Live calls through Azure OpenAI",@@ -7290,6 +7290,7 @@"keys.purpose.openaiCompat": "Ollama, Together or any server that speaks the OpenAI API","keys.purpose.liveCalls": "Live calls use the same key as OpenAI's models","keys.purpose.liveKey": "Optional. Live calls use it instead of your OpenAI key",+ "keys.purpose.liveKeyAzure": "Required. A key of the Azure resource your Live calls use","keys.purpose.elevenlabs": "Voices for spoken replies and calls","keys.purpose.fishAudio": "Fish Audio voices for spoken replies and calls","keys.purpose.box": "Cloud desktops your bots can use",