Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Live calls: keep Azure calls to admins and single-owner servers
milind-soni4c04a6fa9ccf
diff --git a/apps/docs/content/docs/features/voice-and-memory.mdx b/apps/docs/content/docs/features/voice-and-memory.mdxindex 2d845e245f..c7fcc7e913 100644--- a/apps/docs/content/docs/features/voice-and-memory.mdx+++ b/apps/docs/content/docs/features/voice-and-memory.mdx@@ -72,6 +72,8 @@ Live calls are free for everyone, from the desktop app, a web browser or your ph**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.+**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.+**What a Live call sends to OpenAI.** A Live call sends your voice to OpenAI, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. The OpenAI key stays where you saved it: on your computer, or on My Cloud. The desktop says this where you choose Live and where you set it up; a phone says it once, before its first Live call, with **Start call** and **Cancel**. In detail: the chat's last eight text messages when the call starts (so "and the other one?" makes sense), every answer the bot gives on the call's chat (an answer to typed messages only while **Read replies to typed messages** is on, or when it also answers something you said), what a permission card asks (for example the command it wants to run), question options and proposal titles, the name of the app or credential a card waits for, the names of the bot's steps (never their arguments), and the bot's name, title and description.## Dictationdiff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 368ac5748a..4e806e4426 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -10,7 +10,9 @@ keeps people apart on it. The bot box ([bot-box.md](bot-box.md)) is what makes t- **Signing in.** Each person pairs from the app with a link the Admin signs for them; the machine shows the team's namewherever a server names itself. Owners and Admins get everything an admin session can do (Super admin and Admin in theapp); a Member (User) uses each bot as far as it is shared with them (below, "Who can use a bot"), uses rooms and- makes routines, and connects no app and makes no webhook.+ makes routines, and connects no app and makes no webhook. With Azure OpenAI chosen for Live calls, only an Owner or+ Admin can start one: a Member is told so in plain words and never gets a call through another provider+ (`docs/verification/live-calls.md`).- **Conversations.** A bot's main chat is the team's: everyone who sees the bot reads and writes it. Teammates arein the @ list too, and whatever is addressed to one of them reaches their inbox (below, "One inbox per person"). "New conversation"is yours alone: no other Member and no Admin, the Super admin included, sees it, writes in it or learns of it, indiff --git a/docs/verification/live-calls.md b/docs/verification/live-calls.mdindex d11fcdd7cd..3118af9d49 100644--- a/docs/verification/live-calls.md+++ b/docs/verification/live-calls.md@@ -53,7 +53,6 @@ start answer 409 `needsKey`; after the OpenAI key is saved through`PUT /api/config`, a phone's call starts with that key; a separate Live keythen wins; neither key appears in the config or the log.-## Azure OpenAI as the Live providerWith `live.provider: "azure"` (`OMB_LIVE_PROVIDER=azure`) a call creates its@@ -70,6 +69,37 @@ refuses any other. 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.++Azure refuses `session.client` (`400 Unknown parameter`), so an Azure call goes+without `LIVE_DATA_CHANNEL`: the caller's data channel keeps Azure's default+events instead of "may only hang up". This is read from the code and was not+checked against Azure: assume the caller could send session or item events and+receive events holding the bot's instructions. So an Azure call is limited to+an admin, or the owner of a single-owner server (`azureLiveCallRefusal` in+`server/live-access.ts`, asked by `LiveCallController.start`, the only place a+session is created):++| Caller | Azure call |+| --- | --- |+| Desktop app's window; the owner's phone through the companion | yes |+| Single-owner server: local request, or a paired admin device | yes |+| My Cloud: the owner's session | yes |+| Team Cloud: Super admin, Admin | yes |+| Shared company workspace: admin | yes |+| Self-hosted with a sign-in list: admin session | yes |+| Team Cloud User, on the app or their phone; a workspace non-admin; a chat-only device | no, plain sentence |+| A local request where others use the server (a bot's shell): Team Cloud, shared workspace, sign-in list, a chat-only device or code | no |+| A sign-in that only moves a bot in | no |+| A published or inline page, with or without an admin's cookie | no |++The refused answer is `403 { "error": "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." }`,+with no `needsKey`. Nothing reaches Azure or OpenAI: a refused call never falls+back to another provider. `GET /api/config` and the stream tell a session+without the admin scope `live.provider`, never `azureEndpoint` or+`azureDeployment`. `server/live-access.test.ts` runs each caller above through+the sign-in gate and the limit; `server/live-azure-access.e2e.test.ts` and+`server/hosted-access.test.ts` do it on the full server with its `fetch` stubbed.+## User pathStart a Live call from the call button's menu, say something the bot must actdiff --git a/server/hosted-access.test.ts b/server/hosted-access.test.tsindex e43159eeff..b6c02f5776 100644--- a/server/hosted-access.test.ts+++ b/server/hosted-access.test.ts@@ -179,6 +179,30 @@ describe("hosted bridge in the full server", () => {expect((await call("/api/auth/session", { cookie: memberCookie })).body).toMatchObject({ scopes: ["client"], hosted: true });expect((await call("/api/auth/sessions", { cookie: memberCookie })).status).toBe(403);});+ it("keeps an Azure Live call to a workspace admin, in plain words, and never takes a local request for one", async () => {+ state();+ const botId = await policyBot();+ const admin = await login();+ const start = (options: { cookie?: string; local?: boolean }) => call("/api/live/session", { method: "POST", body: { botId, sdp: "v=0\r\n", client: "web" }, ...options });+ const refusal = "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.";+ expect((await call("/api/live/settings", { method: "PATCH", cookie: admin, body: { provider: "azure", azureEndpoint: "https://fixture.openai.azure.com", azureDeployment: "fixture-dep" } })).status).toBe(200);+ try {+ // No key is saved: past the limit, the call stops at the setup prompt and nothing leaves this machine.+ expect(await start({ cookie: admin })).toMatchObject({ status: 409, body: { needsKey: true } });+ // This fixture runs with OMB_LOOPBACK_TRUST=owner, an operator's override: every bot's shell is a local caller too.+ expect(await start({ local: true })).toMatchObject({ status: 403, body: { error: refusal } });+ state("member");+ const member = await login();+ expect(await start({ cookie: member })).toMatchObject({ status: 403, body: { error: refusal } });+ const seen = (await call("/api/config", { cookie: member })).body.live;+ expect(seen).toMatchObject({ provider: "azure" });+ expect(seen).not.toHaveProperty("azureEndpoint");+ expect(seen).not.toHaveProperty("azureDeployment");+ } finally {+ state();+ expect((await call("/api/live/settings", { method: "PATCH", cookie: await login(), body: { provider: "openai", azureEndpoint: "", azureDeployment: "" } })).status).toBe(200);+ }+ });it("closes an existing quiet event stream within fifteen seconds of remote revocation", async () => {state();const cookie = await login();@@ -367,6 +391,7 @@ describe("hosted bridge in the full server", () => {const botId = created.body.bot.id as string;expect((await call("/api/auth/session", { local: true })).body).toMatchObject({ kind: "loopback", scopes: ["client"], trust: "service" });+ expect(await call("/api/live/session", { method: "POST", local: true, body: { botId, sdp: "v=0\r\n", client: "web" } })).toMatchObject({ status: 403, body: { error: expect.stringContaining("may only use the service routes") } });const health = await call("/api/health", { local: true });expect(health.status).toBe(200);expect(health.body.capabilities).toMatchObject({ guardedMessages: 1, guardedRequests: 1, sharedWorkspaceFullAccess: 1 });diff --git a/server/index.ts b/server/index.tsindex 27d96deac2..6859710f32 100644--- a/server/index.ts+++ b/server/index.ts@@ -311,9 +311,9 @@ import {import * as tts from "./tts/index.ts";import { createDecider, deciderReady, describeDecider } from "./decider/index.ts"; import { createExtractor, describeHelpers } from "./extractor/index.ts";import { decideRoomResponder } from "./decider/room-routing.ts"; import { roomRoutingInput } from "./host/room-routing-input.ts";-import { createLiveSession, liveAttachUrl, liveAuthHeaders, liveHistoryFrom, LiveSessionError, type LiveBot, type LiveHistoryMessage } from "./live-call.ts";-import { LiveCallController, LiveCallSignedOutError, type LiveSocket } from "./live-call-controller.ts";-import { liveCallEndpoint, liveCallKey, liveSettingsFor, liveSetupProblem } from "./live-settings.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 { recordLiveCall, spokenLineFields, titleLiveCall } from "./live-call-record.ts";import { narrateTool, toUtterances } from "./tts/speech-text.ts";import { createTtsRoutes } from "./routes/tts.ts";@@ -11949,7 +11949,7 @@ function configForAccess(status: ReturnType<typeof configStatus>, admin: booleanreturn {...withoutKeyHints(status),edition: { edition: status.edition.edition, features: status.edition.features },- signIn: { admins: [], members: [] },+ signIn: { admins: [], members: [] }, live: liveSettingsForClient(status.live),vps: { configured: status.vps.configured, sshAlias: "" },opencodeGo: { configured: status.opencodeGo.configured, providerKeys: [] },profile: CLOUD_TEAM ? profile : { name: profile.name, email: "", ...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}) },@@ -12627,10 +12627,10 @@ const liveCalls = new LiveCallController({return task.activity === "waiting-on-you" ? "waiting" : "working";},broadcast: (frame) => broadcast(frame, { adminOnly: true }),- settings: () => ({ key: liveCallKey(cfg)?.key ?? "", endpoint: liveCallEndpoint(cfg), setupProblem: liveSetupProblem(cfg), ...liveSettingsFor(cfg) }),+ settings: () => liveCallSettings(cfg),+ azureRefusal: (auth) => azureLiveCallRefusal(auth, { othersOnLoopback: adminActivityRecording() }),createSession: ({ key, endpoint, sdp, botId, threadId, voice }) => createLiveSession({ key, endpoint, sdp, voice, bot: liveBotFor(botId), history: liveHistoryFor(threadId), cloudHome: Boolean(CLOUD_HOME) }),- // Node's WebSocket (undici) accepts headers in its second argument.- openSocket: (url, key, endpoint) => new WebSocket(url, { headers: liveAuthHeaders(endpoint.provider, key) } as unknown as string[]) as unknown as LiveSocket,+ openSocket: openLiveSocket,attachUrl: (sessionId, endpoint) => liveAttachUrl(sessionId, endpoint),speakable: (text) => toUtterances(text),// One "call" row per call: its id, times and length, never anything said on it.@@ -12844,7 +12844,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {companionMutationToken,features: { sharedComputers: lendingEnabled() },loopbackTrust: LOOPBACK.trust,- cliOwnerToken, trustLocalBrowser: LOOPBACK.localBrowsers, ...(CLOUD_TEAM ? { restricted: moveInRefusal } : {}),+ cliOwnerToken, trustLocalBrowser: LOOPBACK.localBrowsers, ...(CLOUD_TEAM ? { restricted: moveInRefusal } : {}), scopeRefusal: (m, p) => liveScopeRefusal(cfg, m, p),});// The session term slides on use, so re-issue the cookie on every cookie request; handlers that clear it later overwrite this header.if (gate.auth?.kind === "session" && gate.auth.via === "cookie") {diff --git a/server/live-access.test.ts b/server/live-access.test.tsnew file mode 100644index 0000000000..88f82613c8--- /dev/null+++ b/server/live-access.test.ts@@ -0,0 +1,178 @@+// Every way a call start reaches the server, through the sign-in gate and then the Azure limit, as the server runs them.+import { mkdtempSync, rmSync } from "node:fs";+import type { IncomingMessage } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { teamRoleScopes, type TeamRole } from "./cloud-team.ts";+import { azureLiveCallRefusal, LIVE_AZURE_REFUSAL, liveScopeRefusal } from "./live-access.ts";+import { requiredScope, resolveRequestAuth, type RequestAuth, type ResolveOptions } from "./request-auth.ts";+import { SessionRegistry, type Scope, type SessionRecord } from "./sessions.ts";+import { moveInRefusal } from "./team-move-in.ts";++const LIVE = "/api/live/session";+const COOKIE = "omb_session_test";+const REMOTE = { host: "bots.example.com", "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https" };+const LOCAL = { host: "127.0.0.1:8799" };+const DESKTOP = { loopbackMutationToken: "desktop-secret", companionMutationToken: "relay-secret" };++let dir: string, sessions: SessionRegistry;+beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "omb-live-access-"));+ sessions = new SessionRegistry({ file: join(dir, "sessions.json") });+});+afterEach(() => {+ sessions.close();+ rmSync(dir, { recursive: true, force: true });+});++interface Place { resolve?: Partial<ResolveOptions>; othersOnLoopback?: boolean; provider?: "azure" | "openai" }++/** "gets a call", or the words the person reads and who said them. */+function verdict(headers: Record<string, string>, place: Place = {}): string {+ const { auth, status, error } = resolveRequestAuth({ headers, method: "POST" } as unknown as IncomingMessage, {+ sessions, cookieName: COOKIE, streamPath: "/api/events", url: new URL(LIVE, "http://x"),+ scopeRefusal: (method, path) => liveScopeRefusal({ live: { provider: place.provider ?? "azure" } }, method, path),+ ...place.resolve,+ });+ if (!auth) return `sign-in gate ${status}: ${error}`;+ const refusal = azureLiveCallRefusal(auth, { othersOnLoopback: place.othersOnLoopback ?? false });+ return refusal ? `limit: ${refusal}` : "gets a call";+}++const bearer = (token: string) => ({ ...REMOTE, authorization: `Bearer ${token}` });+const device = (scopes: Scope[]) => bearer(sessions.issue({ label: "Device", scopes }).token);+function teamMember(role: TeamRole, phone = false) {+ const email = `${role}@acme.test`;+ const opened = sessions.openPairing({ scopes: teamRoleScopes(role), label: phone ? "Phone" : "App", member: { email, role }, ...(phone ? { memberCheckedAt: Date.now() } : {}) });+ const paired = sessions.exchange({ code: opened.code, label: "Device", source: "203.0.113.9" });+ if (!paired.ok) throw new Error(paired.error);+ return bearer(paired.token);+}+const portal = (scopes: Scope[]) => bearer(sessions.issuePortal({ email: "[email protected]", grant: "g".repeat(43), scopes }).token);+const SERVICE = { resolve: { loopbackTrust: "service" as const } };+const CALL = "gets a call";+const AT_LIMIT = `limit: ${LIVE_AZURE_REFUSAL}`;+const AT_SIGN_IN = `sign-in gate 403: ${LIVE_AZURE_REFUSAL}`;++describe("an Azure Live call", () => {+ describe("in the desktop app", () => {+ const place = { resolve: DESKTOP };+ it("goes to the app's own window", () => {+ expect(verdict({ ...LOCAL, "x-openmausbot-desktop-owner": "desktop-secret" }, place)).toBe(CALL);+ });+ it("goes to the owner's phone, through the companion that authenticated it", () => {+ expect(verdict({ ...LOCAL, "x-openmausbot-companion": "1", "x-openmausbot-companion-device": "phone-1", "x-openmausbot-companion-auth": "relay-secret" }, place)).toBe(CALL);+ });+ it("is refused to a bot's shell and to a forged companion", () => {+ expect(verdict(LOCAL, place)).toMatch(/^sign-in gate 403: forbidden: this change must come from the desktop app/);+ expect(verdict({ ...LOCAL, "x-openmausbot-companion": "1", "x-openmausbot-companion-device": "phone-1", "x-openmausbot-companion-auth": "guessed" }, place)).toMatch(/^sign-in gate 403: forbidden: invalid companion/);+ });+ it("is refused to a remote device paired chat-only", () => {+ expect(verdict(device(["client"]), place)).toBe(AT_SIGN_IN);+ });+ });++ describe("on a server one person uses", () => {+ it("goes to the owner, locally or on a paired device", () => {+ expect(verdict(LOCAL)).toBe(CALL);+ expect(verdict(device(["admin", "client"]))).toBe(CALL);+ });+ });++ describe("on a self-hosted server others use too", () => {+ const place = { othersOnLoopback: true };+ it("goes to an admin's session", () => {+ expect(verdict(device(["admin", "client"]), place)).toBe(CALL);+ });+ it("is refused to a chat-only person, and to a local request, which may be any bot's shell", () => {+ expect(verdict(device(["client"]), place)).toBe(AT_SIGN_IN);+ expect(verdict(LOCAL, place)).toBe(AT_LIMIT);+ });+ });++ describe("on a person's own Cloud", () => {+ it("goes to the owner's session, and is refused to a bot's shell", () => {+ expect(verdict(device(["admin", "client"]), { ...SERVICE, othersOnLoopback: true })).toBe(CALL);+ expect(verdict(LOCAL, SERVICE)).toMatch(/^sign-in gate 403: forbidden: on this shared server/);+ });+ });++ describe("on a Team Cloud", () => {+ const place = { ...SERVICE, othersOnLoopback: true };+ it("goes to a Super admin and an Admin", () => {+ expect(verdict(teamMember("owner"), place)).toBe(CALL);+ expect(verdict(teamMember("admin"), place)).toBe(CALL);+ });+ it("is refused in plain words to a User, on the app or their phone", () => {+ expect(verdict(teamMember("member"), place)).toBe(AT_SIGN_IN);+ expect(verdict(teamMember("member", true), place)).toBe(AT_SIGN_IN);+ });+ it("is refused to a sign-in that only moves a bot in, whoever's it is", () => {+ const moving = bearer(sessions.issueMoveIn({ label: "Move in", email: "[email protected]", teamRole: "admin", bot: "bot1" }).token);+ expect(verdict(moving, { ...place, resolve: { ...SERVICE.resolve, restricted: moveInRefusal } })).toBe("sign-in gate 403: This sign-in only moves one bot in.");+ expect(verdict(moving, place)).toBe(AT_LIMIT);+ });+ it("is refused to a bot's shell", () => {+ expect(verdict(LOCAL, place)).toMatch(/^sign-in gate 403: forbidden: on this shared server/);+ });+ });++ describe("on a shared company workspace", () => {+ const place = { ...SERVICE, othersOnLoopback: true };+ beforeEach(() => {+ sessions.close();+ sessions = new SessionRegistry({ file: join(dir, "portal-sessions.json"), portalMembership: true });+ });+ it("goes to a workspace admin", () => {+ expect(verdict(portal(["admin", "client"]), place)).toBe(CALL);+ });+ it("is refused to anyone else, and to a local request even where an operator made loopback the owner", () => {+ expect(verdict(portal(["client"]), place)).toBe(AT_SIGN_IN);+ expect(verdict(LOCAL, place)).toMatch(/^sign-in gate 403: forbidden: on this shared server/);+ expect(verdict(LOCAL, { othersOnLoopback: true, resolve: { loopbackTrust: "owner" } })).toBe(AT_LIMIT);+ });+ });++ describe("from a published or shared page", () => {+ // A published page lives on another origin, and an inline one is sandboxed (`Origin: null`).+ const riding = (origin: string) => {+ const token = sessions.issue({ label: "Admin", scopes: ["admin", "client"] }).token;+ return { ...REMOTE, cookie: `${COOKIE}=${token}`, origin };+ };+ it("is refused, though the browser holds an admin's cookie", () => {+ expect(verdict(riding("https://abc.example.page"))).toBe("sign-in gate 403: forbidden: cross-origin request");+ expect(verdict(riding("null"))).toBe("sign-in gate 403: forbidden: cross-origin request");+ });+ it("is refused with no credential at all", () => {+ expect(verdict({ ...REMOTE, origin: "https://abc.example.page" })).toMatch(/^sign-in gate 403: forbidden: this request came through a proxy/);+ });+ });++ it("is refused to a caller the rule does not recognise", () => {+ const unknown = { kind: "something-new", scopes: ["admin", "client"] } as unknown as RequestAuth;+ expect(azureLiveCallRefusal(unknown, { othersOnLoopback: false })).toBe(LIVE_AZURE_REFUSAL);+ });++ it("is refused to a session marked a team User even if its scopes say admin", () => {+ const session = { id: "s", teamRole: "member", scopes: ["admin", "client"] } as unknown as SessionRecord;+ const auth: RequestAuth = { kind: "session", session, via: "bearer", scopes: session.scopes };+ expect(azureLiveCallRefusal(auth, { othersOnLoopback: false })).toBe(LIVE_AZURE_REFUSAL);+ });+});++describe("the words for a session without the admin scope", () => {+ it("name Azure only for a call start, and only with Azure chosen", () => {+ expect(verdict(device(["client"]), { provider: "openai" })).toBe("sign-in gate 403: forbidden: this session lacks the admin scope");+ expect(liveScopeRefusal({ live: { provider: "azure" } }, "post", LIVE)).toBe(LIVE_AZURE_REFUSAL);+ expect(liveScopeRefusal({ live: { provider: "azure" } }, "GET", "/api/live/call")).toBeNull();+ expect(liveScopeRefusal({ live: { provider: "azure" } }, "PATCH", "/api/live/settings")).toBeNull();+ expect(liveScopeRefusal({}, "POST", LIVE)).toBeNull();+ });+ it("change no one's scope: every Live route stays closed to a client session", () => {+ for (const [method, path] of [["POST", LIVE], ["POST", "/api/live/call/end"], ["GET", "/api/live/call"], ["PATCH", "/api/live/settings"], ["POST", "/api/live/device-revoked"]] as const) {+ expect(requiredScope(method, path), `${method} ${path}`).toBe("admin");+ }+ });+});diff --git a/server/live-access.ts b/server/live-access.tsnew file mode 100644index 0000000000..75cfb8c1f4--- /dev/null+++ b/server/live-access.ts@@ -0,0 +1,25 @@+// Who may hold a Live call through Azure OpenAI. LIVE_DATA_CHANNEL in live-call.ts says why it is limited.+import type { AppConfig } from "./config.ts";+import type { RequestAuth } from "./request-auth.ts";++export const LIVE_AZURE_REFUSAL = "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.";++export interface LiveCallPlace {+ /** A local request may not be the owner, because other people use this server and every bot's shell is a local caller+ * too: a Team Cloud, a shared workspace, a sign-in list that lets others in, or a chat-only device. False in the desktop+ * app, where a local change needs the app's private token, and on a server one person uses. */+ othersOnLoopback: boolean;+}++/** Null only for an admin or the single owner. A caller this does not recognise is refused. */+export function azureLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace): string | null {+ if (!auth.scopes.includes("admin")) return LIVE_AZURE_REFUSAL;+ if (auth.kind === "session") return auth.session.teamRole === "member" || auth.session.moveIn ? LIVE_AZURE_REFUSAL : null;+ if (auth.kind === "loopback") return auth.trust === "service" || place.othersOnLoopback ? LIVE_AZURE_REFUSAL : null;+ return LIVE_AZURE_REFUSAL;+}++/** The words for a session without the admin scope, which never reaches a Live route. Only the words: the request is refused either way. */+export function liveScopeRefusal(cfg: Pick<AppConfig, "live">, method: string, path: string): string | null {+ return cfg.live?.provider === "azure" && method.toUpperCase() === "POST" && path === "/api/live/session" ? LIVE_AZURE_REFUSAL : null;+}diff --git a/server/live-azure-access.e2e.test.ts b/server/live-azure-access.e2e.test.tsnew file mode 100644index 0000000000..38527877a1--- /dev/null+++ b/server/live-azure-access.e2e.test.ts@@ -0,0 +1,184 @@+// The full server in each place a Live call starts from, with Azure chosen: who gets through to Azure, who is refused and+// what they read. A disposable home and a made-up key. The server's fetch is a stub that notes where it would have gone,+// so nothing leaves this machine, and a caller who gets through ends at the stub's 503. A shared company workspace has its+// own case in hosted-access.test.ts.+import { randomBytes } from "node:crypto";+import { spawn, type ChildProcess } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+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 { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { freePortBlock } from "./testing/ports.ts";++const SERVER_DIR = dirname(fileURLToPath(import.meta.url));+const FAKE_CLAUDE = join(SERVER_DIR, "testing", "fake-claude-cli.ts");+const HOST = "omb-t-0123456789ab.fly.dev";+const REMOTE = { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https" };+const ENDPOINT = "https://fixture.openai.azure.com";+const SESSIONS = `${ENDPOINT}/openai/v1/live/sessions`;+const TEAM = { id: "team-7f3a", name: "Acme" };+const secret = randomBytes(32).toString("base64url");+const REFUSED = { status: 403, body: { error: LIVE_AZURE_REFUSAL } };+const THROUGH = { status: 502, body: { error: "Azure OpenAI had a problem starting the call. Try again in a moment." } };++type Headers = Record<string, string>;+let stopping: Array<() => Promise<void>> = [];+afterEach(async () => {+ await Promise.all(stopping.map((stop) => stop()));+ stopping = [];+});++async function boot(env: NodeJS.ProcessEnv, config: Record<string, unknown> = {}) {+ chmodSync(FAKE_CLAUDE, 0o755);+ const home = mkdtempSync(join(tmpdir(), "omb-live-azure-"));+ const dataDir = join(home, ".openmausbot");+ const fetches = join(home, "fetches.log");+ mkdirSync(dataDir, { recursive: true });+ mkdirSync(join(home, "web"));+ writeFileSync(join(home, "web", "index.html"), "<!doctype html><title>OpenMausBot</title>");+ writeFileSync(join(dataDir, "config.json"), JSON.stringify({+ instances: {+ ...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" },+ // 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 child: ChildProcess = spawn(process.execPath, ["--import", prelude, join(SERVER_DIR, "index.ts")], {+ cwd: join(SERVER_DIR, ".."),+ env: {+ PATH: process.env.PATH, ...(process.env.PATHEXT ? { PATHEXT: process.env.PATHEXT } : {}), ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),+ HOME: home, USERPROFILE: home, OMB_DATA_DIR: dataDir, OMB_PORT: String(port), OMB_WEBHOOK_PORT: String(port + 1), OMB_STATIC_DIR: join(home, "web"),+ ...env,+ },+ stdio: ["ignore", "pipe", "pipe"],+ });+ let log = "";+ child.stdout?.on("data", (chunk) => { log += chunk; });+ child.stderr?.on("data", (chunk) => { log += chunk; });+ stopping.push(async () => {+ await waitForExit(child, { signal: "SIGTERM" });+ await removeTempDir(home);+ });+ const deadline = Date.now() + 45_000;+ for (;;) {+ if (child.exitCode !== null) throw new Error(`the server exited:\n${log}`);+ try { if ((await fetch(`${base}/api/health`)).ok) break; } catch {}+ if (Date.now() > deadline) throw new Error(`the server did not start:\n${log}`);+ await new Promise((resolve) => setTimeout(resolve, 100));+ }+ const call = async (method: string, path: string, body?: unknown, headers: Headers = {}) => {+ const response = await fetch(`${base}${path}`, { method, headers: { ...(body === undefined ? {} : { "content-type": "application/json" }), ...headers }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ };+ /** A session from a pairing code, as a remote device redeems one. */+ const redeem = async (code: string): Promise<Headers> => {+ const paired = await call("POST", "/api/auth/pair", { code, label: "Fixture device" }, REMOTE);+ expect(paired.status, JSON.stringify(paired.body)).toBe(200);+ return { ...REMOTE, authorization: `Bearer ${paired.body.token as string}` };+ };+ /** A pairing the Admin signs, for a Cloud's owner or a team's member. */+ const signedSession = async (claim: Record<string, unknown> = {}): Promise<Headers> => {+ const body = JSON.stringify({ label: "OpenMausBot app (Cloud)", ttlSeconds: 300, ...claim });+ const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url");+ const response = await fetch(`${base}/api/cloud/pairing`, { method: "POST", headers: {+ ...REMOTE, "content-type": "application/json", "x-omb-cloud-timestamp": timestamp, "x-omb-cloud-nonce": nonce, "x-omb-cloud-signature": `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}`,+ }, body });+ const granted = await response.json() as { code: string };+ return redeem(granted.code);+ };+ const newBot = async (headers: Headers = {}) => {+ const created = await call("POST", "/api/bots", { name: "Ada", modelSelection: { instanceId: "claude", model: "claude-fake" } }, headers);+ 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"));+ 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 };+}++const CLOUD_ENV = {+ OMB_CLOUD_MACHINE_ID: "3f9c2a4e-8b1d-4c6e-9a7f-2d5e8c1b0a93", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test",+ OMB_CLOUD_BOOTSTRAP_SECRET: secret, OMB_PUBLIC_URL: `https://${HOST}`,+};++it("on a self-hosted server: the owner and their devices get through; a chat-only device is refused, and from then on a local request is not taken for the owner", async () => {+ const s = await boot({});+ const botId = await s.newBot();+ expect(await s.start(botId)).toEqual(THROUGH);+ const admin = await s.redeem((await s.call("POST", "/api/auth/pairing", { scopes: ["admin", "client"] })).body.code);+ expect(await s.start(botId, admin)).toEqual(THROUGH);+ expect(s.liveSessions()).toEqual([SESSIONS, SESSIONS]);++ const chatOnly = await s.redeem((await s.call("POST", "/api/auth/pairing", { scopes: ["client"] })).body.code);+ expect(await s.start(botId, chatOnly)).toEqual(REFUSED);+ expect(await s.start(botId)).toEqual(REFUSED);+ expect(s.liveSessions()).toHaveLength(2);+ expect(await s.start(botId, admin)).toEqual(THROUGH);++ const seen = (await s.call("GET", "/api/config", undefined, chatOnly)).body.live;+ expect(seen).toMatchObject({ provider: "azure", configured: true });+ expect(seen).not.toHaveProperty("azureEndpoint");+ expect(seen).not.toHaveProperty("azureDeployment");+ expect((await s.call("GET", "/api/config", undefined, admin)).body.live).toMatchObject({ azureEndpoint: ENDPOINT, azureDeployment: "fixture-dep" });++ // With OpenAI chosen nothing here changes: the chat-only device hears the bare scope refusal it always did.+ expect((await s.call("PATCH", "/api/live/settings", { provider: "openai" }, admin)).status).toBe(200);+ expect(await s.start(botId, chatOnly)).toEqual({ status: 403, body: { error: "forbidden: this session lacks the admin scope" } });+}, 90_000);++it("on a self-hosted server with a sign-in list: an admin's session gets through, a local request does not", async () => {+ const s = await boot({}, { signIn: { admins: ["[email protected]"], members: ["[email protected]"] } });+ const botId = await s.newBot();+ expect(await s.start(botId)).toEqual(REFUSED);+ expect(s.liveSessions()).toEqual([]);+ const admin = await s.redeem((await s.call("POST", "/api/auth/pairing", { scopes: ["admin", "client"] })).body.code);+ expect(await s.start(botId, admin)).toEqual(THROUGH);+}, 90_000);++it("on a person's own Cloud: their session gets through, a bot's shell does not", async () => {+ const s = await boot({ OMB_CLOUD_ROLE: "home", ...CLOUD_ENV });+ const owner = await s.signedSession();+ const botId = await s.newBot(owner);+ expect(await s.start(botId, owner)).toEqual(THROUGH);+ expect(s.liveSessions()).toEqual([SESSIONS]);+ expect(await s.start(botId)).toMatchObject({ status: 403, body: { error: expect.stringContaining("may only use the service routes") } });+ expect(s.liveSessions()).toHaveLength(1);+}, 90_000);++it("on a Team Cloud: a Super admin and an Admin get through; a User is refused in plain words, on the app or their phone, and a bot's shell does not get through", async () => {+ const s = await boot({ OMB_CLOUD_ROLE: "team", OMB_CLOUD_TEAM_ID: TEAM.id, OMB_CLOUD_TEAM_NAME: TEAM.name, ...CLOUD_ENV });+ const session = (email: string, role: string) => s.signedSession({ team: TEAM, member: { email, role } });+ const owner = await session("[email protected]", "owner");+ const admin = await session("[email protected]", "admin");+ const member = await session("[email protected]", "member");+ const botId = await s.newBot(owner);++ expect(await s.start(botId, owner)).toEqual(THROUGH);+ expect(await s.start(botId, admin)).toEqual(THROUGH);+ expect(s.liveSessions()).toEqual([SESSIONS, SESSIONS]);++ expect(await s.start(botId, member)).toEqual(REFUSED);+ const made = await s.call("POST", "/api/team/phone-pairing", {}, member);+ expect(made.status, JSON.stringify(made.body)).toBe(200);+ const phone = await s.redeem(made.body.code);+ expect(await s.start(botId, phone)).toEqual(REFUSED);+ // The companion's header carries no authority.+ expect(await s.start(botId, { ...member, "x-openmausbot-companion": "1", "x-openmausbot-companion-device": "phone-1" })).toEqual(REFUSED);+ expect(await s.start(botId)).toMatchObject({ status: 403, body: { error: expect.stringContaining("may only use the service routes") } });+ expect(s.liveSessions()).toHaveLength(2);++ const seen = (await s.call("GET", "/api/config", undefined, member)).body.live;+ expect(seen).toMatchObject({ provider: "azure" });+ expect(seen).not.toHaveProperty("azureEndpoint");+ expect(seen).not.toHaveProperty("azureDeployment");+}, 90_000);diff --git a/server/live-call-controller.test.ts b/server/live-call-controller.test.tsindex 4d9237da84..f95981d48e 100644--- a/server/live-call-controller.test.ts+++ b/server/live-call-controller.test.ts@@ -49,6 +49,7 @@ function setup(overrides: Partial<LiveCallDeps> = {}) {activity: () => activity,broadcast: (frame) => frames.push(frame.call),settings: () => settings,+ azureRefusal: vi.fn(() => null),createSession: vi.fn(async () => ({ sessionId: "sess_1", sdp: "answer-sdp" })),openSocket: (url, key) => { const socket = new FakeSocket(url, key); sockets.push(socket); return socket; },attachUrl: (id) => `ws://fake/${id}/attach`,@@ -110,6 +111,7 @@ describe("LiveCallController lifecycle", () => {it("refuses an Azure call whose setup is incomplete with the setup message, before reaching Azure", async () => {const t = setup();t.settings.endpoint = null;+ t.settings.provider = "azure";t.settings.setupProblem = LIVE_NEEDS_AZURE;await expect(t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" })).rejects.toMatchObject({ status: 409, message: LIVE_NEEDS_AZURE });expect(t.deps.createSession).not.toHaveBeenCalled();@@ -131,6 +133,67 @@ describe("LiveCallController lifecycle", () => {expect(t.controller.current()).toMatchObject({ status: "live" });});+ describe("with Azure chosen", () => {+ const AZURE: LiveEndpoint = { provider: "azure", apiBase: "https://res.openai.azure.com/openai/v1", model: "live-dep" };+ const REFUSED = "only an admin, in these words";+ const member: RequestAuth = { kind: "loopback", scopes: ["client"], trust: "service" };+ const azure = (overrides: Partial<LiveCallDeps> = {}) => {+ const t = setup(overrides);+ t.settings.endpoint = AZURE;+ t.settings.provider = "azure";+ return t;+ };++ it("asks who is calling, with their own sign-in, and goes ahead when they may", async () => {+ const t = azure();+ await t.controller.start({ auth: owner, ...BOT, client: "web", sdp: "a" });+ expect(t.deps.azureRefusal).toHaveBeenCalledWith(owner);+ expect(t.deps.createSession).toHaveBeenCalledOnce();+ });++ it("refuses with the reason as a 403, never a setup prompt, before any session, socket or line is taken", async () => {+ const t = azure({ azureRefusal: () => REFUSED });+ await expect(t.controller.start({ auth: member, ...BOT, client: "ios", sdp: "a" })).rejects.toMatchObject({ status: 403, message: REFUSED });+ expect(t.deps.createSession).not.toHaveBeenCalled();+ expect(t.sockets).toHaveLength(0);+ expect(t.frames).toEqual([]);+ expect(t.controller.current()).toBeNull();+ expect(t.logs.join("\n")).toContain("[live] call refused bot=bot1 client=ios provider=azure");+ });++ it("refuses a person who may not call even while Azure is not set up yet, rather than sending them to set it up", async () => {+ const t = azure({ azureRefusal: () => REFUSED });+ t.settings.endpoint = null;+ t.settings.key = "";+ t.settings.setupProblem = LIVE_NEEDS_AZURE;+ await expect(t.controller.start({ auth: member, ...BOT, client: "web", sdp: "a" })).rejects.toMatchObject({ status: 403, message: REFUSED });+ });++ it("asks too when only the endpoint says Azure, so no reading of the settings slips past it", async () => {+ const t = azure({ azureRefusal: () => REFUSED });+ delete t.settings.provider;+ await expect(t.controller.start({ auth: member, ...BOT, client: "web", sdp: "a" })).rejects.toMatchObject({ status: 403 });+ expect(t.deps.createSession).not.toHaveBeenCalled();+ });++ it("tells a refused caller nothing about a call already running", async () => {+ const refusals: Array<string | null> = [null, REFUSED];+ const t = azure({ azureRefusal: () => refusals.shift() ?? REFUSED });+ await t.start();+ const second = t.controller.start({ auth: member, ...BOT, client: "web", sdp: "a" });+ await expect(second).rejects.toMatchObject({ status: 403, message: REFUSED });+ await expect(second).rejects.not.toBeInstanceOf(LiveCallBusyError);+ });++ });++ it("asks nothing of the Azure limit for a call through OpenAI", async () => {+ const t = setup({ azureRefusal: vi.fn(() => "never asked") });+ await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });+ expect(t.deps.azureRefusal).not.toHaveBeenCalled();+ expect(t.deps.createSession).toHaveBeenCalledOnce();+ });+it("starts a phone's call with no plan at all once a key exists, through the companion or by the phone's own client", async () => {for (const input of [{ client: "ios", device: "phone-1" }, { client: "android", device: "phone-2" }, { client: "ios" }, { client: "android" }] as const) {const t = setup();diff --git a/server/live-call-controller.ts b/server/live-call-controller.tsindex 602dd8f53b..c128d83fe1 100644--- a/server/live-call-controller.ts+++ b/server/live-call-controller.ts@@ -6,8 +6,8 @@ import {} from "../shared/live-approval.ts";import { clampAppend, commentaryChunks, LiveTranscript } from "../shared/live-call.ts";import { signInWaits } from "../shared/sign-in-request.ts";-import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason } from "../shared/wire.ts";-import { LIVE_NEEDS_KEY, liveCallSummaryLine, liveProviderName, LiveSessionError, liveVoice, type LiveEndpoint } from "./live-call.ts";+import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason, LiveProvider } from "../shared/wire.ts";+import { LIVE_NEEDS_KEY, liveAuthHeaders, liveCallSummaryLine, liveProviderName, LiveSessionError, liveVoice, type LiveEndpoint } from "./live-call.ts";import type { RequestAuth } from "./request-auth.ts";import type { Message, StoreChange } from "./store.ts";@@ -48,7 +48,9 @@ export interface LiveCallDeps {activity(botId: string, threadId: string): LiveActivity;broadcast(frame: { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }): void;/** `endpoint` null, or a `setupProblem`, refuses the call with that message (409). */- settings(): { key: string; endpoint: LiveEndpoint | null; setupProblem?: string | null; voice: string; readTypedReplies: boolean; idleMinutes: number };+ settings(): { key: string; endpoint: LiveEndpoint | null; setupProblem?: string | null; provider?: LiveProvider; voice: string; readTypedReplies: boolean; idleMinutes: number };+ /** Why this caller may not hold a call through Azure OpenAI; null when they may. Required, so no wiring can leave it out. */+ azureRefusal(auth: RequestAuth): string | null;createSession(input: { key: string; endpoint: LiveEndpoint; sdp: string; botId: string; threadId: string; voice: string }): Promise<{ sessionId: string; sdp: string }>;openSocket(url: string, key: string, endpoint: LiveEndpoint): LiveSocket;attachUrl(sessionId: string, endpoint: LiveEndpoint): string;@@ -72,6 +74,10 @@ export class LiveCallSignedOutError extends LiveSessionError {}}+// Node's WebSocket (undici) accepts headers in its second argument.+export const openLiveSocket: LiveCallDeps["openSocket"] = (url, key, endpoint) =>+ new WebSocket(url, { headers: liveAuthHeaders(endpoint.provider, key) } as unknown as string[]) as unknown as LiveSocket;+type AppendKind = "instructions" | "thinking" | "commentary";type Timer = ReturnType<typeof setTimeout>;@@ -147,9 +153,17 @@ export class LiveCallController {}async start(input: { auth: RequestAuth; device?: string; botId: string; botName: string; threadId: string; client: LiveClient; sdp: string }): Promise<{ call: LiveCallState; sdp: string }> {+ const settings = this.deps.settings();+ // First: someone refused here is not told about a running call, or sent to set Azure up.+ if (settings.provider === "azure" || settings.endpoint?.provider === "azure") {+ const refusal = this.deps.azureRefusal(input.auth);+ if (refusal) {+ this.deps.log(`[live] call refused bot=${input.botId} client=${input.client} provider=azure`);+ throw new LiveSessionError(refusal, 403);+ }+ }if (this.call && this.call.state.status !== "ended") throw new LiveCallBusyError({ ...this.call.state });if (input.device && this.revokedDevices.has(input.device)) throw new LiveCallSignedOutError();- const settings = this.deps.settings();const key = settings.key.trim();const endpoint = settings.endpoint;if (settings.setupProblem || !key || !endpoint) throw new LiveSessionError(settings.setupProblem || LIVE_NEEDS_KEY, 409);diff --git a/server/live-call.ts b/server/live-call.tsindex 14f51784f2..f38c47cc0c 100644--- a/server/live-call.ts+++ b/server/live-call.ts@@ -10,7 +10,12 @@ export const MAX_SDP_BYTES = 64 * 1024;export const LIVE_NEEDS_KEY = "Live calls use your own OpenAI key. Add it in Settings → API keys.";export const LIVE_NEEDS_AZURE = "Live calls through Azure OpenAI need the resource endpoint, the GPT-Live deployment name and its key. Add them in Call settings.";-/** The client's data channel is untrusted: it may only hang up; every append goes over the sideband. */+/** The client's data channel is untrusted: it may only hang up; every append goes over the sideband.+ * Exception: Azure OpenAI refuses `session.client`, so an Azure call goes without this list and its caller's channel keeps+ * Azure's default events. Read that as: the caller may send session or item events and receive events holding the bot's+ * instructions (not checked against Azure itself). So an Azure call is only for an admin or the owner of a single-owner+ * server, never another team Member, a shared workspace's non-admin or anyone else: azureLiveCallRefusal in live-access.ts,+ * asked by LiveCallController.start. */export const LIVE_DATA_CHANNEL = {allowed_client_events: ["session.close"],allowed_server_events: [@@ -215,7 +220,7 @@ export async function createLiveSession(input: CreateLiveSessionInput): Promise<instructions: liveInstructions(input.bot, { cloudHome: input.cloudHome }),delegation: { type: "client" },audio: { output: { voice: liveVoice(input.voice) } },- // Azure's GPT-Live refuses `session.client` ("Unknown parameter"), so its data channel keeps Azure's default events.+ // Azure's GPT-Live refuses `session.client` ("Unknown parameter"): see LIVE_DATA_CHANNEL for who may hold such a call....(endpoint.provider === "azure" ? {} : { client: { data_channel: LIVE_DATA_CHANNEL } }),...(initialInput.length ? { input: initialInput } : {}),},diff --git a/server/live-settings.test.ts b/server/live-settings.test.tsindex d184945752..5fc8bc652f 100644--- a/server/live-settings.test.ts+++ b/server/live-settings.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import type { AppConfig } from "./config.ts";import { LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY } from "./live-call.ts";-import { LIVE_IDLE_MINUTES_DEFAULT, liveCallEndpoint, liveCallKey, liveSettingsFor, liveSetupProblem } from "./live-settings.ts";+import { LIVE_IDLE_MINUTES_DEFAULT, liveCallEndpoint, liveCallKey, liveCallSettings, liveSettingsFor, liveSettingsForClient, liveSetupProblem } from "./live-settings.ts";describe("live settings", () => {it("defaults to a 5 minute idle hang-up and reading typed replies, with no key", () => {@@ -66,6 +66,19 @@ describe("Live calls through Azure OpenAI", () => {expect(liveSettingsFor(cfg).configured).toBe(false);});+ 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({ 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));+ 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");+ });+it("default to gpt-live-1 as the deployment name", () => {expect(liveCallEndpoint({ live: { ...azure, azureDeployment: "" } } as AppConfig)?.model).toBe("gpt-live-1");});diff --git a/server/live-settings.ts b/server/live-settings.tsindex c452a4e432..8de18514ba 100644--- a/server/live-settings.ts+++ b/server/live-settings.ts@@ -28,6 +28,16 @@ export function liveSetupProblem(cfg: LiveConfig): string | null {return liveCallEndpoint(cfg) ? null : LIVE_NEEDS_AZURE;}+/** 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) };+}++/** A caller without the admin scope learns which service calls use, not which Azure resource. */+export function liveSettingsForClient({ azureEndpoint: _endpoint, azureDeployment: _deployment, ...settings }: LiveSettings): LiveSettings {+ return settings;+}+export function liveSettingsFor(cfg: AppConfig): LiveSettings {const minutes = cfg.live?.idleMinutes;const key = liveCallKey(cfg);diff --git a/server/request-auth.ts b/server/request-auth.tsindex 19873bf8b0..53923b60a6 100644--- a/server/request-auth.ts+++ b/server/request-auth.ts@@ -509,6 +509,8 @@ export interface ResolveOptions {trustLocalBrowser?: boolean;/** Why a session made for one task may not make this request (a Team Cloud's sign-in that moves one bot in), else null. */restricted?(session: SessionRecord, method: string, path: string, url: URL): string | null;+ /** The sentence a person reads when their session lacks the scope for this request; null keeps the bare refusal. */+ scopeRefusal?(method: string, path: string): string | null;}const CLI_OWNER_HEADER = "x-openmausbot-cli-owner";@@ -580,7 +582,7 @@ export function resolveRequestAuth(req: IncomingMessage, options: ResolveOptionsif (narrowed) return deny(403, narrowed);const needed = requiredScope(method, path, options.features ?? {});if (!session.scopes.includes(needed)) {- return deny(403, `forbidden: this session lacks the ${needed} scope`);+ return deny(403, options.scopeRefusal?.(method, path) ?? `forbidden: this session lacks the ${needed} scope`);}// Redeeming a stream ticket does not renew: an unattended open stream must not keep a session alive.if (via !== "ticket") options.sessions.renew(session.id);diff --git a/server/routes/live.test.ts b/server/routes/live.test.tsindex af5f2837da..ecd98c1d22 100644--- a/server/routes/live.test.ts+++ b/server/routes/live.test.ts@@ -166,6 +166,11 @@ describe("live routes", () => {expect(await request(deps(), "PUT", "/api/live/settings", {})).toEqual({ status: 404, body: { from: "inline routes" } });expect(await request(deps(), "GET", "/api/bots")).toEqual({ status: 404, body: { from: "inline routes" } });});+ it("answers a call the Azure limit refuses with its words as a 403, and no setup prompt", async () => {+ const sentence = "Only an admin can start one.";+ const d = deps({ calls: { ...deps().calls, start: vi.fn(async () => { throw new LiveSessionError(sentence, 403); }) } });+ expect(await request(d, "POST", "/api/live/session", { botId: "bot1", sdp: "v=0", client: "web" })).toEqual({ status: 403, body: { error: sentence } });+ });it("is for admins only", () => {expect(requiredScope("POST", "/api/live/session")).toBe("admin");expect(requiredScope("POST", "/api/live/call/end")).toBe("admin");diff --git a/src/lib/live-call-media.test.ts b/src/lib/live-call-media.test.tsindex 2885b884b9..6b5c36b03e 100644--- a/src/lib/live-call-media.test.ts+++ b/src/lib/live-call-media.test.ts@@ -112,6 +112,15 @@ describe("live call media", () => {expect(currentCall()).toBeNull();});+ it("shows a refusal as the server words it, releases the microphone and offers no retry", async () => {+ const sentence = "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.";+ request.mockRejectedValueOnce(new ApiError(sentence, 403, { error: sentence }));+ await startLiveCall({ botId: "b1", threadId: "t1" });+ expect(liveMedia()).toMatchObject({ phase: "failed", notice: sentence, needsKey: false, action: null });+ expect(track.stopped).toBe(true);+ expect(currentCall()).toBeNull();+ });+it("says who is on the line when another call runs", async () => {const other = { ...call, callId: "c0", client: "ios", status: "live" } as const;request.mockRejectedValueOnce(new ApiError("A Live call is already running.", 409, { activeCall: other }));diff --git a/src/lib/live-call-media.ts b/src/lib/live-call-media.tsindex 1d2b376457..7cacd36da6 100644--- a/src/lib/live-call-media.ts+++ b/src/lib/live-call-media.ts@@ -255,7 +255,7 @@ export async function startLiveCall(target: { botId: string; threadId: string })if (mine !== generation) return;return set({ ...failed, ...micBlocked(deps.capabilities(), pageMic) });}- const hopeless = error instanceof LiveUnsupportedError || (error instanceof ApiError && error.status === 401);+ const hopeless = error instanceof LiveUnsupportedError || (error instanceof ApiError && (error.status === 401 || error.status === 403));set({ ...failed, action: hopeless ? null : "retry", notice: error instanceof Error ? error.message : String(error) });}}