From e47c422dc4b3d27e5a9cbb0eebca6e1694c8b821 Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 12:37:21 -0800 Subject: [PATCH 001/116] Settings for an OpenBot Desktop connected to an OpenBot that runs elsewhere Connected, nothing of OpenBot runs on this computer, so Settings, Computer shows where the app is connected, Sign out, and Use OpenBot on this computer instead, in place of the local services, memory and install folder. The app's version, updates and log folder stay. The page holds no sign-in there, so every Sign out asks the desktop app, and a sign-in that stopped working returns to the desktop app's setup. A desktop app from before it could connect is read as OpenBot on this computer, and a browser is unchanged. --- .../components/app-sidebar/use-sign-out.ts | 5 +- .../settings/connection-sections.tsx | 211 +++++++++++++ .../settings/this-computer-sections.tsx | 4 +- app/src/lib/auth/mutations.ts | 41 ++- app/src/lib/desktop/mutations.ts | 21 ++ app/src/lib/desktop/queries.ts | 40 +++ app/src/routes/_authed.tsx | 13 + app/src/routes/_authed/settings/computer.tsx | 25 +- app/tests/desktop-connected-settings.test.tsx | 276 ++++++++++++++++++ 9 files changed, 627 insertions(+), 9 deletions(-) create mode 100644 app/src/components/settings/connection-sections.tsx create mode 100644 app/tests/desktop-connected-settings.test.tsx diff --git a/app/src/components/app-sidebar/use-sign-out.ts b/app/src/components/app-sidebar/use-sign-out.ts index f884450293..cd4ce84238 100644 --- a/app/src/components/app-sidebar/use-sign-out.ts +++ b/app/src/components/app-sidebar/use-sign-out.ts @@ -20,9 +20,10 @@ export function useSignOut() { run: () => { if (signOut.isPending) return; signOut.mutate(undefined, { - onSuccess: () => { + onSuccess: ({ leaving }) => { toast.close(SIGN_OUT_TOAST); - void navigate({ to: "/sign" }); + // Inside a connected OpenBot Desktop the app shows its own setup, where sign-in is. + if (!leaving) void navigate({ to: "/sign" }); }, onError: (error) => toast.add({ diff --git a/app/src/components/settings/connection-sections.tsx b/app/src/components/settings/connection-sections.tsx new file mode 100644 index 0000000000..d998ede765 --- /dev/null +++ b/app/src/components/settings/connection-sections.tsx @@ -0,0 +1,211 @@ +import { + IconDeviceLaptop, + IconLogout, + IconPlugConnected, +} from "@tabler/icons-react"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { useState } from "react"; +import { PageRows, PageSection } from "@/components/layout/page-shell"; +import { RowMark } from "@/components/layout/row-mark"; +import { + LogsRow, + VersionRow, +} from "@/components/settings/this-computer-sections"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogBody, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { + Item, + ItemActions, + ItemContent, + ItemDescription, + ItemTitle, +} from "@/components/ui/item"; +import { Separator } from "@/components/ui/separator"; +import { + changeConnectionMutationOptions, + signOutOfConnectedOpenBotMutationOptions, +} from "@/lib/desktop/mutations"; +import { desktopStatusQueryOptions } from "@/lib/desktop/queries"; +import { COMPUTER_SECTION } from "@/lib/settings/computer-sections"; + +/** The address's host, which is how a person names the OpenBot they connect to. */ +function hostOf(address: string): string { + try { + return new URL(address).host; + } catch { + return address; + } +} + +/** + * Settings → Computer inside an OpenBot Desktop that is connected to an OpenBot running somewhere + * else: where it is connected, the two ways out, and the app's own details. + * + * It takes the place of `ThisComputerSections`. Nothing of OpenBot runs on this computer then, so + * there are no services to restart or stop, no memory to report and no install folder. The app's + * version, its updates and its log folder are about the app, and stay. + * + * Both ways out end with the window back at setup, so this page goes with them, as it does on Stop. + */ +export function ConnectionSections({ address }: { address: string }) { + const status = useQuery(desktopStatusQueryOptions({ memory: false })); + return ( + <> + + + + + + + + Connected to + + {address} + + + + + + + + + + {status.data && ( + + + {status.data.logFolder && ( + <> + + + + )} + + + + )} + + ); +} + +function SignOutRow({ host }: { host: string }) { + const [open, setOpen] = useState(false); + const signOut = useMutation(signOutOfConnectedOpenBotMutationOptions()); + // On success the desktop app is showing setup, and this page goes with it. + const leaving = signOut.isPending || signOut.isSuccess; + return ( + <> + + + + + + Sign out + + Sign out of this OpenBot on this computer. + + + + + + + + + + Sign out of {host}? + + You'll sign in again in your browser the next time you use OpenBot + here. Your Bots and conversations stay as they are. + + + {signOut.error ? ( + +

+ Couldn't sign out. Try again. +

+
+ ) : null} + + + + +
+
+ + ); +} + +function UseThisComputerRow({ host }: { host: string }) { + const [open, setOpen] = useState(false); + const change = useMutation(changeConnectionMutationOptions()); + // On success the desktop app is showing setup, and this page goes with it. + const leaving = change.isPending || change.isSuccess; + return ( + <> + + + + + + Use OpenBot on this computer instead + + Run every part of OpenBot on this computer. + + + + + + + + + + Use OpenBot on this computer instead? + + This signs you out of {host} and opens setup, where you choose + where OpenBot runs. Nothing on this computer is lost, and you can + connect to {host} again later. + + + {change.error ? ( + +

+ Couldn't open setup. Try again. +

+
+ ) : null} + + + + +
+
+ + ); +} diff --git a/app/src/components/settings/this-computer-sections.tsx b/app/src/components/settings/this-computer-sections.tsx index eef145d54b..730d07a418 100644 --- a/app/src/components/settings/this-computer-sections.tsx +++ b/app/src/components/settings/this-computer-sections.tsx @@ -355,7 +355,7 @@ function MachineSection({ * Where the desktop app keeps its log, with Open log folder, so a person can share the file when * they ask for help. The desktop app opens its own folder; nothing here names a path to open. */ -function LogsRow({ folder }: { folder: string }) { +export function LogsRow({ folder }: { folder: string }) { const open = useMutation(openLogFolderMutationOptions()); return ( @@ -405,7 +405,7 @@ function LogsRow({ folder }: { folder: string }) { * A newer version found says how ready it is, as the banner does: downloading in the background * while this version keeps running, then ready to install in a few minutes. */ -function VersionRow({ status }: { status: DesktopStatus }) { +export function VersionRow({ status }: { status: DesktopStatus }) { const check = useMutation(checkAppUpdateMutationOptions(queryClient)); const install = useMutation(installAppUpdateMutationOptions(queryClient)); // The download's progress, asked twice a second from the click on, as the banner asks once it diff --git a/app/src/lib/auth/mutations.ts b/app/src/lib/auth/mutations.ts index 7672b569d9..c0ff4d0d5f 100644 --- a/app/src/lib/auth/mutations.ts +++ b/app/src/lib/auth/mutations.ts @@ -1,6 +1,11 @@ import { mutationOptions, type QueryClient } from "@tanstack/react-query"; import { updatePerson } from "@/lib/api/generated/people/people"; import { idempotencyKey, ORGANIZATION_ID } from "@/lib/api/request"; +import { + desktopConnectionQueryOptions, + invokeDesktop, +} from "@/lib/desktop/queries"; +import { desktopShell } from "@/lib/desktop/shell"; import { clearSkin } from "@/skins/store"; import { authClient } from "./client"; import { authKeys } from "./queries"; @@ -17,6 +22,33 @@ async function signOut() { if (!answered || answered.error) throw new Error(SIGN_OUT_UNFINISHED); } +/** + * Whether this page is inside an OpenBot Desktop connected to an OpenBot that runs somewhere else. + * There the desktop app holds the sign-in and the page holds none, so the desktop app is what signs + * out, and it shows its own setup afterwards. + */ +export async function connectedThroughDesktop( + queryClient: QueryClient, +): Promise { + if (desktopShell() === null) return false; + const connection = await queryClient.ensureQueryData( + desktopConnectionQueryOptions(), + ); + return connection.mode === "connected"; +} + +/** Ask the desktop app to sign out of the OpenBot it is connected to. */ +export async function signOutThroughDesktop() { + try { + await invokeDesktop("sign_out"); + } catch { + throw new Error(SIGN_OUT_UNFINISHED); + } +} + +/** How a sign-out ended: `leaving` when the desktop app is taking the window back to its setup. */ +export type SignedOut = { leaving: boolean }; + /** * Every way out of OpenBot signs out through here, the skins' own menus included. * @@ -26,7 +58,14 @@ async function signOut() { */ export function signOutMutationOptions(queryClient: QueryClient) { return mutationOptions({ - mutationFn: signOut, + mutationFn: async (): Promise => { + if (await connectedThroughDesktop(queryClient)) { + await signOutThroughDesktop(); + return { leaving: true }; + } + await signOut(); + return { leaving: false }; + }, onSuccess: () => { clearSkin(); queryClient.removeQueries({ queryKey: authKeys.all }); diff --git a/app/src/lib/desktop/mutations.ts b/app/src/lib/desktop/mutations.ts index 006b3382b1..2c3c454bd5 100644 --- a/app/src/lib/desktop/mutations.ts +++ b/app/src/lib/desktop/mutations.ts @@ -56,6 +56,27 @@ export function changeAiConnectionMutationOptions() { }); } +/** + * Sign out of the OpenBot this app is connected to. The desktop app ends the sign-in there, forgets + * it on this computer and shows setup with the address still filled in. Like Stop, this page goes + * with it. + */ +export function signOutOfConnectedOpenBotMutationOptions() { + return mutationOptions({ + mutationFn: (): Promise => invokeDesktop("sign_out"), + }); +} + +/** + * Go back to OpenBot on this computer. The desktop app signs out of the OpenBot it is connected to + * and shows setup at the choice of where OpenBot runs. Nothing on this computer is changed by it. + */ +export function changeConnectionMutationOptions() { + return mutationOptions({ + mutationFn: (): Promise => invokeDesktop("change_connection"), + }); +} + /** * Check for updates now. The desktop app reads its update feed and keeps the answer, so the banner * reads it too. Rejects with the app's own sentence when the feed couldn't be read. diff --git a/app/src/lib/desktop/queries.ts b/app/src/lib/desktop/queries.ts index 1e2ba605ca..f878af538a 100644 --- a/app/src/lib/desktop/queries.ts +++ b/app/src/lib/desktop/queries.ts @@ -123,8 +123,20 @@ export type DesktopUsageData = { offByEnvironment: boolean; }; +/** + * Where the OpenBot this window shows runs: on this computer, which the desktop app started itself, + * or somewhere else, at an address the person typed and signed in to. Never the sign-in itself: the + * desktop app keeps that and the page never holds it. + */ +export type DesktopConnection = + | { mode: "local"; address: null } + | { mode: "connected"; address: string }; + +const ON_THIS_COMPUTER: DesktopConnection = { mode: "local", address: null }; + export const desktopKeys = { all: ["desktop"] as const, + connection: ["desktop", "connection"] as const, aiConnection: ["desktop", "ai-connection"] as const, usageData: ["desktop", "usage-data"] as const, status: (memory: boolean) => ["desktop", "status", { memory }] as const, @@ -144,6 +156,34 @@ export async function invokeDesktop( return (await shell.invoke(`${PLUGIN}|${command}`, args)) as T; } +/** + * Whether this window shows an OpenBot on this computer or one it is connected to. In a browser, + * and in a desktop app from before it could connect (which refuses the question the same way every + * time), the answer is this computer. It does not change while the page shows: changing it sends + * the window back to setup. + */ +export function desktopConnectionQueryOptions() { + return queryOptions({ + queryKey: desktopKeys.connection, + queryFn: async (): Promise => { + if (desktopShell() === null) return ON_THIS_COMPUTER; + try { + const answer = await invokeDesktop<{ + mode?: string; + address?: string | null; + }>("connection"); + return answer?.mode === "connected" && answer.address + ? { mode: "connected", address: answer.address } + : ON_THIS_COMPUTER; + } catch { + return ON_THIS_COMPUTER; + } + }, + staleTime: Number.POSITIVE_INFINITY, + retry: false, + }); +} + /** * What runs here, in two reads. Without `memory` it answers in milliseconds, with every container * listed and none measured, so the page draws at once. With `memory` it takes about two seconds, diff --git a/app/src/routes/_authed.tsx b/app/src/routes/_authed.tsx index 8aa969e504..a38b3d4034 100644 --- a/app/src/routes/_authed.tsx +++ b/app/src/routes/_authed.tsx @@ -3,6 +3,10 @@ import type { ReactNode } from "react"; import { BotLookProvider } from "../components/agents/bot-look"; import { TeamFeaturesDialog } from "../components/edition/team-features-dialog"; import { CommandMenu } from "../components/navigation/command-menu"; +import { + connectedThroughDesktop, + signOutThroughDesktop, +} from "../lib/auth/mutations"; import { currentUserQueryOptions, needsOnboarding } from "../lib/auth/queries"; import { CopilotProvider } from "../lib/copilot/provider"; import { AppHotkeys } from "../lib/hotkeys/app-hotkeys"; @@ -16,6 +20,15 @@ export const Route = createFileRoute("/_authed")({ currentUserQueryOptions(), ); if (!user) { + /* + * Inside an OpenBot Desktop connected to an OpenBot that runs somewhere else, the desktop app + * holds the sign-in and this page has none to renew: the web sign-in screen would sign in a + * window that cannot keep it. The desktop app ends what is left of the sign-in and shows its + * own setup, where the person signs in again. If it cannot, the sign-in screen is still there. + */ + if (await connectedThroughDesktop(context.queryClient)) { + await signOutThroughDesktop().catch(() => undefined); + } throw redirect({ to: "/sign" }); } /* diff --git a/app/src/routes/_authed/settings/computer.tsx b/app/src/routes/_authed/settings/computer.tsx index aa446d1794..3d540e9be0 100644 --- a/app/src/routes/_authed/settings/computer.tsx +++ b/app/src/routes/_authed/settings/computer.tsx @@ -3,8 +3,10 @@ import { createFileRoute } from "@tanstack/react-router"; import { PageShell } from "@/components/layout/page-shell"; import { ComputersPage } from "@/components/manage/computers-page"; import { BrowserSections } from "@/components/settings/browsers/browser-sections"; +import { ConnectionSections } from "@/components/settings/connection-sections"; import { ThisComputerSections } from "@/components/settings/this-computer-sections"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; +import { desktopConnectionQueryOptions } from "@/lib/desktop/queries"; import { desktopShell } from "@/lib/desktop/shell"; import { editionOf } from "@/lib/edition-guard"; import { useScrollToSection } from "@/lib/settings/computer-sections"; @@ -36,6 +38,15 @@ function ComputerPage() { const personal = useQuery(deploymentCapabilitiesQueryOptions()).data?.edition === "personal"; const desktop = desktopShell() !== null; + /* + * Inside OpenBot Desktop: whether OpenBot runs on this computer or the app is connected to one that + * runs somewhere else. Until the app has said which, neither is drawn, so the wrong one never shows. + */ + const connection = useQuery({ + ...desktopConnectionQueryOptions(), + enabled: desktop, + }).data; + const connected = connection?.mode === "connected"; /* * Desktop's Status opens `/settings/this-computer` and the extension's popup `/settings/browsers`; * each redirects here with its section's hash. @@ -46,14 +57,20 @@ function ComputerPage() { description={ personal ? "Your Bots share one computer, where each keeps its own browser signed in. A command one Bot runs can still read another Bot's files. Choose folders they can read here, and connect the browsers you teach them in." - : desktop - ? "Connect the browsers you teach your Bots in, and see what OpenBot runs on this computer." - : "Connect the browsers you teach your Bots in." + : connected + ? "Connect the browsers you teach your Bots in, and see which OpenBot this app is connected to." + : desktop + ? "Connect the browsers you teach your Bots in, and see what OpenBot runs on this computer." + : "Connect the browsers you teach your Bots in." } title="Computer" > {personal ? : null} - {desktop ? : null} + {!desktop || !connection ? null : connection.mode === "connected" ? ( + + ) : ( + + )} ); diff --git a/app/tests/desktop-connected-settings.test.tsx b/app/tests/desktop-connected-settings.test.tsx new file mode 100644 index 0000000000..bbaa6e5817 --- /dev/null +++ b/app/tests/desktop-connected-settings.test.tsx @@ -0,0 +1,276 @@ +/** + * OpenBot Desktop can show an OpenBot that runs on this computer, or one it is connected to at an address. Connected, + * nothing of OpenBot runs here, so Settings → Computer says where the app is connected and offers the two ways out + * (sign out, or go back to OpenBot on this computer) in place of the services, memory and install folder of a local + * OpenBot. The app's own version, updates and log folder stay, since those are about the app. + * + * The page holds no sign-in of its own there: the desktop app keeps it. So signing out, from Settings or from the + * account menu, is asked of the desktop app, and a sign-in that stopped working sends the person back to the desktop + * app's setup, never to the web sign-in screen. + * + * A desktop app from before it could connect refuses the question, and is read as OpenBot on this computer. + */ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import type { ComponentType } from "react"; +import { signOutMutationOptions } from "@/lib/auth/mutations"; +import { deploymentKeys } from "@/lib/deployment/queries"; +import type { DesktopStatus } from "@/lib/desktop/queries"; +import { Route as AuthedRoute } from "@/routes/_authed"; +import { Route as ComputerRoute } from "@/routes/_authed/settings/computer"; +import { settleReactWork } from "./settle-react-work"; + +const ADDRESS = "https://openbot.northwind.example"; + +/** What a connected desktop app answers `status` with: the app's own facts and nothing of a local OpenBot. */ +const CONNECTED_STATUS: DesktopStatus = { + openbotRunning: false, + openbotHeld: false, + processes: [], + containers: [], + intelligenceStack: null, + intelligenceContainers: [], + engine: null, + root: "", + appPort: null, + version: "1.1.0", + build: "Built 2026-11-15 18:30 UTC from 795f619 on main", + logFolder: "/Users/me/Library/Logs/ai.copilotkit.openbot.desktop", +}; + +const LOCAL_STATUS: DesktopStatus = { + ...CONNECTED_STATUS, + openbotRunning: true, + openbotHeld: true, + engine: "podman", + root: "/Users/me/OpenBot", + appPort: 3010, +}; + +type Shell = "connected" | "local" | "older"; + +/** Every command the page asked the desktop app, in order. */ +let asked: string[] = []; +/** Every address the page asked the server. */ +let fetched: string[] = []; +const originalFetch = globalThis.fetch; + +function installShell(kind: Shell) { + (window as unknown as Record).__TAURI_INTERNALS__ = { + transformCallback: () => 0, + invoke: async (command: string) => { + const name = command.replace("plugin:openbot-desktop|", ""); + asked.push(name); + if (name === "connection") { + if (kind === "older") throw "command connection not found"; + return kind === "connected" + ? { mode: "connected", address: ADDRESS } + : { mode: "local", address: null }; + } + if (name === "status") + return kind === "connected" ? CONNECTED_STATUS : LOCAL_STATUS; + if (name === "update_offer") + return { version: null, current: "1.1.0", installing: null }; + if (name === "sign_out" || name === "change_connection") return null; + throw `command ${command} not found`; + }, + }; +} + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://127.0.0.1:3010/" }); +}); +beforeEach(() => { + asked = []; + fetched = []; + globalThis.fetch = Object.assign( + async (input: RequestInfo | URL) => { + const url = typeof input === "string" ? input : input.toString(); + fetched.push(new URL(url, "http://127.0.0.1:3010").pathname); + if (url.includes("/api/auth/sign-out")) + return Response.json({ success: true }); + return Response.json({ error: "not served" }, { status: 401 }); + }, + { preconnect: originalFetch.preconnect }, + ); +}); +afterEach(() => { + cleanup(); + globalThis.fetch = originalFetch; + delete (window as unknown as Record).__TAURI_INTERNALS__; +}); +afterAll(async () => { + await settleReactWork(); + GlobalRegistrator.unregister(); +}); + +function newQueryClient() { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + queryClient.setQueryDefaults(deploymentKeys.capabilities(), { + staleTime: Number.POSITIVE_INFINITY, + }); + queryClient.setQueryData(deploymentKeys.capabilities(), { + generativeUi: true, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + }); + return queryClient; +} + +function renderComputer(kind: Shell) { + installShell(kind); + const Page = ComputerRoute.options.component as ComponentType; + const router = createRouter({ + routeTree: createRootRoute({ component: () => }), + history: createMemoryHistory({ initialEntries: ["/"] }), + }); + return render( + + + , + ); +} + +test("connected, Settings → Computer says where the app is connected and shows nothing of a local OpenBot", async () => { + const view = renderComputer("connected"); + await view.findByRole("heading", { name: "Connection" }); + expect(view.getByText(ADDRESS)).toBeTruthy(); + expect(view.getByRole("button", { name: "Sign out" })).toBeTruthy(); + expect(view.getByRole("button", { name: "Use this computer" })).toBeTruthy(); + // The app itself: its version and its log folder stay. + expect(await view.findByText("Version 1.1.0")).toBeTruthy(); + expect(view.getByRole("button", { name: "Open log folder" })).toBeTruthy(); + // Nothing OpenBot runs here: no services, no install folder, no engine. + expect(view.queryByRole("heading", { name: "App" })).toBeNull(); + expect(view.queryByText("Software OpenBot runs on")).toBeNull(); + expect(view.queryByText("Installed in")).toBeNull(); + expect(view.queryByRole("button", { name: "Stop" })).toBeNull(); + expect(view.queryByRole("button", { name: "Restart" })).toBeNull(); + const header = view + .getByRole("heading", { level: 1, name: "Computer" }) + .closest("header"); + expect(header?.textContent).toContain( + "Connect the browsers you teach your Bots in, and see which OpenBot this app is connected to.", + ); + expect(header?.textContent).not.toContain("runs on this computer"); +}); + +test("with OpenBot on this computer, the page is as it was: its services, and no Connection section", async () => { + const view = renderComputer("local"); + await view.findByRole("heading", { name: "App" }); + expect(view.getByText("Installed in")).toBeTruthy(); + expect(view.queryByRole("heading", { name: "Connection" })).toBeNull(); +}); + +test("a desktop app from before it could connect is read as OpenBot on this computer", async () => { + const view = renderComputer("older"); + await view.findByRole("heading", { name: "App" }); + expect(asked).toContain("connection"); + expect(view.queryByRole("heading", { name: "Connection" })).toBeNull(); +}); + +test("Sign out asks first, then asks the desktop app to sign out", async () => { + const view = renderComputer("connected"); + fireEvent.click(await view.findByRole("button", { name: "Sign out" })); + const dialog = await view.findByRole("dialog"); + expect(dialog.textContent).toContain( + "Sign out of openbot.northwind.example?", + ); + expect(asked).not.toContain("sign_out"); + fireEvent.click( + Array.from(dialog.querySelectorAll("button")).find( + (button) => button.textContent === "Sign out", + ) as HTMLButtonElement, + ); + await waitFor(() => expect(asked).toContain("sign_out")); +}); + +test("Use this computer asks first, saying nothing here is lost, then asks the desktop app to switch", async () => { + const view = renderComputer("connected"); + fireEvent.click( + await view.findByRole("button", { name: "Use this computer" }), + ); + const dialog = await view.findByRole("dialog"); + expect(dialog.textContent).toContain("Use OpenBot on this computer instead?"); + expect(dialog.textContent).toContain("Nothing on this computer is lost"); + expect(asked).not.toContain("change_connection"); + fireEvent.click( + Array.from(dialog.querySelectorAll("button")).find( + (button) => button.textContent === "Switch to this computer", + ) as HTMLButtonElement, + ); + await waitFor(() => expect(asked).toContain("change_connection")); + expect(asked).not.toContain("sign_out"); +}); + +test("connected, the account menu's Sign out is the desktop app's, and the page is told it is leaving", async () => { + installShell("connected"); + const queryClient = newQueryClient(); + const options = signOutMutationOptions(queryClient); + const outcome = await options.mutationFn?.(undefined, {} as never); + expect(asked).toContain("sign_out"); + expect(fetched).not.toContain("/api/auth/sign-out"); + expect(outcome).toEqual({ leaving: true }); +}); + +test("with OpenBot on this computer or in a browser, Sign out is the web sign-out as before", async () => { + for (const kind of ["local", "browser"] as const) { + asked = []; + fetched = []; + if (kind === "local") installShell("local"); + const options = signOutMutationOptions(newQueryClient()); + const outcome = await options.mutationFn?.(undefined, {} as never); + expect(asked).not.toContain("sign_out"); + expect(fetched).toContain("/api/auth/sign-out"); + expect(outcome).toEqual({ leaving: false }); + delete (window as unknown as Record).__TAURI_INTERNALS__; + } +}); + +test("connected, a sign-in that stopped working goes back to the desktop app's setup", async () => { + installShell("connected"); + const guard = AuthedRoute.options.beforeLoad as (input: { + context: { queryClient: QueryClient }; + location: { pathname: string }; + }) => Promise; + await guard({ + context: { queryClient: newQueryClient() }, + location: { pathname: "/" }, + }).catch(() => undefined); + expect(fetched).toContain("/api/v2/organizations/default/people/me"); + expect(asked).toContain("sign_out"); +}); + +test("in a browser, a visitor who is not signed in goes to the sign-in screen and no desktop app is asked", async () => { + const guard = AuthedRoute.options.beforeLoad as (input: { + context: { queryClient: QueryClient }; + location: { pathname: string }; + }) => Promise; + const thrown = await guard({ + context: { queryClient: newQueryClient() }, + location: { pathname: "/" }, + }).then( + () => null, + (error) => error, + ); + expect(asked).toEqual([]); + expect(JSON.stringify(thrown?.options ?? thrown)).toContain("/sign"); +}); From 0fccb7709687e97a5000f6b6706147dfa9a2d2cf Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 12:39:36 -0800 Subject: [PATCH 002/116] Add an API keys page to Settings, and say what OAuth needs in the spec A person had no way to make their first API key from the app: the operations were in the spec and nothing called them. Settings now has API keys under You. It lists the person's keys with when each was made, last used and expires, creates one by name and shows it once with Copy, and revokes one after asking. Two answers from the API read as a sentence, not an error. An OpenBot with no sign-in (503 SIGN_IN_UNAVAILABLE) says it has no keys. A caller that is not signed in on the web (403), which is OpenBot Desktop connected to an OpenBot elsewhere, is told to create keys from OpenBot in the browser, with a button that opens the page there. The spec's description and its appOAuth and apiKey schemes now state what a developer needs: the public client ids, loopback redirect addresses, the metadata, authorize, token and revocation endpoints, token prefixes and lifetimes, consent, and how to get a first key. Text only, so the generated clients are unchanged. --- CHANGELOG.md | 5 + api/openapi.yaml | 21 +- api/openapi/common.yaml | 57 ++- app/src/components/settings/api-keys.tsx | 405 ++++++++++++++++++ .../components/settings/settings-sidebar.tsx | 10 +- app/src/lib/api-keys/mutations.ts | 74 ++++ app/src/lib/api-keys/queries.ts | 85 ++++ app/src/lib/desktop/open-in-browser.ts | 18 + app/src/routeTree.gen.ts | 21 + app/src/routes/_authed/settings/api-keys.tsx | 6 + app/tests/api-keys-screen.test.tsx | 339 +++++++++++++++ app/tests/settings-sidebar.test.ts | 9 + 12 files changed, 1046 insertions(+), 4 deletions(-) create mode 100644 app/src/components/settings/api-keys.tsx create mode 100644 app/src/lib/api-keys/mutations.ts create mode 100644 app/src/lib/api-keys/queries.ts create mode 100644 app/src/lib/desktop/open-in-browser.ts create mode 100644 app/src/routes/_authed/settings/api-keys.tsx create mode 100644 app/tests/api-keys-screen.test.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 56df252441..3c7a53d441 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -350,6 +350,11 @@ earlier release's is one top-level line in it, `x-openbot-scheduled-work: server person, is sent as `Authorization: Bearer` or `x-api-key`, and works on `/api/v2` only. The server also issues access tokens through OAuth 2.1 with PKCE, which work on `/api/v2` only too. Both end when the person is removed. +- **Settings has an API keys page.** Under You, a signed-in person lists their keys, creates one + by name and revokes one. A new key is shown once, with Copy. OpenBot on one computer for one + person has no sign-in and says it has no keys, and OpenBot Desktop connected to an OpenBot + elsewhere opens the page in your browser. The spec now lists what an app needs for OAuth: the + client ids, redirect addresses, endpoints and how long tokens last. - **The web app calls the new addresses**, through a client generated from the spec, for Bots, the audit trail, accounts, admin settings, model connections, notifications, routines, conversations and approvals, and opens its sockets there. Apps, connections, a Bot's grants, diff --git a/api/openapi.yaml b/api/openapi.yaml index 8a9222a3b9..5ae6a41537 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -10,6 +10,10 @@ info: Until multi-organization lands, an OpenBot install has exactly one organization, and organizationId is that organization. Clients address it as `default`; the server treats any other value as an organization that does not exist. + A program of your own signs its requests in one of two ways, and both work on /api/v2 only. An API key acts as the person who made it. Keys start `obk_` and are sent as `Authorization: Bearer ` or in an `x-api-key` header. To get a first key, sign in to OpenBot's web app, open Settings, then API keys, and create one. The key is shown once. Only a person signed in to the web app can make or delete keys: a key or an app's sign-in cannot. An app that signs people in uses OAuth 2.1 instead, described under the appOAuth security scheme: its client ids, redirect addresses, endpoints and how long tokens last. + + An install for one person on one computer has no sign-in. It signs nobody in, so it has neither OAuth nor API keys, and the operations that manage keys and sessions answer 503 with the code SIGN_IN_UNAVAILABLE. + This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request. servers: - url: http://127.0.0.1:3001 @@ -18295,7 +18299,20 @@ components: description: The web app's server-side session, so no token ever reaches the browser. Served over HTTPS the cookie is __Secure-better-auth.session_token. A single-user install signs its one person in without a cookie. appOAuth: type: oauth2 - description: Desktop and mobile. OAuth 2.1 authorization code with PKCE (RFC 7636, S256 only); the access token is sent as a bearer token. + description: |- + Desktop and mobile. OAuth 2.1 authorization code with PKCE (RFC 7636, S256 only); the access token is sent as a bearer token. + + Clients. Three public clients are registered: `openbot-desktop-oauth`, `openbot-mobile` and `openbot-cli`. A public client has no secret and must use PKCE with S256. Dynamic client registration is off, so an app uses one of these ids. + + Redirect addresses. A client on the person's own computer listens on a loopback address and any port: `http://127.0.0.1:/callback` or `http://[::1]:/callback`. `localhost` is not accepted. + + Endpoints. The authorization server's metadata (RFC 8414) is at `/.well-known/oauth-authorization-server/api/auth`. The person is sent to `/api/auth/oauth2/authorize`. The code is exchanged, and a token refreshed, at `/api/auth/oauth2/token`, with a form-encoded body (`application/x-www-form-urlencoded`) that carries `client_id`. A token is revoked (RFC 7009) at `/api/auth/oauth2/revoke`. + + Tokens. An access token starts `oba_` and lasts one hour. A refresh token starts `obr_`, is issued only when the `offline_access` scope is asked for, and rotates on every use: each refresh answers a new refresh token and ends the one it was given. Access tokens work on /api/v2 only. + + Consent. The person is asked once for each app, and not again for scopes they already allowed it. + + An install for one person on one computer has no sign-in, so it has no OAuth: there is nobody to authorize an app as. flows: authorizationCode: authorizationUrl: /api/auth/oauth2/authorize @@ -18383,7 +18400,7 @@ components: type: http scheme: bearer bearerFormat: OpenBot API key - description: Automation. An API key acts as the person who created it, inside one organization. + description: 'Automation. An API key acts as the person who created it, inside one organization. A key starts `obk_` and is sent as `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 only. A person makes one in the web app, signed in, under Settings, then API keys (createApiKey).' recorderConnection: type: http scheme: bearer diff --git a/api/openapi/common.yaml b/api/openapi/common.yaml index 4adf35fbec..39892df718 100644 --- a/api/openapi/common.yaml +++ b/api/openapi/common.yaml @@ -32,6 +32,23 @@ info: does not exist. + A program of your own signs its requests in one of two ways, and both + work on /api/v2 only. An API key acts as the person who made it. Keys + start `obk_` and are sent as `Authorization: Bearer ` or in an + `x-api-key` header. To get a first key, sign in to OpenBot's web app, open + Settings, then API keys, and create one. The key is shown once. Only a + person signed in to the web app can make or delete keys: a key or an + app's sign-in cannot. An app that signs people in uses OAuth 2.1 + instead, described under the appOAuth security scheme: its client ids, + redirect addresses, endpoints and how long tokens last. + + + An install for one person on one computer has no sign-in. It signs + nobody in, so it has neither OAuth nor API keys, and the operations + that manage keys and sessions answer 503 with the code + SIGN_IN_UNAVAILABLE. + + This file is the single source of truth: the clients, the server's types, the docs and the contract tests are all generated from it or checked against it. A change that breaks an existing client fails the pull request. @@ -420,6 +437,41 @@ components: description: >- Desktop and mobile. OAuth 2.1 authorization code with PKCE (RFC 7636, S256 only); the access token is sent as a bearer token. + + + Clients. Three public clients are registered: `openbot-desktop-oauth`, + `openbot-mobile` and `openbot-cli`. A public client has no secret and + must use PKCE with S256. Dynamic client registration is off, so an + app uses one of these ids. + + + Redirect addresses. A client on the person's own computer listens on + a loopback address and any port: + `http://127.0.0.1:/callback` or + `http://[::1]:/callback`. `localhost` is not accepted. + + + Endpoints. The authorization server's metadata (RFC 8414) is at + `/.well-known/oauth-authorization-server/api/auth`. The person is + sent to `/api/auth/oauth2/authorize`. The code is exchanged, and a + token refreshed, at `/api/auth/oauth2/token`, with a form-encoded + body (`application/x-www-form-urlencoded`) that carries `client_id`. + A token is revoked (RFC 7009) at `/api/auth/oauth2/revoke`. + + + Tokens. An access token starts `oba_` and lasts one hour. A refresh + token starts `obr_`, is issued only when the `offline_access` scope + is asked for, and rotates on every use: each refresh answers a new + refresh token and ends the one it was given. Access tokens work on + /api/v2 only. + + + Consent. The person is asked once for each app, and not again for + scopes they already allowed it. + + + An install for one person on one computer has no sign-in, so it has + no OAuth: there is nobody to authorize an app as. flows: authorizationCode: authorizationUrl: /api/auth/oauth2/authorize @@ -509,7 +561,10 @@ components: bearerFormat: OpenBot API key description: >- Automation. An API key acts as the person who created it, inside one - organization. + organization. A key starts `obk_` and is sent as + `Authorization: Bearer ` or in an `x-api-key` header, on /api/v2 + only. A person makes one in the web app, signed in, under Settings, + then API keys (createApiKey). recorderConnection: type: http scheme: bearer diff --git a/app/src/components/settings/api-keys.tsx b/app/src/components/settings/api-keys.tsx new file mode 100644 index 0000000000..495031925a --- /dev/null +++ b/app/src/components/settings/api-keys.tsx @@ -0,0 +1,405 @@ +import { IconExternalLink, IconKey, IconPlus } from "@tabler/icons-react"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Fragment, useState } from "react"; +import { + PageEmpty, + PageRows, + PageSection, + PageShell, +} from "@/components/layout/page-shell"; +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogBody, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"; +import { Input } from "@/components/ui/input"; +import { + Item, + ItemActions, + ItemContent, + ItemDescription, + ItemMedia, + ItemTitle, +} from "@/components/ui/item"; +import { Separator } from "@/components/ui/separator"; +import { + createApiKeyMutationOptions, + type NewApiKey, + revokeApiKeyMutationOptions, +} from "@/lib/api-keys/mutations"; +import { type ApiKey, apiKeyListQueryOptions } from "@/lib/api-keys/queries"; +import { openInSystemBrowser } from "@/lib/desktop/open-in-browser"; +import { desktopShell } from "@/lib/desktop/shell"; +import { relativeTime } from "@/lib/relative-time"; +import { queryClient } from "@/query-client"; +import { copyText } from "./linked-accounts"; + +/** The longest name the API takes (`CreateApiKeyRequest.name`). */ +const NAME_LIMIT = 32; + +const day = new Intl.DateTimeFormat(undefined, { dateStyle: "medium" }); + +/** What a key is called on screen. The API allows a key with no name; the screen never makes one. */ +function keyName(apiKey: ApiKey): string { + return apiKey.name?.trim() || "Unnamed key"; +} + +/** A key's row, under its name: how it starts, when it was made, its last use, and its end if it has one. */ +export function apiKeyDescription(apiKey: ApiKey, now = Date.now()): string { + const parts = [ + ...(apiKey.start ? [`${apiKey.start}…`] : []), + `Created ${day.format(new Date(apiKey.createdAt))}`, + apiKey.lastUsedAt + ? `Last used ${relativeTime(apiKey.lastUsedAt)}` + : "Never used", + ]; + if (apiKey.expiresAt) { + const expires = new Date(apiKey.expiresAt); + parts.push( + `${expires.getTime() <= now ? "Expired" : "Expires"} ${day.format(expires)}`, + ); + } + return parts.join(" · "); +} + +/** + * Settings → API keys: the keys a person made for their own scripts and programs, with Create and + * Revoke. + * + * A key is shown whole once, when it is made, and is kept nowhere in the app after that dialog + * closes. Two answers from the API are not failures and read as a sentence: an OpenBot with no + * sign-in has no keys, and OpenBot Desktop connected to an OpenBot elsewhere is sent to the browser, + * because only a person signed in on the web can manage keys. + */ +export function ApiKeysPage() { + const list = useQuery(apiKeyListQueryOptions()); + const [creating, setCreating] = useState(false); + const [made, setMade] = useState(null); + const ready = list.data?.state === "ready"; + const createButton = (size: "sm" | "lg", variant: "default" | "outline") => ( + + ); + return ( + + {/* One section, so it carries no heading: the page title already names it. */} + + {list.isPending ? null : list.error ? ( +

+ Couldn't load your API keys. Reload the page. +

+ ) : list.data.state === "unavailable" ? ( + + This OpenBot runs on one computer for one person and has no sign-in, + so it has no API keys. + + ) : list.data.state === "browser-only" ? ( + + ) : list.data.apiKeys.length === 0 ? ( + + A key lets a script or another program use OpenBot as you. + + ) : ( + + {list.data.apiKeys.map((apiKey, index) => ( + + {index > 0 ? : null} + + + ))} + + )} +
+ { + setCreating(false); + setMade(key); + }} + onOpenChange={setCreating} + open={creating} + /> + setMade(null)} /> +
+ ); +} + +/** + * Where keys are managed when this window can't: OpenBot in a browser. In OpenBot Desktop a button + * opens this page there; anywhere else there is nothing to press, so it is only said. + */ +function BrowserOnly() { + const [failed, setFailed] = useState(false); + const address = `${window.location.origin}/settings/api-keys`; + return ( + + setFailed(!(await openInSystemBrowser(address))) + } + size="sm" + variant="outline" + > + + Open in browser + + ) : undefined + } + icon={IconKey} + title="API keys are managed in your browser" + > + {failed ? ( + + Couldn't open your browser. Go to {address} there. + + ) : ( + "Create API keys from OpenBot in your browser." + )} + + ); +} + +/** + * One key, with its own Revoke: asked first in a dialog, because whatever uses the key stops working + * at once, and pending for this row alone. A refusal is said in the dialog, where the person asked. + */ +function ApiKeyRow({ apiKey }: { apiKey: ApiKey }) { + const [asking, setAsking] = useState(false); + const revoke = useMutation(revokeApiKeyMutationOptions(queryClient)); + const name = keyName(apiKey); + return ( + <> + + + + + + {name} + {apiKeyDescription(apiKey)} + + + + + + + + + Revoke {name}? + + +

+ Anything that uses this key stops working right away. You can't + undo this. +

+ {revoke.error ? ( +

+ {revoke.error.message} +

+ ) : null} +
+ + + + +
+
+ + ); +} + +/** The one thing a key needs from a person: a name. One field, so a dialog and not a screen of its own. */ +function CreateApiKeyDialog({ + onMade, + onOpenChange, + open, +}: { + onMade: (made: NewApiKey) => void; + onOpenChange: (open: boolean) => void; + open: boolean; +}) { + const [name, setName] = useState(""); + const create = useMutation(createApiKeyMutationOptions(queryClient)); + const trimmed = name.trim(); + const close = (next: boolean) => { + if (!next) { + setName(""); + create.reset(); + } + onOpenChange(next); + }; + return ( + + +
{ + event.preventDefault(); + if (!trimmed || create.isPending) return; + create.mutate( + { name: trimmed }, + { + onSuccess: (made) => { + // Handed on and dropped here, so the key is held only by the dialog that shows it. + setName(""); + create.reset(); + onMade(made); + }, + }, + ); + }} + > + + Create API key + + + + Name + + Name it after what will use it, so you can tell your keys apart. + + setName(event.target.value)} + placeholder="Nightly report" + value={name} + /> + + {create.error ? ( +

+ {create.error.message} +

+ ) : null} +
+ + + + +
+
+
+ ); +} + +/** The key itself, this once. Closing the dialog drops it: the API never gives it again. */ +function NewApiKeyDialog({ + made, + onClose, +}: { + made: NewApiKey | null; + onClose: () => void; +}) { + const [copied, setCopied] = useState(false); + const [copyFailed, setCopyFailed] = useState(false); + const close = () => { + setCopied(false); + setCopyFailed(false); + onClose(); + }; + return ( + { + if (!open) close(); + }} + open={made !== null} + > + + + Copy your API key + + + {made ? ( +
+

+ Copy this key now and keep it somewhere safe. You can't see it + again after you close this. +

+
+ + {made.key} + + +
+ {copyFailed ? ( +

+ Couldn't copy. Select the key and copy it yourself. +

+ ) : null} +
+ ) : null} +
+ + + +
+
+ ); +} diff --git a/app/src/components/settings/settings-sidebar.tsx b/app/src/components/settings/settings-sidebar.tsx index 49dad6383a..1c671e4348 100644 --- a/app/src/components/settings/settings-sidebar.tsx +++ b/app/src/components/settings/settings-sidebar.tsx @@ -1,6 +1,7 @@ import { IconArrowLeft, IconBell, + IconKey, IconLayoutGrid, IconListCheck, IconSettings, @@ -58,7 +59,7 @@ type SettingsSidebarItem = { /** * Settings, for every Bot at once (`docs/how-openbot-works.md`), in three groups: * - * - You: your account, where updates reach you, and your Vault. + * - You: your account, where updates reach you, your Vault, and your API keys. * - Every Bot: what is set once for all of them, in the fixed order of `lib/primitives.ts`. * Conversations is not here: it is where work happens, not something to set. Routines, Memory, * Skills and Apps (Connections) are things you make and come back to, so they are in the main @@ -91,6 +92,13 @@ export const SETTINGS_SIDEBAR_ITEMS: SettingsSidebarItem[] = [ icon: VAULT.icon, linkOptions: { to: "/settings/vault" }, }, + { + /* The keys you make for your own scripts and programs, which use OpenBot as you. */ + group: "you", + title: "API keys", + icon: IconKey, + linkOptions: { to: "/settings/api-keys" }, + }, { /* The computer Bots work on, folders, what OpenBot runs here, and your Recorder browsers. */ group: "every-bot", diff --git a/app/src/lib/api-keys/mutations.ts b/app/src/lib/api-keys/mutations.ts new file mode 100644 index 0000000000..551da28331 --- /dev/null +++ b/app/src/lib/api-keys/mutations.ts @@ -0,0 +1,74 @@ +import { mutationOptions, type QueryClient } from "@tanstack/react-query"; +import { + createApiKey, + deleteApiKey, +} from "@/lib/api/generated/api-keys/api-keys"; +import { idempotencyKey, ORGANIZATION_ID } from "@/lib/api/request"; +import { ClientError } from "@/lib/client"; +import { type ApiKey, apiKeyKeys } from "./queries"; + +const CREATE_FALLBACK = "Couldn't create the API key. Try again."; +const REVOKE_FALLBACK = "Couldn't revoke the API key. Try again."; + +/** What a person gives to make a key: what it is for. */ +export type ApiKeyInput = { name: string }; + +/** A key just made. `key` is the key itself, which the API answers this once and never again. */ +export type NewApiKey = { apiKey: ApiKey; key: string }; + +/** The API's code for "no such key". */ +export const API_KEY_NOT_FOUND = "API_KEY_NOT_FOUND"; + +/** + * Whether a refusal says the key is already gone: the API's own 404, `API_KEY_NOT_FOUND`. Revoked in + * another tab, which is what the person asked for, so it is success. Any other 404 (a proxy, a + * missing route) says nothing about the key and is a failure: the key may still work. + */ +export function alreadyRevoked(error: unknown): boolean { + return ( + error instanceof ClientError && + error.status === 404 && + error.code === API_KEY_NOT_FOUND + ); +} + +function invalidateApiKeys(queryClient: QueryClient) { + return queryClient.invalidateQueries({ queryKey: apiKeyKeys.all }); +} + +export function createApiKeyMutationOptions(queryClient: QueryClient) { + return mutationOptions({ + mutationFn: (input: ApiKeyInput): Promise => + createApiKey( + ORGANIZATION_ID, + "me", + input, + { "Idempotency-Key": idempotencyKey() }, + { fallback: CREATE_FALLBACK }, + ), + // The key itself is handed to whoever asked and kept nowhere: it can't be read again, so a + // copy left in the mutation cache would be the one place it outlived the dialog that showed it. + gcTime: 0, + onSuccess: () => invalidateApiKeys(queryClient), + }); +} + +export function revokeApiKeyMutationOptions(queryClient: QueryClient) { + return mutationOptions({ + mutationFn: async (apiKeyId: string): Promise => { + try { + await deleteApiKey( + ORGANIZATION_ID, + "me", + apiKeyId, + { "Idempotency-Key": idempotencyKey() }, + { fallback: REVOKE_FALLBACK }, + ); + } catch (error) { + if (alreadyRevoked(error)) return; + throw error; + } + }, + onSettled: () => invalidateApiKeys(queryClient), + }); +} diff --git a/app/src/lib/api-keys/queries.ts b/app/src/lib/api-keys/queries.ts new file mode 100644 index 0000000000..92b9e03d1d --- /dev/null +++ b/app/src/lib/api-keys/queries.ts @@ -0,0 +1,85 @@ +import { queryOptions } from "@tanstack/react-query"; +import { everyPage } from "@/lib/api/every-page"; +import { listApiKeys } from "@/lib/api/generated/api-keys/api-keys"; +import type { ApiKey as ApiKeyRecord } from "@/lib/api/generated/model"; +import { ORGANIZATION_ID } from "@/lib/api/request"; +import { ClientError } from "@/lib/client"; + +/** An API key the person made, as the API lists it. Never the key itself: `start` is its first characters. */ +export type ApiKey = ApiKeyRecord; + +export const apiKeyKeys = { + all: ["api-keys"] as const, + list: () => ["api-keys", "list"] as const, +}; + +const LOAD_FALLBACK = "Couldn't load your API keys."; + +/** The API's code for "this OpenBot signs nobody in", which is OpenBot on one computer for one person. */ +export const SIGN_IN_UNAVAILABLE = "SIGN_IN_UNAVAILABLE"; + +/** The API's code for a refusal by who is asking. */ +export const PERMISSION_DENIED = "PERMISSION_DENIED"; + +/** + * Whether a refusal is this OpenBot saying it has no sign-in, and so no API keys: the API's 503 with + * `SIGN_IN_UNAVAILABLE`. That is the feature being absent, not the server breaking. Any other + * failure, a 503 from a proxy included, is shown as a failure. + */ +export function apiKeysAbsent(error: unknown): boolean { + return ( + error instanceof ClientError && + error.status === 503 && + error.code === SIGN_IN_UNAVAILABLE + ); +} + +/** + * Whether a refusal is the API saying keys are managed only by a person signed in to OpenBot on the + * web: its 403 with `PERMISSION_DENIED`. The list is always the person's own (`me`), so the only way + * to be refused is to have signed in as an app, which is what OpenBot Desktop connected to an OpenBot + * elsewhere does. + */ +export function apiKeysNeedBrowser(error: unknown): boolean { + return ( + error instanceof ClientError && + error.status === 403 && + error.code === PERMISSION_DENIED + ); +} + +/** + * What the screen has to show: the person's keys, or one of the two reasons there is no list. Both + * reasons are answers, not failures, so the screen says them in a sentence. + */ +export type ApiKeyList = + | { state: "ready"; apiKeys: ApiKey[] } + /** This OpenBot has no sign-in, so it has no keys. */ + | { state: "unavailable" } + /** Keys are managed from OpenBot in a browser, not from here. */ + | { state: "browser-only" }; + +/** Every page of the person's API keys, newest first. A handful at most, so the screen reads them all. */ +export function apiKeyListQueryOptions() { + return queryOptions({ + queryKey: apiKeyKeys.list(), + queryFn: async ({ signal }): Promise => { + try { + const apiKeys = await everyPage(async (cursor) => { + const page = await listApiKeys( + ORGANIZATION_ID, + "me", + { limit: 100, ...(cursor ? { cursor } : {}) }, + { signal, fallback: LOAD_FALLBACK }, + ); + return { items: page.apiKeys, nextCursor: page.nextCursor }; + }); + return { state: "ready", apiKeys }; + } catch (error) { + if (apiKeysAbsent(error)) return { state: "unavailable" }; + if (apiKeysNeedBrowser(error)) return { state: "browser-only" }; + throw error; + } + }, + }); +} diff --git a/app/src/lib/desktop/open-in-browser.ts b/app/src/lib/desktop/open-in-browser.ts new file mode 100644 index 0000000000..bab16634bf --- /dev/null +++ b/app/src/lib/desktop/open-in-browser.ts @@ -0,0 +1,18 @@ +import { desktopShell } from "./shell"; + +/** + * Open an address in the person's own browser from the OpenBot Desktop window, answering whether it + * was handed over. The window is a webview, so a link to one of OpenBot's own pages would open + * inside it; this is the opener plugin's command, which leaves the window where it is. False in a + * plain browser, and when the window refuses the command. + */ +export async function openInSystemBrowser(url: string): Promise { + const shell = desktopShell(); + if (!shell) return false; + try { + await shell.invoke("plugin:opener|open_url", { url }); + return true; + } catch { + return false; + } +} diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.ts index 4610113495..ba2fdfac1a 100644 --- a/app/src/routeTree.gen.ts +++ b/app/src/routeTree.gen.ts @@ -44,6 +44,7 @@ import { Route as AuthedAdminSkillsRouteImport } from './routes/_authed/admin/sk import { Route as AuthedAdminWhatIfRouteImport } from './routes/_authed/admin/what-if' import { Route as AuthedSettingsIndexRouteImport } from './routes/_authed/settings/index' import { Route as AuthedSettingsPersonalRouteImport } from './routes/_authed/settings/_personal' +import { Route as AuthedSettingsApiKeysRouteImport } from './routes/_authed/settings/api-keys' import { Route as AuthedSettingsApprovalsRouteImport } from './routes/_authed/settings/approvals' import { Route as AuthedSettingsBrowsersRouteImport } from './routes/_authed/settings/browsers' import { Route as AuthedSettingsComputerRouteImport } from './routes/_authed/settings/computer' @@ -295,6 +296,11 @@ const AuthedSettingsPersonalRoute = AuthedSettingsPersonalRouteImport.update({ id: '/_personal', getParentRoute: () => AuthedSettingsRouteRoute, } as any) +const AuthedSettingsApiKeysRoute = AuthedSettingsApiKeysRouteImport.update({ + id: '/api-keys', + path: '/api-keys', + getParentRoute: () => AuthedSettingsRouteRoute, +} as any) const AuthedSettingsApprovalsRoute = AuthedSettingsApprovalsRouteImport.update({ id: '/approvals', path: '/approvals', @@ -757,6 +763,7 @@ export interface FileRoutesByFullPath { '/admin/providers': typeof AuthedAdminProvidersRoute '/admin/skills': typeof AuthedAdminSkillsRoute '/admin/what-if': typeof AuthedAdminWhatIfRoute + '/settings/api-keys': typeof AuthedSettingsApiKeysRoute '/settings/approvals': typeof AuthedSettingsApprovalsRoute '/settings/browsers': typeof AuthedSettingsBrowsersRoute '/settings/computer': typeof AuthedSettingsComputerRoute @@ -866,6 +873,7 @@ export interface FileRoutesByTo { '/admin/skills': typeof AuthedAdminSkillsRoute '/admin/what-if': typeof AuthedAdminWhatIfRoute '/settings': typeof AuthedSettingsIndexRoute + '/settings/api-keys': typeof AuthedSettingsApiKeysRoute '/settings/approvals': typeof AuthedSettingsApprovalsRoute '/settings/browsers': typeof AuthedSettingsBrowsersRoute '/settings/computer': typeof AuthedSettingsComputerRoute @@ -978,6 +986,7 @@ export interface FileRoutesById { '/_authed/admin/skills': typeof AuthedAdminSkillsRoute '/_authed/admin/what-if': typeof AuthedAdminWhatIfRoute '/_authed/settings/_personal': typeof AuthedSettingsPersonalRouteWithChildren + '/_authed/settings/api-keys': typeof AuthedSettingsApiKeysRoute '/_authed/settings/approvals': typeof AuthedSettingsApprovalsRoute '/_authed/settings/browsers': typeof AuthedSettingsBrowsersRoute '/_authed/settings/computer': typeof AuthedSettingsComputerRoute @@ -1091,6 +1100,7 @@ export interface FileRouteTypes { | '/admin/providers' | '/admin/skills' | '/admin/what-if' + | '/settings/api-keys' | '/settings/approvals' | '/settings/browsers' | '/settings/computer' @@ -1200,6 +1210,7 @@ export interface FileRouteTypes { | '/admin/skills' | '/admin/what-if' | '/settings' + | '/settings/api-keys' | '/settings/approvals' | '/settings/browsers' | '/settings/computer' @@ -1311,6 +1322,7 @@ export interface FileRouteTypes { | '/_authed/admin/skills' | '/_authed/admin/what-if' | '/_authed/settings/_personal' + | '/_authed/settings/api-keys' | '/_authed/settings/approvals' | '/_authed/settings/browsers' | '/_authed/settings/computer' @@ -1644,6 +1656,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedSettingsPersonalRouteImport parentRoute: typeof AuthedSettingsRouteRoute } + '/_authed/settings/api-keys': { + id: '/_authed/settings/api-keys' + path: '/api-keys' + fullPath: '/settings/api-keys' + preLoaderRoute: typeof AuthedSettingsApiKeysRouteImport + parentRoute: typeof AuthedSettingsRouteRoute + } '/_authed/settings/approvals': { id: '/_authed/settings/approvals' path: '/approvals' @@ -2278,6 +2297,7 @@ const AuthedSettingsPersonalRouteWithChildren = interface AuthedSettingsRouteRouteChildren { AuthedSettingsPersonalRoute: typeof AuthedSettingsPersonalRouteWithChildren + AuthedSettingsApiKeysRoute: typeof AuthedSettingsApiKeysRoute AuthedSettingsApprovalsRoute: typeof AuthedSettingsApprovalsRoute AuthedSettingsBrowsersRoute: typeof AuthedSettingsBrowsersRoute AuthedSettingsComputerRoute: typeof AuthedSettingsComputerRoute @@ -2300,6 +2320,7 @@ interface AuthedSettingsRouteRouteChildren { const AuthedSettingsRouteRouteChildren: AuthedSettingsRouteRouteChildren = { AuthedSettingsPersonalRoute: AuthedSettingsPersonalRouteWithChildren, + AuthedSettingsApiKeysRoute: AuthedSettingsApiKeysRoute, AuthedSettingsApprovalsRoute: AuthedSettingsApprovalsRoute, AuthedSettingsBrowsersRoute: AuthedSettingsBrowsersRoute, AuthedSettingsComputerRoute: AuthedSettingsComputerRoute, diff --git a/app/src/routes/_authed/settings/api-keys.tsx b/app/src/routes/_authed/settings/api-keys.tsx new file mode 100644 index 0000000000..43dbaca5f3 --- /dev/null +++ b/app/src/routes/_authed/settings/api-keys.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from "@tanstack/react-router"; +import { ApiKeysPage } from "@/components/settings/api-keys"; + +export const Route = createFileRoute("/_authed/settings/api-keys")({ + component: ApiKeysPage, +}); diff --git a/app/tests/api-keys-screen.test.tsx b/app/tests/api-keys-screen.test.tsx new file mode 100644 index 0000000000..9e4b461fd0 --- /dev/null +++ b/app/tests/api-keys-screen.test.tsx @@ -0,0 +1,339 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { HttpResponse, http } from "msw"; +import { setupServer } from "msw/node"; +import { ApiKeysPage } from "@/components/settings/api-keys"; +import { + getApiKeysMock, + getCreateApiKeyMockHandler, + getCreateApiKeyResponseMock, + getDeleteApiKeyMockHandler, + getListApiKeysMockHandler, + getListApiKeysResponseMock, +} from "@/lib/api/generated/api-keys/api-keys.msw"; +import type { ApiKey } from "@/lib/api/generated/model"; +import { queryClient as appQueryClient } from "@/query-client"; +import { settleReactWork } from "./settle-react-work"; + +/** + * Settings → API keys, against the spec's own server. + * + * The MSW handlers are the ones Orval generates beside the client, answering at the API's addresses + * with the spec's examples, and the screen is the real one. A request anywhere else is not found, so + * a hand-written address cannot pass. + */ + +const requests: string[] = []; +const server = setupServer( + ...getApiKeysMock(), + http.all("*", () => new HttpResponse(null, { status: 404 })), +); +server.events.on("request:start", ({ request }) => { + const url = new URL(request.url); + requests.push(`${request.method} ${url.pathname}${url.search}`); +}); + +const KEYS = "/api/v2/organizations/default/people/me/api-keys"; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://openbot.invalid/" }); + server.listen({ onUnhandledRequest: "error" }); +}); +afterEach(() => { + cleanup(); + server.resetHandlers(); + requests.length = 0; + // The screen's writes invalidate through the app's one client; nothing is left in it for the next test. + appQueryClient.clear(); + delete (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__; +}); +afterAll(async () => { + server.close(); + await settleReactWork(); + GlobalRegistrator.unregister(); +}); + +function draw() { + const rootRoute = createRootRoute(); + const router = createRouter({ + routeTree: rootRoute.addChildren([ + createRoute({ + getParentRoute: () => rootRoute, + path: "/settings/api-keys", + component: ApiKeysPage, + }), + ]), + history: createMemoryHistory({ initialEntries: ["/settings/api-keys"] }), + }); + return render( + + + , + ); +} + +/** A problem answer, as the API writes one. */ +function problem(status: number, code: string, detail: string) { + return HttpResponse.json( + { + type: "https://open.bot/errors/example", + title: detail, + status, + detail, + code, + category: "permission", + retryable: false, + requestId: "req_example", + traceId: "trace_example", + }, + { status, headers: { "content-type": "application/problem+json" } }, + ); +} + +test("lists the person's keys with when each was made, last used and expires", async () => { + const [example] = getListApiKeysResponseMock().apiKeys; + const never: ApiKey = { + id: "9f8e7d6c5b4a3210", + name: "Laptop script", + start: "obk_Qr", + createdAt: "2026-11-01T10:00:00.000Z", + expiresAt: null, + lastUsedAt: null, + }; + server.use( + getListApiKeysMockHandler({ apiKeys: [example, never], nextCursor: null }), + ); + const view = draw(); + + const used = (await view.findByText("Nightly report")).closest( + '[data-slot="item"]', + ); + expect(used?.textContent).toContain("obk_Xy"); + expect(used?.textContent).toContain("Created Nov 14, 2026"); + expect(used?.textContent).toMatch(/Last used .+ ago|Last used/); + expect(used?.textContent).toContain("Expires Feb 12, 2027"); + + const unused = view.getByText("Laptop script").closest('[data-slot="item"]'); + expect(unused?.textContent).toContain("Never used"); + expect(unused?.textContent).not.toContain("Expires"); + + expect(requests).toContain(`GET ${KEYS}?limit=100`); +}); + +test("reads every page of the list", async () => { + const [example] = getListApiKeysResponseMock().apiKeys; + server.use( + getListApiKeysMockHandler(({ request }) => + new URL(request.url).searchParams.get("cursor") === "bmV4dA" + ? { + apiKeys: [{ ...example, id: "second", name: "Second page key" }], + nextCursor: null, + } + : { apiKeys: [example], nextCursor: "bmV4dA" }, + ), + ); + const view = draw(); + + await view.findByText("Second page key"); + expect(view.getByText("Nightly report")).toBeTruthy(); + expect(requests).toContain(`GET ${KEYS}?limit=100&cursor=bmV4dA`); +}); + +test("with no keys it says so and offers to create one", async () => { + server.use(getListApiKeysMockHandler({ apiKeys: [], nextCursor: null })); + const view = draw(); + + await view.findByText("No API keys yet"); + expect( + view.getAllByRole("button", { name: "Create key" }).length, + ).toBeGreaterThan(0); +}); + +test("creating a key sends its name with an Idempotency-Key, shows the key once with Copy, and it is gone after Done", async () => { + const sent: { key: string; body: unknown }[] = []; + const copied: string[] = []; + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { + writeText: async (text: string) => { + copied.push(text); + }, + }, + }); + server.use( + getCreateApiKeyMockHandler(async ({ request }) => { + sent.push({ + key: request.headers.get("idempotency-key") ?? "", + body: await request.json(), + }); + return getCreateApiKeyResponseMock(); + }), + ); + const secret = getCreateApiKeyResponseMock().key; + const view = draw(); + await view.findByText("Nightly report"); + + fireEvent.click(view.getByRole("button", { name: "Create key" })); + const name = await view.findByLabelText("Name"); + // Typed, not set: the box is a Base UI input, which reads keystrokes and not a `change` event. + await userEvent.type(name, " Deploy script "); + fireEvent.submit(name.closest("form") as HTMLFormElement); + + // The key, whole, once. + await view.findByText(secret); + expect(view.getByText(/can't see it again/)).toBeTruthy(); + expect(sent).toHaveLength(1); + expect(sent[0].body).toEqual({ name: "Deploy script" }); + expect(sent[0].key).toMatch(/^[0-9a-f]{32}$/); + expect(requests).toContain(`POST ${KEYS}`); + + fireEvent.click(view.getByRole("button", { name: "Copy" })); + await view.findByRole("button", { name: "Copied" }); + expect(copied).toEqual([secret]); + + fireEvent.click(view.getByRole("button", { name: "Done" })); + await waitFor(() => expect(view.queryByText(secret)).toBeNull()); + expect(document.body.textContent).not.toContain(secret); + // Nothing the app keeps holds it either. + expect(JSON.stringify(appQueryClient.getQueryCache().getAll())).not.toContain( + secret, + ); + expect( + JSON.stringify( + appQueryClient + .getMutationCache() + .getAll() + .map((mutation) => mutation.state), + ), + ).not.toContain(secret); +}); + +test("a name is needed before a key is made", async () => { + const view = draw(); + await view.findByText("Nightly report"); + + fireEvent.click(view.getByRole("button", { name: "Create key" })); + const name = await view.findByLabelText("Name"); + fireEvent.submit(name.closest("form") as HTMLFormElement); + + await settleReactWork(); + expect(requests.filter((line) => line.startsWith("POST"))).toEqual([]); +}); + +test("revoking asks first, then deletes the key and its row goes", async () => { + let keys = getListApiKeysResponseMock().apiKeys; + const deleted: { id: string; key: string }[] = []; + server.use( + getListApiKeysMockHandler(() => ({ apiKeys: keys, nextCursor: null })), + getDeleteApiKeyMockHandler(({ request, params }) => { + deleted.push({ + id: String(params.apiKeyId), + key: request.headers.get("idempotency-key") ?? "", + }); + keys = keys.filter((key) => key.id !== params.apiKeyId); + }), + ); + const view = draw(); + await view.findByText("Nightly report"); + + fireEvent.click(view.getByRole("button", { name: "Revoke Nightly report" })); + // Asked first: nothing is deleted by the row's button. + await view.findByText("Revoke Nightly report?"); + expect(deleted).toEqual([]); + + fireEvent.click(view.getByRole("button", { name: "Revoke" })); + await waitFor(() => expect(view.queryByText("Nightly report")).toBeNull()); + expect(deleted).toHaveLength(1); + expect(deleted[0].id).toBe("4b2c9e71d0a84f6b"); + expect(deleted[0].key).toMatch(/^[0-9a-f]{32}$/); + expect(requests).toContain(`DELETE ${KEYS}/4b2c9e71d0a84f6b`); + await view.findByText("No API keys yet"); +}); + +test("an OpenBot with no sign-in says it has no API keys, in a sentence and not as an error", async () => { + server.use( + http.get(`*${KEYS}`, () => + problem( + 503, + "SIGN_IN_UNAVAILABLE", + "This OpenBot signs nobody in, so it has no API keys.", + ), + ), + ); + const view = draw(); + + await view.findByText("API keys aren't available on this OpenBot"); + expect(view.queryByRole("alert")).toBeNull(); + expect(view.queryByRole("button", { name: "Create key" })).toBeNull(); +}); + +test("any other 503 is a failure to load, not the missing feature", async () => { + server.use( + http.get( + `*${KEYS}`, + () => new HttpResponse("bad gateway", { status: 503 }), + ), + ); + const view = draw(); + + // The app's client tries a failed read once more before it says so. + const alert = await view.findByRole("alert", {}, { timeout: 4000 }); + expect(alert.textContent).toContain("Couldn't load your API keys."); +}); + +test("refused for not being signed in on the web, in a browser it says where to create keys", async () => { + server.use( + http.get(`*${KEYS}`, () => + problem( + 403, + "PERMISSION_DENIED", + "An API key or an app can't manage API keys or sessions. Sign in to OpenBot to do this.", + ), + ), + ); + const view = draw(); + + await view.findByText("Create API keys from OpenBot in your browser."); + expect(view.queryByRole("alert")).toBeNull(); + expect(view.queryByRole("button", { name: "Create key" })).toBeNull(); + expect(view.queryByRole("button", { name: "Open in browser" })).toBeNull(); +}); + +test("refused in OpenBot Desktop, a button opens this page in the system browser", async () => { + const invoked: { command: string; args: unknown }[] = []; + (window as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__ = { + transformCallback: () => 0, + invoke: async (command: string, args: unknown) => { + invoked.push({ command, args }); + return null; + }, + }; + server.use( + http.get(`*${KEYS}`, () => + problem( + 403, + "PERMISSION_DENIED", + "An API key or an app can't manage API keys or sessions. Sign in to OpenBot to do this.", + ), + ), + ); + const view = draw(); + + await view.findByText("Create API keys from OpenBot in your browser."); + fireEvent.click(view.getByRole("button", { name: "Open in browser" })); + await waitFor(() => expect(invoked).toHaveLength(1)); + expect(invoked[0]).toEqual({ + command: "plugin:opener|open_url", + args: { url: "http://openbot.invalid/settings/api-keys" }, + }); +}); diff --git a/app/tests/settings-sidebar.test.ts b/app/tests/settings-sidebar.test.ts index 76034033a7..092911fafa 100644 --- a/app/tests/settings-sidebar.test.ts +++ b/app/tests/settings-sidebar.test.ts @@ -31,6 +31,15 @@ describe("settings sidebar", () => { expect(groups).toEqual([...groups].sort((a, b) => a - b)); }); + test("API keys is the person's own, last of You, in both editions", () => { + const you = SETTINGS_SIDEBAR_ITEMS.filter((item) => item.group === "you"); + const apiKeys = you[you.length - 1]; + + expect(apiKeys?.title).toBe("API keys"); + expect(apiKeys?.linkOptions).toEqual({ to: "/settings/api-keys" }); + expect(apiKeys?.personalOnly).toBeUndefined(); + }); + test("Routines, Memory, Skills and Learning are not in Settings: the first three are in the main menu", () => { const titles = SETTINGS_SIDEBAR_ITEMS.map((item) => item.title); for (const moved of ["Routines", "Memory", "Skills", "Learning"]) From 8ca2f9549bc7737f6cb1a13c9e42f144ed733eab Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 12:51:20 -0800 Subject: [PATCH 003/116] Let Desktop's setup connect to an OpenBot that runs elsewhere The first screen's OpenBot for Business choice can now be picked. It asks for the address of the OpenBot a company runs in place of what this computer needs and Install, then signs in through the browser. Nothing is installed or started on this computer for it. The booking link moves to that screen, for a company that has no OpenBot yet. OpenBot Cloud is still shown as coming soon, and Self-hosted is unchanged. Setup asks the shell where OpenBot runs before anything else. A saved connection opens that OpenBot, or shows the first screen with the address filled in and the reason the sign-in ended, and none of the checks, downloads or starts of an install on this computer run. A shell that does not know the question is an install on this computer, as before. What goes wrong is said in the shell's own sentence. The screen reads only its kind to choose what to offer: the field to fix, Try again, Sign in again, or opening that OpenBot in the browser. Use OpenBot on this computer instead goes back, and switches a saved connection first. --- desktop/src/App.test.tsx | 470 +++++++++++++++++++++++- desktop/src/App.tsx | 139 ++++++- desktop/src/ConnectToOpenBot.tsx | 322 ++++++++++++++++ desktop/src/Problem.tsx | 11 +- desktop/src/Welcome.tsx | 110 ++++-- desktop/src/setupLayout.browser.test.ts | 13 + desktop/src/styles.css | 82 ++++- desktop/src/telemetry.ts | 13 +- 8 files changed, 1114 insertions(+), 46 deletions(-) create mode 100644 desktop/src/ConnectToOpenBot.tsx diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index f3ee14f680..92ea038392 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -602,14 +602,15 @@ async function chooseOpenAi(view: Awaited>) { await userEvent.click(view.getByRole("button", { name: "Continue" })); } -test("the first screen offers Self-hosted, shows Cloud and Business greyed, and says what this computer needs and why", async () => { +test("the first screen offers Self-hosted and OpenBot for Business, shows Cloud greyed, and says what this computer needs and why", async () => { setupRootConfiguration("/tmp/local-eval-welcome", async () => emptyConfiguration(), ); withLocalCli({}); const view = await renderApp(); expect(view.getByRole("heading", { name: "Set up OpenBot" })).toBeTruthy(); - // Three ways to run OpenBot. This app sets up the first; the other two are there to be seen. + // Three ways to run OpenBot. This app sets up the first and connects to the third; OpenBot Cloud + // is there to be seen. const self = view.getByRole("radio", { name: /^Self-hosted/, }) as HTMLInputElement; @@ -621,7 +622,10 @@ test("the first screen offers Self-hosted, shows Cloud and Business greyed, and }) as HTMLInputElement; expect([self.checked, self.disabled]).toEqual([true, false]); expect([cloud.checked, cloud.disabled]).toEqual([false, true]); - expect([business.checked, business.disabled]).toEqual([false, true]); + expect([business.checked, business.disabled]).toEqual([false, false]); + expect(business.closest("label")?.textContent).toContain( + "For your whole team. Connect to the OpenBot your company runs.", + ); // What Self-hosted asks of this computer, and why: every part of OpenBot runs on it. expect( view.getByRole("heading", { name: "What this computer needs" }), @@ -642,13 +646,467 @@ test("the first screen offers Self-hosted, shows Cloud and Business greyed, and "4 CPU cores or more", "40 GB of free disk space", ]); - // The one booking link, never a scheduling page of its own, still live on the greyed row. + expect(buttons(view)).toEqual(["Install"]); + expectPlain(view); + expect(localCliCalls()).toEqual([]); +}); + +/* + * An OpenBot that runs elsewhere. The shell's commands, what they answer and the sentence for each + * thing that can go wrong are faked here exactly as the shell gives them: the window shows the + * sentence as given, and reads only its `kind` to choose what to offer. + */ +const ELSEWHERE = "https://openbot.example.com"; +const THIS_COMPUTER = { mode: "local", address: null, signedIn: false }; + +const CONNECT_PROBLEMS: Array<{ + kind: string; + said: string; + at: "check" | "connect"; + offer: "field" | "Try again" | "Sign in again" | "Open in browser"; +}> = [ + { + kind: "address-invalid", + at: "check", + offer: "field", + said: "That isn't an address OpenBot can connect to. Use one that starts with https://, such as https://openbot.example.com.", + }, + { + kind: "unreachable", + at: "check", + offer: "Try again", + said: "OpenBot couldn't reach openbot.example.com. Check the address and your network, then try again.", + }, + { + kind: "not-openbot", + at: "check", + offer: "field", + said: "There's no OpenBot at openbot.example.com. Check the address with whoever runs your OpenBot.", + }, + { + kind: "single-person", + at: "check", + offer: "field", + said: "The OpenBot at openbot.example.com is set up for one person on its own computer, so the app can't connect to it.", + }, + { + kind: "too-old", + at: "check", + offer: "Open in browser", + said: "The OpenBot at openbot.example.com is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser.", + }, + { + kind: "sign-in-cancelled", + at: "connect", + offer: "Sign in again", + said: "Sign-in didn't finish. Try again when you're ready.", + }, + { + kind: "sign-in-failed", + at: "connect", + offer: "Sign in again", + said: "OpenBot couldn't sign you in at openbot.example.com. Try again, or ask whoever runs your OpenBot.", + }, + { + kind: "session-ended", + at: "connect", + offer: "Sign in again", + said: "Your sign-in to openbot.example.com has ended. Sign in again to keep going.", + }, + { + kind: "credential-store", + at: "connect", + offer: "Try again", + said: "OpenBot couldn't save your sign-in on this computer. Unlock your keychain, then try again.", + }, +]; + +/** A first run on which the person picks OpenBot for Business: the connect screen. */ +async function chooseConnect(shell: Record = {}) { + setupRootConfiguration("/tmp/connect-elsewhere", async () => + emptyConfiguration(), + ); + withLocalCli({ + connection: THIS_COMPUTER, + record_setup_event: null, + ...shell, + }); + const view = await renderApp(); + await userEvent.click( + view.getByRole("radio", { name: /^OpenBot for Business/ }), + ); + return view; +} + +/** What the window asked the shell for, in order, leaving out what it counts for usage data. */ +function asked(from = 0) { + return invokeCalls + .slice(from) + .filter((call) => call.command !== "record_setup_event"); +} + +/** + * The shell of an app whose saved choice is an OpenBot that runs elsewhere. It answers `answers`, + * and anything else the window asks for, which is every command of an install on this computer, is + * a stray: the test fails on one. + */ +function connectedShell(answers: Record) { + const strays: string[] = []; + invokeHandler = async (command, args) => { + if (command in answers) { + const answer = answers[command]; + return typeof answer === "function" ? answer(args) : answer; + } + if (command === "record_setup_event") return null; + strays.push(command); + throw new Error(`a connected app asked for ${command}`); + }; + return strays; +} + +test("choosing OpenBot for Business asks for an address in place of Install, and going back brings Install back", async () => { + const view = await chooseConnect(); + const business = view.getByRole("radio", { + name: /^OpenBot for Business/, + }) as HTMLInputElement; + expect(business.checked).toBe(true); + const field = view.getByLabelText("OpenBot address") as HTMLInputElement; + expect(field.placeholder).toBe("https://openbot.example.com"); + expect(field.value).toBe(""); + expect( + view.getByText( + "You'll sign in to it in your browser. Nothing is installed on this computer.", + ), + ).toBeTruthy(); + // What Self-hosted asks of this computer, and its Install, are not this choice's. + expect(buttons(view)).toEqual([ + "Connect", + "Use OpenBot on this computer instead", + ]); + expect( + view.queryByRole("heading", { name: "What this computer needs" }), + ).toBeNull(); + expect(view.queryByText(/Setup takes/)).toBeNull(); + // Nothing to connect to until an address is typed. + expect(view.getByRole("button", { name: "Connect" })).toHaveProperty( + "disabled", + true, + ); + // The one booking link, for somebody whose company has no OpenBot yet. + expect(view.getByText(/Don't have one yet\?/)).toBeTruthy(); expect( view.getByRole("link", { name: "Book a demo" }).getAttribute("href"), ).toBe("https://open.bot/business"); - expect(buttons(view)).toEqual(["Install"]); + // OpenBot Cloud is still to come. + expect(view.getByRole("radio", { name: /^OpenBot Cloud/ })).toHaveProperty( + "disabled", + true, + ); expectPlain(view); - expect(localCliCalls()).toEqual([]); + // Back, by the control that says so, and by the row itself. + await userEvent.type(field, "openbot.example.com"); + await userEvent.click( + view.getByRole("button", { name: "Use OpenBot on this computer instead" }), + ); + expect(buttons(view)).toEqual(["Install"]); + await userEvent.click(business); + // What was typed is still there. + expect( + (view.getByLabelText("OpenBot address") as HTMLInputElement).value, + ).toBe("openbot.example.com"); + await userEvent.click(view.getByRole("radio", { name: /^Self-hosted/ })); + expect(buttons(view)).toEqual(["Install"]); + expect( + view.getByRole("heading", { name: "What this computer needs" }), + ).toBeTruthy(); + // The saved choice was this computer all along: there was nothing to switch back from. + expect(asked().map((call) => call.command)).not.toContain( + "use_this_computer", + ); +}); + +test("a good address signs in through the browser, and nothing on this computer is asked for", async () => { + const signIn = deferred(); + const view = await chooseConnect({ + check_openbot_address: { address: ELSEWHERE }, + connect_to_openbot: () => signIn.promise, + }); + const from = invokeCalls.length; + const field = view.getByLabelText("OpenBot address") as HTMLInputElement; + // No scheme: the shell takes it as https, and the window does not refuse it first. + await userEvent.type(field, "openbot.example.com{Enter}"); + expect( + await view.findByText("Finish signing in in your browser."), + ).toBeTruthy(); + // The address as the shell understood it, and Cancel as the only control while it waits. + expect(field.value).toBe(ELSEWHERE); + expect(buttons(view)).toEqual(["Cancel"]); + await act(async () => signIn.resolve(null)); + expect(view.getByText("Opening OpenBot…")).toBeTruthy(); + expect(view.queryAllByRole("button")).toEqual([]); + expect(view.queryByRole("alert")).toBeNull(); + expect(asked(from)).toEqual([ + { + command: "check_openbot_address", + args: { address: "openbot.example.com" }, + }, + { command: "connect_to_openbot", args: { address: ELSEWHERE } }, + ]); + // The screen is counted, and the address never is. + expect(setupEvents()).toContainEqual({ + event: { kind: "step_viewed", step: "connect_openbot" }, + }); + expect(JSON.stringify(setupEvents())).not.toContain("openbot.example.com"); +}); + +for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { + test(`${kind}: the screen says the shell's sentence and offers ${offer === "field" ? "the field to fix" : offer}`, async () => { + let checks = 0; + let signIns = 0; + const view = await chooseConnect({ + check_openbot_address: () => { + checks += 1; + if (at === "check") throw { said, kind }; + return { address: ELSEWHERE }; + }, + connect_to_openbot: () => { + signIns += 1; + throw { said, kind }; + }, + "plugin:opener|open_url": null, + }); + const field = view.getByLabelText("OpenBot address") as HTMLInputElement; + await userEvent.type(field, `${ELSEWHERE}{Enter}`); + const alert = await view.findByRole("alert"); + expect(alert.textContent).toContain(said); + // The address is still there, to fix or to try again with. + expect(field.value).toBe(ELSEWHERE); + if (offer === "field") { + expect(alert.textContent).toBe(said); + expect(document.activeElement).toBe(field); + expect(field.getAttribute("aria-invalid")).toBe("true"); + expect(buttons(view)).toEqual([ + "Connect", + "Use OpenBot on this computer instead", + ]); + // A sentence about the address goes once the address changes. + await userEvent.type(field, "x"); + expect(view.queryByRole("alert")).toBeNull(); + expect(field.getAttribute("aria-invalid")).toBeNull(); + } else if (offer === "Open in browser") { + const link = view.getByRole("link", { name: "Open in browser" }); + expect(link.getAttribute("href")).toBe(ELSEWHERE); + await userEvent.click(link); + expect(invokeCalls).toContainEqual({ + command: "plugin:opener|open_url", + args: { url: ELSEWHERE }, + }); + expect(view.getByRole("button", { name: "Connect" })).toBeTruthy(); + } else { + // One way on, and it says what it does. + expect(view.queryByRole("button", { name: "Connect" })).toBeNull(); + await userEvent.click(view.getByRole("button", { name: offer })); + await waitFor(() => expect(at === "check" ? checks : signIns).toBe(2)); + } + }); +} + +test("Cancel while the browser is waited on stops the sign-in and gives the form back", async () => { + const signIn = deferred(); + const view = await chooseConnect({ + check_openbot_address: { address: ELSEWHERE }, + connect_to_openbot: () => signIn.promise, + cancel_connect: null, + }); + const field = view.getByLabelText("OpenBot address") as HTMLInputElement; + await userEvent.type(field, `${ELSEWHERE}{Enter}`); + await view.findByText("Finish signing in in your browser."); + await userEvent.click(view.getByRole("button", { name: "Cancel" })); + expect( + invokeCalls.filter((call) => call.command === "cancel_connect"), + ).toHaveLength(1); + expect(view.queryByText("Finish signing in in your browser.")).toBeNull(); + expect(view.getByRole("button", { name: "Connect" })).toHaveProperty( + "disabled", + false, + ); + expect(field.value).toBe(ELSEWHERE); + // The shell then ends the sign-in it was asked to stop. The person chose that: nothing is + // announced, and the field is where they are. + await act(async () => + signIn.reject({ + said: "Sign-in didn't finish. Try again when you're ready.", + kind: "sign-in-cancelled", + }), + ); + expect(view.queryByRole("alert")).toBeNull(); + expect(document.activeElement).toBe(field); +}); + +test("a launch that is connected and signed in opens OpenBot and asks nothing of this computer", async () => { + const strays = connectedShell({ + connection: { mode: "connected", address: ELSEWHERE, signedIn: true }, + show_connected: null, + }); + // The development double mount included: OpenBot is opened once. + const view = await renderApp(true); + expect(invokeCalls.map((call) => call.command)).toEqual([ + "connection", + "show_connected", + ]); + expect(view.getByRole("status").textContent).toBe("Opening OpenBot…"); + expect(view.queryAllByRole("button")).toEqual([]); + expect(strays).toEqual([]); +}); + +test("a launch after the sign-in ended says so once, with the address filled in and Sign in again", async () => { + const said = + "Your sign-in to openbot.example.com has ended. Sign in again to keep going."; + let notices = 0; + const strays = connectedShell({ + connection: { mode: "connected", address: ELSEWHERE, signedIn: false }, + // Answered once, as the shell does. + take_connection_notice: () => { + notices += 1; + return notices === 1 ? { kind: "session-ended", message: said } : null; + }, + check_openbot_address: { address: ELSEWHERE }, + connect_to_openbot: () => new Promise(() => {}), + }); + const view = await renderApp(true); + expect(view.getByRole("heading", { name: "Set up OpenBot" })).toBeTruthy(); + expect( + view.getByRole("radio", { name: /^OpenBot for Business/ }), + ).toHaveProperty("checked", true); + expect( + (view.getByLabelText("OpenBot address") as HTMLInputElement).value, + ).toBe(ELSEWHERE); + expect(view.getByRole("alert").textContent).toBe(said); + expect(notices).toBe(1); + expect(view.queryByRole("button", { name: "Install" })).toBeNull(); + expect(view.queryByRole("button", { name: "Connect" })).toBeNull(); + await userEvent.click(view.getByRole("button", { name: "Sign in again" })); + await view.findByText("Finish signing in in your browser."); + expect(view.queryByRole("alert")).toBeNull(); + expect(asked().map((call) => call.command)).toEqual([ + "connection", + "take_connection_notice", + "check_openbot_address", + "connect_to_openbot", + ]); + expect(setupEvents()).toEqual([ + { event: { kind: "step_viewed", step: "connect_openbot" } }, + ]); + expect(strays).toEqual([]); +}); + +test("asked from Settings to choose where OpenBot runs, the first screen opens on the connect choice with the address and no failure", async () => { + setupRootConfiguration("/tmp/choose-again", async () => emptyConfiguration()); + withLocalCli({ + connection: { mode: "connected", address: ELSEWHERE, signedIn: false }, + take_connection_notice: { kind: "choose", message: null }, + use_this_computer: null, + record_setup_event: null, + }); + const view = await renderApp(); + expect(view.getByRole("heading", { name: "Set up OpenBot" })).toBeTruthy(); + expect( + view.getByRole("radio", { name: /^OpenBot for Business/ }), + ).toHaveProperty("checked", true); + expect( + (view.getByLabelText("OpenBot address") as HTMLInputElement).value, + ).toBe(ELSEWHERE); + expect(view.queryByRole("alert")).toBeNull(); + expect(buttons(view)).toEqual([ + "Connect", + "Use OpenBot on this computer instead", + ]); + // Nothing of an install on this computer has been asked for yet. + expect(asked().map((call) => call.command)).toEqual([ + "connection", + "take_connection_notice", + ]); + // Picking Self-hosted switches the saved choice, then setup carries on as it does today. + await userEvent.click(view.getByRole("radio", { name: /^Self-hosted/ })); + await view.findByRole("button", { name: "Install" }); + const commands = asked().map((call) => call.command); + expect(commands.indexOf("use_this_computer")).toBe(2); + expect(commands).toContain("already_configured"); +}); + +test("a saved sign-in that can't open OpenBot says why on the connect screen, and Try again opens it without signing in again", async () => { + const said = + "OpenBot couldn't reach openbot.example.com. Check the address and your network, then try again."; + let shows = 0; + const strays = connectedShell({ + connection: { mode: "connected", address: ELSEWHERE, signedIn: true }, + show_connected: () => { + shows += 1; + if (shows === 1) throw { said, kind: "unreachable" }; + return new Promise(() => {}); + }, + }); + const view = await renderApp(); + expect((await view.findByRole("alert")).textContent).toContain(said); + expect( + (view.getByLabelText("OpenBot address") as HTMLInputElement).value, + ).toBe(ELSEWHERE); + await userEvent.click(view.getByRole("button", { name: "Try again" })); + await view.findByText("Opening OpenBot…"); + expect(asked().map((call) => call.command)).toEqual([ + "connection", + "show_connected", + "show_connected", + ]); + expect(strays).toEqual([]); +}); + +test("Use OpenBot on this computer instead switches a saved connection back, and setup carries on as a first run", async () => { + setupRootConfiguration("/tmp/back-to-this-computer", async () => + emptyConfiguration(), + ); + withLocalCli({ + connection: { mode: "connected", address: ELSEWHERE, signedIn: false }, + take_connection_notice: null, + use_this_computer: null, + record_setup_event: null, + }); + const view = await renderApp(); + // Connected: nothing of an install on this computer has been asked for. + expect(asked().map((call) => call.command)).toEqual([ + "connection", + "take_connection_notice", + ]); + await userEvent.click( + view.getByRole("button", { name: "Use OpenBot on this computer instead" }), + ); + await view.findByRole("button", { name: "Install" }); + const commands = asked().map((call) => call.command); + expect(commands.indexOf("use_this_computer")).toBe(2); + expect(commands.indexOf("default_root")).toBeGreaterThan(2); + expect(view.getByRole("radio", { name: /^Self-hosted/ })).toHaveProperty( + "checked", + true, + ); + expect( + view.getByRole("heading", { name: "What this computer needs" }), + ).toBeTruthy(); + // The address is still there for somebody who changes their mind. + await userEvent.click( + view.getByRole("radio", { name: /^OpenBot for Business/ }), + ); + expect( + (view.getByLabelText("OpenBot address") as HTMLInputElement).value, + ).toBe(ELSEWHERE); +}); + +test("a person who went back to this computer finds the address they connected to if they pick connect again", async () => { + const view = await chooseConnect({ + connection: { mode: "local", address: ELSEWHERE, signedIn: false }, + }); + expect( + (view.getByLabelText("OpenBot address") as HTMLInputElement).value, + ).toBe(ELSEWHERE); }); test("the first screen says nothing about usage data: that is the last screen's choice", async () => { diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index 7dbcdf8836..efd68b81f1 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -113,7 +113,139 @@ export function App() { return ; } +/** Where OpenBot runs, as the shell has it saved (`connection`). */ +type Connection = { + mode: "local" | "connected"; + address: string | null; + /** A sign-in for that address is kept on this computer. */ + signedIn: boolean; +}; + +/** Said once by the shell when it put this window back: why, or `choose` to pick again. */ +type ConnectionNotice = { kind: string; message: string | null }; + +type Launch = + | { at: "asking" } + /** OpenBot on this computer: setup as it has always been. */ + | { at: "local"; address: string } + /** Signed in to an OpenBot that runs elsewhere, which the shell is opening. */ + | { at: "opening" } + /** The first screen with that OpenBot's address, to sign in to it again or choose otherwise. */ + | { + at: "connect"; + address: string; + problem: Problem | null; + reopen: boolean; + }; + +/** + * Asks where OpenBot runs before anything else. On this computer, setup carries on exactly as it + * did (`LocalSetup`). Connected to an OpenBot that runs elsewhere, none of that is mounted, so + * nothing about an install on this computer is asked for, downloaded or started: the shell opens + * that OpenBot, or the first screen shows its address to sign in to again. + * + * A shell from before this choice does not know `connection`: that is OpenBot on this computer. + */ function Setup() { + const [launch, setLaunch] = useState({ at: "asking" }); + // Asked once, the development double mount included: the shell answers its notice only once. + const asked = useRef(false); + const alive = useRef(true); + useEffect(() => { + alive.current = true; + if (!asked.current) { + asked.current = true; + void (async () => { + const found = await invoke("connection").catch(() => null); + if (!alive.current) return; + const address = found?.address ?? ""; + if (found?.mode !== "connected") { + setLaunch({ at: "local", address }); + return; + } + if (found.signedIn) { + setLaunch({ at: "opening" }); + try { + await invoke("show_connected"); + } catch (error) { + if (alive.current) + setLaunch({ + at: "connect", + address, + problem: asProblem(error), + reopen: true, + }); + } + return; + } + const notice = await invoke( + "take_connection_notice", + ).catch(() => null); + if (!alive.current) return; + setLaunch({ + at: "connect", + address, + // `choose` is the person asking to pick again from Settings: nothing went wrong. + problem: notice?.message + ? { said: notice.message, kind: notice.kind } + : null, + reopen: false, + }); + })(); + } + return () => { + alive.current = false; + }; + }, []); + const connecting = launch.at === "connect"; + useEffect(() => { + if (connecting) + recordSetupEvent({ kind: "step_viewed", step: "connect_openbot" }); + }, [connecting]); + + if (launch.at === "local") return ; + if (launch.at === "connect") { + const { address } = launch; + return ( +
+ {}} + // The saved choice goes back to this computer, then setup carries on as a first run. + onThisComputer={async () => { + await invoke("use_this_computer"); + setLaunch({ at: "local", address }); + }} + saved={{ + address, + problem: launch.problem, + reopen: launch.reopen + ? () => invoke("show_connected") + : undefined, + }} + onInstall={() => {}} + /> +
+ ); + } + return ( +
+
+

Getting OpenBot ready

+ {launch.at === "opening" ? ( + Opening OpenBot… + ) : ( +

+ Checking your saved setup… +

+ )} +
+
+ ); +} + +/** Setup of OpenBot on this computer. `address`: an OpenBot connected to before, if any. */ +function LocalSetup({ address }: { address: string }) { const [blocker, setBlocker] = useState(null); // A Windows fix made earlier that only counts once Windows has restarted, and it has not. const [restartPending, setRestartPending] = useState(false); @@ -937,10 +1069,15 @@ function Setup() { * Skipped entirely when a stack is already up: somebody returning to a running OpenBot is not * setting one up. */ - if (!running && step === "welcome") { + if (!running && (step === "welcome" || step === "connect_openbot")) { return (
setStep("connect_openbot")} + onThisComputer={() => setStep("welcome")} + saved={{ address }} onInstall={() => { // The default Bot, recorded as a choice of it would be. recordSetupEvent(harnessChoiceEvent(DEFAULT_HARNESS)); diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx new file mode 100644 index 0000000000..89623cc7f5 --- /dev/null +++ b/desktop/src/ConnectToOpenBot.tsx @@ -0,0 +1,322 @@ +import { invoke } from "@tauri-apps/api/core"; +import { useEffect, useId, useRef, useState } from "react"; +import { ExternalLink } from "./ExternalLink"; +import { asProblem, Failure, type Problem } from "./Problem"; +import { StatusLine } from "./SetupProgress"; + +/** OpenBot's one booking link. */ +export const BOOK_A_DEMO = "https://open.bot/business"; + +/** + * What the screen offers after something went wrong, chosen by the problem's `kind`. The sentence + * is the shell's, shown as given. + * + * `field`: the address is what to fix, so the sentence sits under the field and the field has the + * focus. `sign-in` and `retry`: the screen's one button says Sign in again or Try again. `browser`: + * this app can't connect to that OpenBot, and a link opens it in the browser. A kind this app does + * not know is offered Try again. + */ +type Offer = "field" | "retry" | "sign-in" | "browser"; + +function offerFor(kind: string | null | undefined): Offer { + switch (kind) { + case "address-invalid": + case "not-openbot": + case "single-person": + return "field"; + case "too-old": + return "browser"; + case "sign-in-cancelled": + case "sign-in-failed": + case "session-ended": + return "sign-in"; + default: + return "retry"; + } +} + +/** Nothing failed: the sign-in stopped or ended, and signing in again is all there is to do. */ +function isNotice(kind: string | null | undefined) { + return kind === "sign-in-cancelled" || kind === "session-ended"; +} + +/** The typed address as a link the browser can open. The shell takes no scheme as https too. */ +function browserAddress(address: string) { + const typed = address.trim(); + return /^https?:\/\//i.test(typed) ? typed : `https://${typed}`; +} + +type Phase = "idle" | "checking" | "waiting" | "opening" | "leaving"; + +/** What went wrong, and what the screen offers for it. `null` offers nothing of its own. */ +type Trouble = { problem: Problem; offer: Offer | null }; + +export type Connecting = ReturnType; + +/** + * Connecting this app to an OpenBot that runs elsewhere: the address, the sign-in in the person's + * browser, and what went wrong. Held by the first screen, above the choice of where OpenBot runs, + * so an address typed is still there after a look at the other choice. + * + * The shell does the work. `check_openbot_address` says whether there is an OpenBot this app can + * connect to at the address, and gives it back as it understood it. `connect_to_openbot` opens the + * browser, waits for the sign-in and then shows that OpenBot in this window. Nothing is installed + * or started on this computer. + */ +export function useConnectToOpenBot({ + address: remembered = "", + problem: found = null, + reopen, + onThisComputer, +}: { + /** The address connected to before, when there is one. */ + address?: string; + /** What the launch found: a sign-in that ended, or an OpenBot it could not open. */ + problem?: Problem | null; + /** + * Opens OpenBot with the sign-in this computer already has. Given when the launch tried that and + * it failed: Try again does it again, without a new sign-in, while the address is the same. + */ + reopen?: () => Promise; + /** Back to OpenBot on this computer. May fail, when a saved connection has to be switched. */ + onThisComputer: () => void | Promise; +}) { + const [address, setAddress] = useState(remembered); + const [phase, setPhase] = useState("idle"); + const [trouble, setTrouble] = useState( + found ? { problem: found, offer: offerFor(found.kind) } : null, + ); + const [reopens, setReopens] = useState(Boolean(reopen)); + // Each go at connecting: one that was cancelled or left behind says nothing when it ends. + const attempt = useRef(0); + const waiting = useRef(false); + const alive = useRef(true); + const field = useRef(null); + const action = useRef(null); + // Where the focus goes once the form is back: it was on a control that was disabled meanwhile. + const [focus, setFocus] = useState<{ on: "field" | "action" } | null>(null); + useEffect(() => { + if (!focus) return; + (focus.on === "field" ? field : action).current?.focus(); + }, [focus]); + + useEffect(() => { + alive.current = true; + return () => { + alive.current = false; + // Leaving the screen while the browser is waited on stops that sign-in. + if (waiting.current) { + waiting.current = false; + invoke("cancel_connect").catch(() => {}); + } + }; + }, []); + + async function submit() { + const typed = address.trim(); + if (!typed || phase !== "idle") return; + attempt.current += 1; + const mine = attempt.current; + const current = () => alive.current && attempt.current === mine; + setTrouble(null); + try { + if (reopens && reopen) { + setPhase("opening"); + await reopen(); + return; + } + setPhase("checking"); + const checked = await invoke<{ address: string }>( + "check_openbot_address", + { address: typed }, + ); + if (!current()) return; + setAddress(checked.address); + setPhase("waiting"); + waiting.current = true; + await invoke("connect_to_openbot", { address: checked.address }); + if (!current()) return; + waiting.current = false; + // Signed in: the shell is showing that OpenBot in this window. + setPhase("opening"); + } catch (error) { + if (!current()) return; + waiting.current = false; + const problem = asProblem(error); + const offer = offerFor(problem.kind); + setTrouble({ problem, offer }); + // Only Try again opens it with the sign-in this computer has: any other way on signs in anew. + if (offer !== "retry") setReopens(false); + setPhase("idle"); + // To the field when the address is what to fix, to the button when it is the way on. + if (offer !== "browser") + setFocus({ on: offer === "field" ? "field" : "action" }); + } + } + + /** Stops the sign-in the browser is waited on for. The person chose it, so nothing is said. */ + async function cancel() { + attempt.current += 1; + waiting.current = false; + setPhase("idle"); + setFocus({ on: "field" }); + await invoke("cancel_connect").catch(() => {}); + } + + async function leave() { + if (phase !== "idle") return; + setTrouble(null); + setPhase("leaving"); + try { + await onThisComputer(); + } catch (error) { + if (alive.current) setTrouble({ problem: asProblem(error), offer: null }); + } finally { + if (alive.current) setPhase("idle"); + } + } + + return { + address, + phase, + trouble, + busy: phase !== "idle", + field, + action, + /** A sentence about the address, or about opening it, is not about the next one typed. */ + change(next: string) { + setAddress(next); + setTrouble(null); + setReopens(false); + }, + submit, + cancel, + leave, + }; +} + +/** + * The first screen's lower half when OpenBot runs elsewhere: one field for its address, what + * happens next, and Connect. While the browser is waited on, Cancel is the only control. + */ +export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) { + const id = useId(); + const { address, phase, trouble, busy } = connecting; + const underField = trouble?.offer === "field"; + return ( +
{ + event.preventDefault(); + void connecting.submit(); + }} + > +
+ + connecting.change(event.target.value)} + /> + {trouble && underField && ( + + )} +
+ {phase === "waiting" ? ( + <> + Finish signing in in your browser. +
+ +
+ + ) : phase === "opening" ? ( + Opening OpenBot… + ) : ( + <> +

+ You'll sign in to it in your browser. Nothing is installed on this + computer. +

+ {trouble && !underField && ( + + )} +
+ +
+ {phase === "checking" && ( + Checking the address… + )} +

+ Don't have one yet?{" "} + Book a demo. +

+ + + )} + + ); +} + +/** The sentence, in the card: a notice when nothing failed, the window's failure when it did. */ +function Trouble({ trouble, address }: { trouble: Trouble; address: string }) { + const { problem, offer } = trouble; + if (isNotice(problem.kind)) { + return ( +
+

{problem.said}

+
+ ); + } + return ( + + {offer === "browser" && address.trim() && ( + + Open in browser + + )} + + ); +} diff --git a/desktop/src/Problem.tsx b/desktop/src/Problem.tsx index 2268095043..53318136ae 100644 --- a/desktop/src/Problem.tsx +++ b/desktop/src/Problem.tsx @@ -1,5 +1,5 @@ import { invoke } from "@tauri-apps/api/core"; -import { useState } from "react"; +import { type ReactNode, useState } from "react"; import { ExternalLink } from "./ExternalLink"; /** @@ -21,6 +21,11 @@ export type Problem = { leftover_containers?: string[] | null; /** Only a Windows restart fixes this: the window offers one instead of Try again. */ restart_windows?: boolean | null; + /** + * Which thing went wrong while connecting to an OpenBot that runs elsewhere. The window reads it + * only to choose what to offer next (`ConnectToOpenBot`); the sentence is still `said`. + */ + kind?: string | null; }; /** Anything thrown, as a problem. A bare string keeps working and reads as it always did. */ @@ -158,13 +163,16 @@ export function TroubleshootingLogs({ /** * `onRetry`, where the screen has no other way to run what failed again: Try again, in the card. * The install behind the account step had none, and its failure sat there with nothing to press. + * `children`, where the way on is something other than Try again: it takes that button's place. */ export function Failure({ problem, onRetry, + children, }: { problem: Problem; onRetry?: () => void; + children?: ReactNode; }) { return (
@@ -177,6 +185,7 @@ export function Failure({
)} + {children &&
{children}
} {/* The real output, kept but not the headline. Whoever is debugging opens this; the person reading the sentence above never has to. */} {problem.detail && ( diff --git a/desktop/src/Welcome.tsx b/desktop/src/Welcome.tsx index a702ff5ff2..566872faf3 100644 --- a/desktop/src/Welcome.tsx +++ b/desktop/src/Welcome.tsx @@ -1,14 +1,14 @@ import { IconBuilding, IconCloud, IconDeviceLaptop } from "@tabler/icons-react"; import { type ReactNode, useState } from "react"; +import { ConnectToOpenBot, useConnectToOpenBot } from "./ConnectToOpenBot"; import { EarlyDownloadsLine, earlyDownloadsMeasured, useEarlyDownloads, } from "./EarlyDownloads"; -import { ExternalLink } from "./ExternalLink"; +import type { Problem } from "./Problem"; -/** OpenBot's one booking link. */ -export const BOOK_A_DEMO = "https://open.bot/business"; +export { BOOK_A_DEMO } from "./ConnectToOpenBot"; /** * The least a computer needs to run every part of OpenBot itself. @@ -25,19 +25,24 @@ export const SELF_HOSTED_NEEDS = [ "40 GB of free disk space", ] as const; +/** Where OpenBot runs: on this computer, or at an address this app connects to. */ +export type Hosting = "self-hosted" | "connect"; + /** * Where OpenBot runs, and what that asks of this computer, before it asks for anything else. * - * In this order: the three ways to run OpenBot, of which only Self-hosted can be chosen here - * (OpenBot Cloud and OpenBot for Business are shown greyed, Business with the one booking link); - * all of it fits the window's default size (1000×800, less a title bar) with no scrollbar; - * what this computer needs for Self-hosted and why, which is that every part of OpenBot runs on it; - * then how long setup takes. Usage data is not said here: it is the last screen's choice - * (`UsageDataChoice`). + * First the three ways to run OpenBot, of which two can be chosen here: Self-hosted runs + * everything on this computer, and OpenBot for Business connects this app to the OpenBot a company + * runs, at its address. OpenBot Cloud is shown greyed. Then what the choice needs. For Self-hosted + * that is what this computer needs and why, which is that every part of OpenBot runs on it, how + * long setup takes, and Install. For OpenBot for Business it is the address and Connect + * (`ConnectToOpenBot`), with the one booking link for a company that has no OpenBot yet. Either + * way it fits the window's default size (1000×800, less a title bar) with no scrollbar. Usage data + * is not said here: it is the last screen's choice (`UsageDataChoice`). * - * The big downloads start while this screen shows, before Install is clicked, and its line says how - * far they are (`EarlyDownloadsLine`). Once they are done it says nothing: Install is the next step - * either way. + * The big downloads start while this screen shows with Self-hosted chosen, before Install is + * clicked, and its line says how far they are (`EarlyDownloadsLine`). Once they are done it says + * nothing: Install is the next step either way. * * On a disk too full for OpenBot, Install waits with the line that says so, and is there once the * download starts by itself. On Windows F it was pressable at 15 GB free: it built OpenBot's machine, @@ -45,23 +50,30 @@ export const SELF_HOSTED_NEEDS = [ * downloads have looked at the disk asks them first (`earlyDownloadsMeasured`). */ export function Welcome({ + hosting, + onConnect, + onThisComputer, + saved, onInstall, failure, }: { + hosting: Hosting; + /** OpenBot for Business was picked. */ + onConnect: () => void; + /** Self-hosted was picked again. May fail, when a saved connection has to be switched first. */ + onThisComputer: () => void | Promise; + /** What is known of an OpenBot connected to before (`useConnectToOpenBot`). */ + saved?: { + address?: string; + problem?: Problem | null; + reopen?: () => Promise; + }; onInstall: () => void; - /** A failure from setup itself, shown inside this card rather than under it. */ + /** A failure from setup on this computer, shown inside this card rather than under it. */ failure?: ReactNode; }) { - const downloads = useEarlyDownloads(); - const [checking, setChecking] = useState(false); - const short = downloads?.state === "short"; - const install = () => { - setChecking(true); - void earlyDownloadsMeasured().then((now) => { - setChecking(false); - if (now?.state !== "short") onInstall(); - }); - }; + const connecting = useConnectToOpenBot({ ...saved, onThisComputer }); + const connect = hosting === "connect"; return (
@@ -76,14 +88,20 @@ export function Welcome({

Set up OpenBot

Where OpenBot runs -
+ {connect ? ( + + ) : ( + + )} +
+ ); +} + +/** What Self-hosted asks of this computer and why, how long setup takes, and Install. */ +function SelfHosted({ + onInstall, + failure, +}: { + onInstall: () => void; + failure?: ReactNode; +}) { + const downloads = useEarlyDownloads(); + const [checking, setChecking] = useState(false); + const short = downloads?.state === "short"; + const install = () => { + setChecking(true); + void earlyDownloadsMeasured().then((now) => { + setChecking(false); + if (now?.state !== "short") onInstall(); + }); + }; + return ( + <>

What this computer needs

@@ -149,7 +195,7 @@ export function Welcome({

{failure} - + ); } diff --git a/desktop/src/setupLayout.browser.test.ts b/desktop/src/setupLayout.browser.test.ts index 855669c223..0ff436134a 100644 --- a/desktop/src/setupLayout.browser.test.ts +++ b/desktop/src/setupLayout.browser.test.ts @@ -739,6 +739,19 @@ describe.skipIf(!asked)("the first screen at the window's default size", () => { return card.scrollHeight - card.clientHeight; }); expect(overflow).toBeLessThanOrEqual(0); + // And with the other choice picked, OpenBot for Business: its address field and Connect. + await page.getByText("OpenBot for Business").click(); + await page.getByLabel("OpenBot address", { exact: true }).waitFor(); + await page.waitForTimeout(400); + expect( + await page.evaluate(() => { + const card = document.querySelector("main > .sheet") as HTMLElement; + return card.scrollHeight - card.clientHeight; + }), + ).toBeLessThanOrEqual(0); + expect(await page.getByRole("button", { name: "Connect" }).count()).toBe( + 1, + ); } finally { await page.close(); } diff --git a/desktop/src/styles.css b/desktop/src/styles.css index 9ba21523f4..87c6e6e410 100644 --- a/desktop/src/styles.css +++ b/desktop/src/styles.css @@ -732,9 +732,9 @@ button.text-link.change-provider { } /* - * The ways to run OpenBot, on the first screen. Self-hosted is the one this app sets up; OpenBot - * Cloud and OpenBot for Business are shown so a person knows they exist, greyed and not choosable. - * Business's booking link stays live, and keeps the pointer every link has. + * The ways to run OpenBot, on the first screen. Self-hosted is the one this app sets up, and + * OpenBot for Business is the one it connects to. OpenBot Cloud is shown so a person knows it + * exists, greyed and not choosable. */ fieldset.picker.hosting { max-height: none; @@ -766,6 +766,76 @@ fieldset.picker.hosting .tile.unavailable .mark-tile { opacity: 0.45; } +/* Not choosable for now, while an address is checked or the browser is waited on: Cancel is. */ +fieldset.picker.hosting .tile.held, +fieldset.picker.hosting .tile.held:hover, +fieldset.picker.hosting .tile.held:active { + cursor: default; + background: var(--card); +} + +/* + * OpenBot for Business, under the choices: the address of the OpenBot to connect to, what happens + * next under the field, then Connect. What went wrong with the address is said under the field, + * in the destructive colour; anything else is said in a card between the field and the button. + */ +.connect-to-openbot .field { + margin: 8px 0 0; +} + +/* Held while it is checked or signed in to: still readable, on the ground of a field at rest. */ +.connect-to-openbot .field input:read-only { + background: var(--muted); +} + +.address-problem { + margin: 6px 0 0; + font-size: var(--text-sm); + line-height: 20px; + overflow-wrap: anywhere; +} + +.connect-to-openbot .footnote { + margin-top: 8px; +} + +/* A sign-in that stopped or ended: the card that waits on the person, with the sentence in ink. */ +.connect-to-openbot .local-alert { + margin: 16px 0 0; +} + +.connect-to-openbot .local-alert p { + color: var(--text-primary); +} + +.connect-to-openbot .blocker p, +.connect-to-openbot .local-alert p { + overflow-wrap: anywhere; +} + +/* A link that is the way on, drawn as the app's `outline` button. */ +a.button-link { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 40px; + padding: 0 14px; + border-radius: var(--r-card); + border: 1px solid var(--border); + background: var(--background); + color: var(--text-primary); + font-size: var(--text-sm); + line-height: 1; + font-weight: 500; + text-decoration: none; + white-space: nowrap; + transition: background-color 150ms ease-out; +} + +a.button-link:hover { + background: var(--muted); +} + /* What Self-hosted asks of this computer: the reason, then the four needs, two to a line. */ .needs .lede { margin-bottom: 6px; @@ -1871,13 +1941,15 @@ a:hover { /* The app's dark `outline` button: `dark:bg-input/30`, a shade above the card. */ button.quiet, - button.another-question { + button.another-question, + a.button-link { background: color-mix(in srgb, var(--input) 30%, transparent); border-color: var(--input); } button.quiet:hover:not(:disabled), - button.another-question:hover:not(:disabled) { + button.another-question:hover:not(:disabled), + a.button-link:hover { background: color-mix(in srgb, var(--input) 50%, transparent); } diff --git a/desktop/src/telemetry.ts b/desktop/src/telemetry.ts index 07d201805c..96882cc984 100644 --- a/desktop/src/telemetry.ts +++ b/desktop/src/telemetry.ts @@ -1,7 +1,18 @@ import { invoke } from "@tauri-apps/api/core"; import type { ModelChoice } from "./ProviderPicker"; -export type SetupStep = "welcome" | "install" | "account" | "model" | "connect"; +/** + * `connect` is the Start step, where OpenBot on this computer starts. `connect_openbot` is the + * first screen with an OpenBot that runs elsewhere chosen: the address field. The address itself is + * never part of an event. + */ +export type SetupStep = + | "welcome" + | "install" + | "account" + | "model" + | "connect" + | "connect_openbot"; const HARNESSES = { crewai: "crewai", From 124cae7b978834b8d79bba74641950e55e628fdc Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 12:54:40 -0800 Subject: [PATCH 004/116] Offer connecting to an OpenBot from Settings when OpenBot runs on this computer A person who already runs OpenBot here had no way back to the choice of where it runs. Settings, Computer now has a Connection row that, after a confirm, stops OpenBot here and opens setup at that choice. It is drawn only by a desktop app that can connect. --- .../settings/connection-sections.tsx | 67 +++++++++++++++++++ app/src/lib/desktop/queries.ts | 11 ++- app/src/routes/_authed/settings/computer.tsx | 10 ++- app/tests/desktop-connected-settings.test.tsx | 28 +++++++- 4 files changed, 109 insertions(+), 7 deletions(-) diff --git a/app/src/components/settings/connection-sections.tsx b/app/src/components/settings/connection-sections.tsx index d998ede765..c750db595a 100644 --- a/app/src/components/settings/connection-sections.tsx +++ b/app/src/components/settings/connection-sections.tsx @@ -152,6 +152,73 @@ function SignOutRow({ host }: { host: string }) { ); } +/** + * Settings → Computer inside an OpenBot Desktop that runs OpenBot on this computer: the way to + * connect to an OpenBot that runs somewhere else instead. Drawn under `ThisComputerSections`, and + * only by a desktop app that can connect. + * + * It stops OpenBot here, as Stop does, and the window shows setup at the choice of where OpenBot + * runs. This page goes with it. + */ +export function ConnectInsteadSection() { + const [open, setOpen] = useState(false); + const change = useMutation(changeConnectionMutationOptions()); + const leaving = change.isPending || change.isSuccess; + return ( + + + + + + + + OpenBot runs on this computer + + You can connect to an OpenBot your company runs instead. + + + + + + + + + + + Connect to an OpenBot instead? + + OpenBot stops on this computer and setup opens, where you type the + address of the OpenBot to connect to. Nothing on this computer is + lost, and you can come back to it later. + + + {change.error ? ( + +

+ Couldn't open setup. Try again. +

+
+ ) : null} + + + + +
+
+
+ ); +} + function UseThisComputerRow({ host }: { host: string }) { const [open, setOpen] = useState(false); const change = useMutation(changeConnectionMutationOptions()); diff --git a/app/src/lib/desktop/queries.ts b/app/src/lib/desktop/queries.ts index f878af538a..a0ccd71c3d 100644 --- a/app/src/lib/desktop/queries.ts +++ b/app/src/lib/desktop/queries.ts @@ -129,10 +129,15 @@ export type DesktopUsageData = { * desktop app keeps that and the page never holds it. */ export type DesktopConnection = - | { mode: "local"; address: null } + /** `canConnect`: the desktop app is one that can connect to an OpenBot elsewhere. */ + | { mode: "local"; address: null; canConnect: boolean } | { mode: "connected"; address: string }; -const ON_THIS_COMPUTER: DesktopConnection = { mode: "local", address: null }; +const ON_THIS_COMPUTER: DesktopConnection = { + mode: "local", + address: null, + canConnect: false, +}; export const desktopKeys = { all: ["desktop"] as const, @@ -174,7 +179,7 @@ export function desktopConnectionQueryOptions() { }>("connection"); return answer?.mode === "connected" && answer.address ? { mode: "connected", address: answer.address } - : ON_THIS_COMPUTER; + : { mode: "local", address: null, canConnect: true }; } catch { return ON_THIS_COMPUTER; } diff --git a/app/src/routes/_authed/settings/computer.tsx b/app/src/routes/_authed/settings/computer.tsx index 3d540e9be0..356d2bd0db 100644 --- a/app/src/routes/_authed/settings/computer.tsx +++ b/app/src/routes/_authed/settings/computer.tsx @@ -3,7 +3,10 @@ import { createFileRoute } from "@tanstack/react-router"; import { PageShell } from "@/components/layout/page-shell"; import { ComputersPage } from "@/components/manage/computers-page"; import { BrowserSections } from "@/components/settings/browsers/browser-sections"; -import { ConnectionSections } from "@/components/settings/connection-sections"; +import { + ConnectInsteadSection, + ConnectionSections, +} from "@/components/settings/connection-sections"; import { ThisComputerSections } from "@/components/settings/this-computer-sections"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { desktopConnectionQueryOptions } from "@/lib/desktop/queries"; @@ -69,7 +72,10 @@ function ComputerPage() { {!desktop || !connection ? null : connection.mode === "connected" ? ( ) : ( - + <> + + {connection.canConnect ? : null} + )} diff --git a/app/tests/desktop-connected-settings.test.tsx b/app/tests/desktop-connected-settings.test.tsx index bbaa6e5817..7b3806261e 100644 --- a/app/tests/desktop-connected-settings.test.tsx +++ b/app/tests/desktop-connected-settings.test.tsx @@ -173,18 +173,42 @@ test("connected, Settings → Computer says where the app is connected and shows expect(header?.textContent).not.toContain("runs on this computer"); }); -test("with OpenBot on this computer, the page is as it was: its services, and no Connection section", async () => { +test("with OpenBot on this computer, its services are as they were, and the way to connect to an OpenBot instead is offered", async () => { const view = renderComputer("local"); await view.findByRole("heading", { name: "App" }); expect(view.getByText("Installed in")).toBeTruthy(); - expect(view.queryByRole("heading", { name: "Connection" })).toBeNull(); + expect(view.queryByText("Connected to")).toBeNull(); + await view.findByRole("heading", { name: "Connection" }); + expect(view.getByText("OpenBot runs on this computer")).toBeTruthy(); +}); + +test("Connect to an OpenBot asks first, saying OpenBot stops here and nothing is lost, then asks the desktop app", async () => { + const view = renderComputer("local"); + fireEvent.click( + await view.findByRole("button", { name: "Connect to an OpenBot" }), + ); + const dialog = await view.findByRole("dialog"); + expect(dialog.textContent).toContain("Connect to an OpenBot instead?"); + expect(dialog.textContent).toContain("OpenBot stops on this computer"); + expect(dialog.textContent).toContain("Nothing on this computer is lost"); + expect(asked).not.toContain("change_connection"); + fireEvent.click( + Array.from(dialog.querySelectorAll("button")).find( + (button) => button.textContent === "Stop and open setup", + ) as HTMLButtonElement, + ); + await waitFor(() => expect(asked).toContain("change_connection")); }); test("a desktop app from before it could connect is read as OpenBot on this computer", async () => { const view = renderComputer("older"); await view.findByRole("heading", { name: "App" }); expect(asked).toContain("connection"); + // It cannot connect, so it is not offered. expect(view.queryByRole("heading", { name: "Connection" })).toBeNull(); + expect( + view.queryByRole("button", { name: "Connect to an OpenBot" }), + ).toBeNull(); }); test("Sign out asks first, then asks the desktop app to sign out", async () => { From 97648317c96509867fabfe3b89fdddbdb6e9d100 Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 13:03:53 -0800 Subject: [PATCH 005/116] Say connection problems calmly, and offer the choice to an install on this computer A connection that didn't work is not a failed install. Every connection problem that is not about the address itself now shows the shell's sentence in the calm notice, with no failure heading and no troubleshooting logs, and the way on is the screen's button: Try again, Sign in again, or Open in browser beside Connect. The connect screen no longer scrolls at the window's default size. The failure card is as it was for setup on this computer. Setup also asks the shell whether the person chose, in Settings, to pick where OpenBot runs. When they did, the first screen shows whichever way OpenBot runs today. On a computer that already runs OpenBot, nothing starts while the choice shows, and Continue goes on as any relaunch does. --- desktop/src/App.test.tsx | 77 +++++++++++++++++++++++++++++- desktop/src/App.tsx | 81 ++++++++++++++++++++++++++------ desktop/src/ConnectToOpenBot.tsx | 46 ++++++++---------- desktop/src/Problem.tsx | 6 +-- desktop/src/Welcome.tsx | 52 +++++++++++++++----- desktop/src/styles.css | 9 ++-- 6 files changed, 207 insertions(+), 64 deletions(-) diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index 92ea038392..160d101d3a 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -893,7 +893,15 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { await userEvent.type(field, "x"); expect(view.queryByRole("alert")).toBeNull(); expect(field.getAttribute("aria-invalid")).toBeNull(); - } else if (offer === "Open in browser") { + return; + } + // A connection that didn't work is not a failed install: a calm notice with the sentence, + // not the failure card with its heading and troubleshooting logs. + expect(alert.classList.contains("blocker")).toBe(false); + expect(view.queryByText("That didn’t finish")).toBeNull(); + expect(view.queryByRole("button", { name: "Copy logs" })).toBeNull(); + expect(view.queryByRole("link", { name: "Get setup help" })).toBeNull(); + if (offer === "Open in browser") { const link = view.getByRole("link", { name: "Open in browser" }); expect(link.getAttribute("href")).toBe(ELSEWHERE); await userEvent.click(link); @@ -904,6 +912,7 @@ for (const { kind, said, at, offer } of CONNECT_PROBLEMS) { expect(view.getByRole("button", { name: "Connect" })).toBeTruthy(); } else { // One way on, and it says what it does. + expect(alert.textContent).toBe(said); expect(view.queryByRole("button", { name: "Connect" })).toBeNull(); await userEvent.click(view.getByRole("button", { name: offer })); await waitFor(() => expect(at === "check" ? checks : signIns).toBe(2)); @@ -1034,6 +1043,72 @@ test("asked from Settings to choose where OpenBot runs, the first screen opens o expect(commands).toContain("already_configured"); }); +/* + * Settings' choice of where OpenBot runs, for a person who already runs it on this computer: the + * shell stops OpenBot, puts setup back and says `choose` once. The first screen shows in place of + * the start that a relaunch does by itself, and nothing starts until the person continues. + */ +test("asked from Settings on an install on this computer, the first screen shows the choice and starts nothing until Continue, which starts it as a relaunch does", async () => { + setupConnectedLocalStack( + "/tmp/choose-on-this-computer", + localStatus("ready", "valid"), + ); + let notices = 0; + withLocalCli({ + connection: { mode: "local", address: ELSEWHERE, signedIn: false }, + take_connection_notice: () => { + notices += 1; + return notices === 1 ? { kind: "choose", message: null } : null; + }, + record_setup_event: null, + }); + const view = await renderApp(); + expect( + await view.findByRole("heading", { name: "Set up OpenBot" }), + ).toBeTruthy(); + expect(view.getByRole("radio", { name: /^Self-hosted/ })).toHaveProperty( + "checked", + true, + ); + // OpenBot is already installed here: the way on is Continue, not Install. + expect(buttons(view)).toEqual(["Continue"]); + expect(view.queryByText(/Setup takes/)).toBeNull(); + await new Promise((resolve) => setTimeout(resolve, 30)); + const started = () => + invokeCalls + .map((call) => call.command) + .filter((command) => + [ + "run_local_eval", + "set_up_local_eval", + "connect_local_eval", + "start_stack", + "show_openbot", + "prepare_installation", + "start_early_downloads", + "use_this_computer", + ].includes(command), + ); + expect(started()).toEqual([]); + // The other choice, with the address connected to before, and back. + await userEvent.click( + view.getByRole("radio", { name: /^OpenBot for Business/ }), + ); + expect( + (view.getByLabelText("OpenBot address") as HTMLInputElement).value, + ).toBe(ELSEWHERE); + await userEvent.click(view.getByRole("radio", { name: /^Self-hosted/ })); + expect(started()).toEqual([]); + // Continue: today's relaunch, which starts the saved installation and opens OpenBot. + await userEvent.click(view.getByRole("button", { name: "Continue" })); + await view.findByRole("heading", { name: "OpenBot is running" }); + expect(started()).toEqual(["run_local_eval", "start_stack", "show_openbot"]); + expect(getStartStackPayload()).toMatchObject({ + root: "/tmp/choose-on-this-computer", + ...LOCAL_ADDRESSES, + }); +}); + test("a saved sign-in that can't open OpenBot says why on the connect screen, and Try again opens it without signing in again", async () => { const said = "OpenBot couldn't reach openbot.example.com. Check the address and your network, then try again."; diff --git a/desktop/src/App.tsx b/desktop/src/App.tsx index efd68b81f1..7e4295220b 100644 --- a/desktop/src/App.tsx +++ b/desktop/src/App.tsx @@ -54,7 +54,7 @@ import { type SetupStep, } from "./telemetry"; import { UsageDataChoice } from "./UsageDataChoice"; -import { Welcome } from "./Welcome"; +import { type Hosting, Welcome } from "./Welcome"; import { type Blocker, WindowsBlocker, WindowsRestart } from "./WindowsBlocker"; type AlreadyConfigured = { @@ -126,8 +126,11 @@ type ConnectionNotice = { kind: string; message: string | null }; type Launch = | { at: "asking" } - /** OpenBot on this computer: setup as it has always been. */ - | { at: "local"; address: string } + /** + * OpenBot on this computer: setup as it has always been. `choose`: the person asked from + * Settings to choose where OpenBot runs, so the first screen shows before anything starts. + */ + | { at: "local"; address: string; choose: boolean } /** Signed in to an OpenBot that runs elsewhere, which the shell is opening. */ | { at: "opening" } /** The first screen with that OpenBot's address, to sign in to it again or choose otherwise. */ @@ -159,11 +162,12 @@ function Setup() { const found = await invoke("connection").catch(() => null); if (!alive.current) return; const address = found?.address ?? ""; - if (found?.mode !== "connected") { - setLaunch({ at: "local", address }); + // An older shell knows neither question: OpenBot on this computer, with nothing to say. + if (!found) { + setLaunch({ at: "local", address, choose: false }); return; } - if (found.signedIn) { + if (found.mode === "connected" && found.signedIn) { setLaunch({ at: "opening" }); try { await invoke("show_connected"); @@ -182,6 +186,14 @@ function Setup() { "take_connection_notice", ).catch(() => null); if (!alive.current) return; + if (found.mode !== "connected") { + setLaunch({ + at: "local", + address, + choose: notice?.kind === "choose", + }); + return; + } setLaunch({ at: "connect", address, @@ -203,7 +215,8 @@ function Setup() { recordSetupEvent({ kind: "step_viewed", step: "connect_openbot" }); }, [connecting]); - if (launch.at === "local") return ; + if (launch.at === "local") + return ; if (launch.at === "connect") { const { address } = launch; return ( @@ -214,7 +227,7 @@ function Setup() { // The saved choice goes back to this computer, then setup carries on as a first run. onThisComputer={async () => { await invoke("use_this_computer"); - setLaunch({ at: "local", address }); + setLaunch({ at: "local", address, choose: false }); }} saved={{ address, @@ -244,8 +257,20 @@ function Setup() { ); } -/** Setup of OpenBot on this computer. `address`: an OpenBot connected to before, if any. */ -function LocalSetup({ address }: { address: string }) { +/** + * Setup of OpenBot on this computer. `address`: an OpenBot connected to before, if any. `choose`: + * open at the first screen, the choice of where OpenBot runs, whatever is already installed. + */ +function LocalSetup({ address, choose }: { address: string; choose: boolean }) { + /* + * The choice the person asked for from Settings, shown over wherever setup would have resumed: + * nothing starts by itself while it shows. Continue with Self-hosted drops it, and setup goes on + * as this launch would have without it; an installation that is already set up starts as it does + * on any relaunch. + */ + const [choosing, setChoosing] = useState( + choose ? "self-hosted" : null, + ); const [blocker, setBlocker] = useState(null); // A Windows fix made earlier that only counts once Windows has restarted, and it has not. const [restartPending, setRestartPending] = useState(false); @@ -291,11 +316,15 @@ function LocalSetup({ address }: { address: string }) { // The back end is ready on the release it had, and its update did not finish. const [backEndNotice, setBackEndNotice] = useState(null); const [step, setStep] = useState("welcome"); + const [checkingResume, setCheckingResume] = useState(true); + // With nothing set up yet, setup opens at the first screen anyway: it is the choice. + useEffect(() => { + if (!checkingResume && choosing && step === "welcome") setChoosing(null); + }, [checkingResume, choosing, step]); const [steps, setSteps] = useState([]); // When the install now running began: its row on the other screens counts from here. const [installSince, setInstallSince] = useState(null); const [busy, setBusy] = useState(false); - const [checkingResume, setCheckingResume] = useState(true); const savedLaunch = useRef(null); // An interrupted run needs an explicit Start. const interruptedAtLaunch = useRef(false); @@ -332,14 +361,21 @@ function LocalSetup({ address }: { address: string }) { }, [engineReady, installationReady]); const returningToInstallation = savedLaunch.current === installationKey; const [running, setRunning] = useState(false); - const visibleSetupStep = - checkingResume || blockerFailure || blocker || running ? null : step; + const visibleSetupStep: SetupStep | null = + checkingResume || blockerFailure || blocker || running + ? null + : choosing === "connect" + ? "connect_openbot" + : choosing + ? "welcome" + : step; /* * The first screen starts the big downloads, without a click: the person opened OpenBot's setup * to install it. The native side downloads only what this computer's install will need, once per * run of the app (`early_downloads.rs`). */ - const onFirstScreen = visibleSetupStep === "welcome"; + // Not for the choice asked for from Settings: that screen starts nothing. + const onFirstScreen = visibleSetupStep === "welcome" && !choosing; useEffect(() => { if (!onFirstScreen || !root.trim()) return; invoke("start_early_downloads", { root: root.trim() }).catch(() => {}); @@ -983,6 +1019,7 @@ function LocalSetup({ address }: { address: string }) { const localAuto = !checkingResume && !running && + !choosing && step === "connect" && modelCanStart() && (resumingStart || @@ -1069,6 +1106,22 @@ function LocalSetup({ address }: { address: string }) { * Skipped entirely when a stack is already up: somebody returning to a running OpenBot is not * setting one up. */ + if (!running && choosing && step !== "welcome") { + // Asked for from Settings, over a setup that would have resumed further on. + return ( +
+ setChoosing("connect")} + onThisComputer={() => setChoosing("self-hosted")} + saved={{ address }} + resumes + onInstall={() => setChoosing(null)} + /> +
+ ); + } + if (!running && (step === "welcome" || step === "connect_openbot")) { return (
diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx index 89623cc7f5..4aba407e6d 100644 --- a/desktop/src/ConnectToOpenBot.tsx +++ b/desktop/src/ConnectToOpenBot.tsx @@ -1,7 +1,7 @@ import { invoke } from "@tauri-apps/api/core"; import { useEffect, useId, useRef, useState } from "react"; import { ExternalLink } from "./ExternalLink"; -import { asProblem, Failure, type Problem } from "./Problem"; +import { asProblem, type Problem } from "./Problem"; import { StatusLine } from "./SetupProgress"; /** OpenBot's one booking link. */ @@ -35,11 +35,6 @@ function offerFor(kind: string | null | undefined): Offer { } } -/** Nothing failed: the sign-in stopped or ended, and signing in again is all there is to do. */ -function isNotice(kind: string | null | undefined) { - return kind === "sign-in-cancelled" || kind === "session-ended"; -} - /** The typed address as a link the browser can open. The shell takes no scheme as https too. */ function browserAddress(address: string) { const typed = address.trim(); @@ -263,9 +258,7 @@ export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) { You'll sign in to it in your browser. Nothing is installed on this computer.

- {trouble && !underField && ( - - )} + {trouble && !underField && }
{phase === "checking" && ( Checking the address… @@ -300,23 +301,16 @@ export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) { ); } -/** The sentence, in the card: a notice when nothing failed, the window's failure when it did. */ -function Trouble({ trouble, address }: { trouble: Trouble; address: string }) { - const { problem, offer } = trouble; - if (isNotice(problem.kind)) { - return ( -
-

{problem.said}

-
- ); - } +/** + * The sentence, in a calm notice: the card that waits on the person. A connection that didn't work + * is not a failed install, so it is not drawn as one: no failure heading and no troubleshooting + * logs, which are about OpenBot on this computer. The way on is the screen's button, or the link + * beside it when that OpenBot can only be opened in the browser. + */ +function Trouble({ trouble }: { trouble: Trouble }) { return ( - - {offer === "browser" && address.trim() && ( - - Open in browser - - )} - +
+

{trouble.problem.said}

+
); } diff --git a/desktop/src/Problem.tsx b/desktop/src/Problem.tsx index 53318136ae..c238e74902 100644 --- a/desktop/src/Problem.tsx +++ b/desktop/src/Problem.tsx @@ -1,5 +1,5 @@ import { invoke } from "@tauri-apps/api/core"; -import { type ReactNode, useState } from "react"; +import { useState } from "react"; import { ExternalLink } from "./ExternalLink"; /** @@ -163,16 +163,13 @@ export function TroubleshootingLogs({ /** * `onRetry`, where the screen has no other way to run what failed again: Try again, in the card. * The install behind the account step had none, and its failure sat there with nothing to press. - * `children`, where the way on is something other than Try again: it takes that button's place. */ export function Failure({ problem, onRetry, - children, }: { problem: Problem; onRetry?: () => void; - children?: ReactNode; }) { return (
@@ -185,7 +182,6 @@ export function Failure({
)} - {children &&
{children}
} {/* The real output, kept but not the headline. Whoever is debugging opens this; the person reading the sentence above never has to. */} {problem.detail && ( diff --git a/desktop/src/Welcome.tsx b/desktop/src/Welcome.tsx index 566872faf3..56b0f034b1 100644 --- a/desktop/src/Welcome.tsx +++ b/desktop/src/Welcome.tsx @@ -54,10 +54,17 @@ export function Welcome({ onConnect, onThisComputer, saved, + resumes = false, onInstall, failure, }: { hosting: Hosting; + /** + * OpenBot is already set up on this computer, and the person asked from Settings to choose where + * it runs. Self-hosted's way on is Continue, which goes on with that setup; there is nothing to + * install or download first. + */ + resumes?: boolean; /** OpenBot for Business was picked. */ onConnect: () => void; /** Self-hosted was picked again. May fail, when a saved connection has to be switched first. */ @@ -146,30 +153,22 @@ export function Welcome({ {connect ? ( ) : ( - + )} ); } -/** What Self-hosted asks of this computer and why, how long setup takes, and Install. */ +/** What Self-hosted asks of this computer and why, then the way on. */ function SelfHosted({ onInstall, failure, + resumes, }: { onInstall: () => void; failure?: ReactNode; + resumes: boolean; }) { - const downloads = useEarlyDownloads(); - const [checking, setChecking] = useState(false); - const short = downloads?.state === "short"; - const install = () => { - setChecking(true); - void earlyDownloadsMeasured().then((now) => { - setChecking(false); - if (now?.state !== "short") onInstall(); - }); - }; return ( <>
@@ -185,6 +184,34 @@ function SelfHosted({ ))}
+ {resumes ? ( +
+ +
+ ) : ( + + )} + {failure} + + ); +} + +/** How long setup takes, Install, and the downloads this screen started. */ +function Install({ onInstall }: { onInstall: () => void }) { + const downloads = useEarlyDownloads(); + const [checking, setChecking] = useState(false); + const short = downloads?.state === "short"; + const install = () => { + setChecking(true); + void earlyDownloadsMeasured().then((now) => { + setChecking(false); + if (now?.state !== "short") onInstall(); + }); + }; + return ( + <>

Setup takes 1 to 10 minutes, depending on your internet speed.

@@ -194,7 +221,6 @@ function SelfHosted({ - {failure} ); } diff --git a/desktop/src/styles.css b/desktop/src/styles.css index 87c6e6e410..939a8a07b5 100644 --- a/desktop/src/styles.css +++ b/desktop/src/styles.css @@ -799,17 +799,16 @@ fieldset.picker.hosting .tile.held:active { margin-top: 8px; } -/* A sign-in that stopped or ended: the card that waits on the person, with the sentence in ink. */ +/* + * A connection that didn't work, or a sign-in that stopped or ended: the card that waits on the + * person, with the shell's sentence in ink. Not the failure card: nothing on this computer failed. + */ .connect-to-openbot .local-alert { margin: 16px 0 0; } .connect-to-openbot .local-alert p { color: var(--text-primary); -} - -.connect-to-openbot .blocker p, -.connect-to-openbot .local-alert p { overflow-wrap: anywhere; } From 9c9ce151c950ff5fba04f22768707e34b91e0c67 Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 13:07:47 -0800 Subject: [PATCH 006/116] Sign in to an OpenBot at an address and relay the window to it OpenBot Desktop could only run OpenBot on the computer it is installed on. This adds what it takes to show an OpenBot that runs somewhere else instead, as a library module of its own (desktop/src-tauri/src/connected) that nothing calls yet. choice: which of the two the person chose, in connection.json in the app's configuration folder, with the address and the organisation picked there. No file means on this computer. address: a typed address kept as scheme and host (https, or http for 127.0.0.1 and [::1]; no scheme is taken as https), and two public questions asked of it: what it offers and how an app signs in to it (RFC 8414). Each way that can go wrong is one kind with its own sentence: not an address, unreachable, not an OpenBot, one person's OpenBot on its own computer, a release from before apps could sign in. A redirect to another host is not followed, and metadata that names another host is refused. sign_in: OAuth 2.1 authorization code with PKCE (S256) as the public client openbot-desktop-oauth, with a listener on 127.0.0.1 at a port the system picks and a redirect of exactly /callback. The verifier, the state and the callback's first line use what provider_oauth already has (its random and its challenge are now shared, unchanged). The wait ends on the code, a refusal, Cancel or ten minutes. After the exchange the OpenBot is asked /api/me with the new token; a 401 there means it cannot serve the app. Refresh tokens rotate, so one refresh runs at a time and the new token is stored before the old one is let go. Sign-out revokes both tokens (RFC 7009) and forgets the sign-in. credentials: the refresh token in the system's credential store through keyring 4.2 (Keychain, Credential Manager, the Secret Service), under the app's identifier and the address. The access token stays in memory. Nothing token-shaped is written to a file or a log, and the log's redaction now also covers OpenBot's own token prefixes and the relay's cookie. relay: an HTTP/1 server on 127.0.0.1 only, at a port the system picks, that passes each request and WebSocket upgrade on to the one typed address with the access token added. It answers only its own Host, only requests that carry the secret made for that run (given to the window as an HttpOnly, SameSite=Strict cookie at an entry address that is never forwarded), and no request from another site. Absolute request targets and CONNECT are refused and redirects are handed back, rewritten onto the relay when they point at the typed address. Origin, Cookie, Referer, Forwarded and X-Forwarded-* are dropped on the way out and Set-Cookie on the way back. Bodies stream both ways. The organisation the person picked is named in a header on every request, set by the shell and never taken from the page. A 401 to a request with no body leads to one refresh and the request again; a refused refresh says the session ended, once, and the relay stops. The tests run against a stand-in OpenBot that answers the same addresses the same way: the metadata document, a form-encoded token endpoint with the client's id in the body, the verifier really checked, a code that burns on a wrong verifier, rotating refresh tokens where a replayed one answers invalid_grant, revocation, and a redirect that must be http://127.0.0.1:/callback. The credential store in tests is keyring's own in-memory one. New crates: keyring and keyring-core; tokio, hyper, hyper-util, http-body-util, bytes and futures-util, which reqwest and Tauri already build; tokio-tungstenite for the tests' WebSocket. --- desktop/src-tauri/Cargo.lock | 305 ++++- desktop/src-tauri/Cargo.toml | 20 +- desktop/src-tauri/src/connected/address.rs | 334 +++++ desktop/src-tauri/src/connected/choice.rs | 183 +++ .../src-tauri/src/connected/credentials.rs | 146 ++ .../src-tauri/src/connected/fake_openbot.rs | 775 +++++++++++ desktop/src-tauri/src/connected/mod.rs | 215 +++ desktop/src-tauri/src/connected/relay.rs | 1171 +++++++++++++++++ desktop/src-tauri/src/connected/sign_in.rs | 1019 ++++++++++++++ desktop/src-tauri/src/lib.rs | 1 + desktop/src-tauri/src/logging.rs | 8 + desktop/src-tauri/src/logging_file_tests.rs | 52 + desktop/src-tauri/src/problem.rs | 6 + desktop/src-tauri/src/provider_oauth.rs | 9 +- 14 files changed, 4240 insertions(+), 4 deletions(-) create mode 100644 desktop/src-tauri/src/connected/address.rs create mode 100644 desktop/src-tauri/src/connected/choice.rs create mode 100644 desktop/src-tauri/src/connected/credentials.rs create mode 100644 desktop/src-tauri/src/connected/fake_openbot.rs create mode 100644 desktop/src-tauri/src/connected/mod.rs create mode 100644 desktop/src-tauri/src/connected/relay.rs create mode 100644 desktop/src-tauri/src/connected/sign_in.rs diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index e66a092079..80a22fc204 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -8,6 +8,17 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures 0.3.1", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -64,6 +75,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arbitrary" version = "1.4.2" @@ -305,6 +327,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.6.2" @@ -458,6 +489,15 @@ dependencies = [ "toml 1.1.5+spec-1.1.0", ] +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + [[package]] name = "cc" version = "1.4.5" @@ -538,6 +578,22 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "crypto-common 0.2.2", + "inout", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "combine" version = "4.6.8" @@ -664,6 +720,12 @@ dependencies = [ "libc", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -760,6 +822,15 @@ version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d" +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + [[package]] name = "darling" version = "0.20.11" @@ -829,6 +900,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "dbus" version = "0.9.12" @@ -962,6 +1039,7 @@ dependencies = [ "block-buffer 0.12.1", "const-oid", "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -1764,6 +1842,24 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "html5ever" version = "0.39.0" @@ -1822,6 +1918,12 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -1844,6 +1946,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2081,6 +2184,16 @@ dependencies = [ "cfb", ] +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + [[package]] name = "ipnet" version = "2.12.1" @@ -2305,6 +2418,27 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59" +dependencies = [ + "log", +] + [[package]] name = "konst" version = "0.2.20" @@ -2605,12 +2739,75 @@ dependencies = [ "zbus", ] +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + [[package]] name = "num-conv" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -2972,8 +3169,15 @@ version = "1.0.3" dependencies = [ "base64 0.22.1", "block2", + "bytes", "dirs", "flate2", + "futures-util", + "http-body-util", + "hyper", + "hyper-util", + "keyring", + "keyring-core", "libc", "log", "objc2", @@ -3006,6 +3210,8 @@ dependencies = [ "tauri-plugin-updater", "tauri-plugin-window-state", "time", + "tokio", + "tokio-tungstenite", "windows 0.62.2", "windows-registry", "zip 2.4.2", @@ -3623,12 +3829,14 @@ dependencies = [ "sync_wrapper", "tokio", "tokio-rustls", + "tokio-util", "tower", "tower-http", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams 0.4.2", "web-sys", "webpki-roots", ] @@ -3669,7 +3877,7 @@ dependencies = [ "url", "wasm-bindgen", "wasm-bindgen-futures", - "wasm-streams", + "wasm-streams 0.5.0", "web-sys", ] @@ -3910,6 +4118,25 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -4144,6 +4371,17 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha2" version = "0.10.9" @@ -5178,6 +5416,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17a073bfed563fa236697a068031408a93cd9522e08abf9933ead3e73411bd71" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -5392,6 +5642,22 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.2", + "sha1", + "thiserror 2.0.20", +] + [[package]] name = "typed-path" version = "0.13.0" @@ -5624,6 +5890,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "wasm-streams" version = "0.5.0" @@ -5937,6 +6216,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.2.0" @@ -6443,6 +6735,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index dbee71939f..7ff29a2297 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -34,7 +34,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" rand = "0.9" base64 = "0.22" -reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "blocking", "json"] } +# `stream`: the relay hands a request's and a response's body on as it arrives. See `connected/relay.rs`. +reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "blocking", "json", "stream"] } flate2 = "1" # Checking the digest of an installer before running it. See `install.rs`. sha2 = "0.10" @@ -79,6 +80,20 @@ log = "0.4" regex = "1" # The log's UTC timestamps, and the local offset its first line says. The version Tauri already uses. time = { version = "0.3", features = ["formatting", "macros", "local-offset"] } +# The sign-in to an OpenBot that runs elsewhere, kept in the system's own credential store: Keychain +# on macOS, Credential Manager on Windows, the Secret Service on Linux. See `connected/credentials.rs`. +keyring = "4.2" +# The entry type `keyring` hands back, and the in-memory store its own tests use, which this +# crate's tests use in place of the real keychain. The version `keyring` already builds. +keyring-core = "1" +# The loopback relay between the window and that OpenBot: an HTTP/1 server on 127.0.0.1, with the +# runtime, bodies and streams reqwest and Tauri already build. See `connected/relay.rs`. +tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "sync", "time", "macros"] } +hyper = { version = "1", features = ["server", "http1"] } +hyper-util = { version = "0.1", features = ["tokio"] } +http-body-util = "0.1" +bytes = "1" +futures-util = { version = "0.3", default-features = false, features = ["std"] } [target.'cfg(unix)'.dependencies] libc = "0.2" @@ -118,6 +133,9 @@ harness = false [dev-dependencies] tauri = { version = "2", features = ["test"] } +# A real WebSocket client and server at each end of the relay in its tests. +tokio-tungstenite = "0.30" +futures-util = { version = "0.3", default-features = false, features = ["std", "sink"] } # Every local evaluation CLI call checks the pinned runtime and script against their digests, # about 150 MB. Unoptimized, that hash alone took 4.9 s per call in a debug build; optimized, 0.3 s. diff --git a/desktop/src-tauri/src/connected/address.rs b/desktop/src-tauri/src/connected/address.rs new file mode 100644 index 0000000000..0782f5542d --- /dev/null +++ b/desktop/src-tauri/src/connected/address.rs @@ -0,0 +1,334 @@ +//! The address a person types, made into one the app can use, and checked to be an OpenBot this +//! app can connect to. +//! +//! Two questions are asked of the address, both public: what it offers +//! (`/api/v2/organizations/default/deployment`, which every OpenBot answers before sign-in) and +//! how an app signs in to it (its authorization server metadata, RFC 8414). Each way that can go +//! wrong is one `Kind`, so the window can say what to do next. + +use super::{host_of, http, transport, Kind}; +use crate::problem::Problem; + +const DEPLOYMENT: &str = "/api/v2/organizations/default/deployment"; +const METADATA: &str = "/.well-known/oauth-authorization-server/api/auth"; +/// What keeps a sign-in going after its first hour: a refresh token. +const OFFLINE_ACCESS: &str = "offline_access"; + +/// How this app signs in to an OpenBot, as that OpenBot publishes it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Metadata { + pub authorization_endpoint: String, + pub token_endpoint: String, + pub revocation_endpoint: Option, + /// Every scope it lists. The app's screens use the whole API, so all of them are asked for. + pub scopes: Vec, +} + +/// `typed` as the app keeps it: scheme and host (and a port that is not the scheme's own), with +/// no path and no trailing slash. An address with no scheme is taken as `https://`. Only `https`, +/// except for this computer's own `127.0.0.1` and `[::1]`, where `http` is allowed. +pub fn normalise(typed: &str) -> Result { + let typed = typed.trim(); + let invalid = |why: &str| Kind::AddressInvalid.problem("", why.to_owned()); + if typed.is_empty() || typed.contains(char::is_whitespace) { + return Err(invalid("no address, or one with a space in it")); + } + let with_scheme = if typed.contains("://") { + typed.to_owned() + } else { + format!("https://{typed}") + }; + let url = reqwest::Url::parse(&with_scheme).map_err(|error| invalid(&error.to_string()))?; + let host = url.host_str().filter(|host| !host.is_empty()); + let Some(host) = host else { + return Err(invalid("no host")); + }; + if !url.username().is_empty() || url.password().is_some() { + return Err(invalid("a name or password in the address")); + } + match url.scheme() { + "https" => {} + "http" if matches!(host, "127.0.0.1" | "[::1]") => {} + "http" => return Err(invalid("http is only for 127.0.0.1 and [::1]")), + other => return Err(invalid(&format!("the scheme {other}"))), + } + // A name needs a dot or to be an IP address: "openbot" alone is a word, not an address. + let named = host.contains('.') || host.starts_with('['); + if !named { + return Err(invalid("a host with no dot in it")); + } + Ok(match url.port() { + Some(port) => format!("{}://{host}:{port}", url.scheme()), + None => format!("{}://{host}", url.scheme()), + }) +} + +/// Normalise `typed`, then ask the OpenBot there whether this app can connect to it. The answer is +/// the normalised address and how to sign in. +pub fn check(typed: &str) -> Result<(String, Metadata), Problem> { + let address = normalise(typed)?; + let metadata = probe(&address)?; + Ok((address, metadata)) +} + +/// Ask a normalised `address` what it is and how an app signs in to it. +pub fn probe(address: &str) -> Result { + let host = host_of(address); + let client = http().map_err(|error| Kind::Unreachable.problem(&host, error))?; + let get = |path: &str| { + client + .get(format!("{address}{path}")) + .header(reqwest::header::ACCEPT, "application/json") + .send() + .map_err(|error| Kind::Unreachable.problem(&host, transport(error))) + }; + + let answered = get(DEPLOYMENT)?; + let status = answered.status(); + let deployment = json_object(answered).filter(|_| status.is_success()); + let edition = deployment + .as_ref() + .and_then(|deployment| deployment.get("edition")) + .and_then(serde_json::Value::as_str); + let Some(edition) = edition else { + return Err(Kind::NotOpenBot.problem( + &host, + format!("GET {DEPLOYMENT} answered {status}, not as an OpenBot does"), + )); + }; + let on_its_own_computer = deployment + .as_ref() + .and_then(|deployment| deployment.get("localEvaluation")) + .and_then(serde_json::Value::as_bool) + .unwrap_or(false); + if on_its_own_computer { + return Err(Kind::SinglePerson.problem(&host, "the deployment says localEvaluation")); + } + + let answered = get(METADATA)?; + let status = answered.status(); + let Some(document) = json_object(answered).filter(|_| status.is_success()) else { + // No sign-in for apps. A personal OpenBot has no sign-in at all; any other is a release + // from before apps could sign in. + let kind = if edition == "personal" { + Kind::SinglePerson + } else { + Kind::TooOld + }; + return Err(kind.problem( + &host, + format!("GET {METADATA} answered {status}; edition {edition}"), + )); + }; + metadata_from(address, &document).map_err(|why| Kind::TooOld.problem(&host, why)) +} + +fn json_object( + response: reqwest::blocking::Response, +) -> Option> { + match response.json::().ok()? { + serde_json::Value::Object(object) => Some(object), + _ => None, + } +} + +/// The endpoints and scopes of a metadata document. Each endpoint has to be on the address itself: +/// the browser is sent to one and a code is posted to another, and neither goes anywhere but the +/// OpenBot the person typed. +fn metadata_from( + address: &str, + document: &serde_json::Map, +) -> Result { + let home = reqwest::Url::parse(address).map_err(|error| error.to_string())?; + let endpoint = |name: &str| -> Result, String> { + let Some(value) = document.get(name).and_then(serde_json::Value::as_str) else { + return Ok(None); + }; + let url = reqwest::Url::parse(value).map_err(|_| format!("{name} is not an address"))?; + let same = url.scheme() == home.scheme() + && url.host_str() == home.host_str() + && url.port_or_known_default() == home.port_or_known_default() + && url.username().is_empty() + && url.password().is_none(); + if !same { + return Err(format!("{name} is on another host than the address")); + } + Ok(Some(url.into())) + }; + let scopes: Vec = document + .get("scopes_supported") + .and_then(serde_json::Value::as_array) + .map(|scopes| { + scopes + .iter() + .filter_map(|scope| scope.as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default(); + if !scopes.iter().any(|scope| scope == OFFLINE_ACCESS) { + return Err(format!("the metadata lists no {OFFLINE_ACCESS} scope")); + } + let supports_s256 = document + .get("code_challenge_methods_supported") + .and_then(serde_json::Value::as_array) + .is_none_or(|methods| methods.iter().any(|method| method == "S256")); + if !supports_s256 { + return Err("the metadata lists no S256 code challenge".into()); + } + Ok(Metadata { + authorization_endpoint: endpoint("authorization_endpoint")? + .ok_or("the metadata names no authorization_endpoint")?, + token_endpoint: endpoint("token_endpoint")? + .ok_or("the metadata names no token_endpoint")?, + revocation_endpoint: endpoint("revocation_endpoint")?, + scopes, + }) +} + +#[cfg(test)] +mod tests { + use super::super::fake_openbot::{FakeOpenBot, Shape}; + use super::super::kind_of; + use super::*; + + fn kind(typed: &str) -> Option { + kind_of(&check(typed).expect_err("refused")) + } + + #[test] + fn a_typed_address_is_kept_as_scheme_and_host() { + for (typed, kept) in [ + ("https://openbot.example.com", "https://openbot.example.com"), + ( + " https://OpenBot.Example.com/ ", + "https://openbot.example.com", + ), + ( + "https://openbot.example.com/settings/computer?x=1#top", + "https://openbot.example.com", + ), + ("openbot.example.com", "https://openbot.example.com"), + ( + "openbot.example.com:8443/", + "https://openbot.example.com:8443", + ), + ( + "https://openbot.example.com:443", + "https://openbot.example.com", + ), + ("http://127.0.0.1:4000/", "http://127.0.0.1:4000"), + ("http://[::1]:4000", "http://[::1]:4000"), + ] { + assert_eq!(normalise(typed).as_deref(), Ok(kept), "{typed}"); + } + } + + #[test] + fn http_anywhere_but_this_computer_and_anything_that_is_no_address_are_refused() { + for typed in [ + "", + " ", + "openbot", + "not an address", + "http://openbot.example.com", + "http://localhost:4000", + "http://192.168.1.20:4000", + "ftp://openbot.example.com", + "file:///etc/hosts", + "https://someone:secret@openbot.example.com", + "https://", + ] { + let problem = normalise(typed).expect_err(typed); + assert_eq!(kind_of(&problem), Some(Kind::AddressInvalid), "{typed}"); + assert_eq!( + problem.said, + "That isn't an address OpenBot can connect to. Use one that starts with https://, such as https://openbot.example.com." + ); + } + } + + #[test] + fn an_openbot_this_app_can_sign_in_to_answers_its_address_and_how() { + let openbot = FakeOpenBot::start(Shape::Current); + let (address, metadata) = check(&format!("{}/some/page", openbot.address())).unwrap(); + assert_eq!(address, openbot.address()); + assert_eq!( + metadata.authorization_endpoint, + format!("{address}/api/auth/oauth2/authorize") + ); + assert_eq!( + metadata.token_endpoint, + format!("{address}/api/auth/oauth2/token") + ); + assert_eq!( + metadata.revocation_endpoint, + Some(format!("{address}/api/auth/oauth2/revoke")) + ); + assert!(metadata + .scopes + .iter() + .any(|scope| scope == "offline_access")); + assert!(metadata.scopes.len() > 1); + } + + #[test] + fn nothing_listening_is_unreachable() { + // A port that was just free: bound, read, and let go. + let _ports = crate::test_support::hold_ports(); + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let typed = format!("http://127.0.0.1:{port}"); + let problem = check(&typed).expect_err("nothing is there"); + assert_eq!(kind_of(&problem), Some(Kind::Unreachable)); + assert_eq!( + problem.said, + format!("OpenBot couldn't reach 127.0.0.1:{port}. Check the address and your network, then try again.") + ); + } + + #[test] + fn a_web_page_and_json_that_is_not_openbots_are_not_an_openbot() { + for shape in [Shape::WebPage, Shape::OtherJson] { + let server = FakeOpenBot::start(shape.clone()); + assert_eq!(kind(&server.address()), Some(Kind::NotOpenBot), "{shape:?}"); + } + } + + #[test] + fn an_openbot_for_one_person_on_its_own_computer_is_said_to_be_one() { + for shape in [Shape::LocalEvaluation, Shape::Personal] { + let server = FakeOpenBot::start(shape.clone()); + assert_eq!( + kind(&server.address()), + Some(Kind::SinglePerson), + "{shape:?}" + ); + } + } + + #[test] + fn an_openbot_from_before_apps_could_sign_in_is_too_old() { + let server = FakeOpenBot::start(Shape::NoMetadata); + assert_eq!(kind(&server.address()), Some(Kind::TooOld)); + } + + /// The browser is sent to the authorization endpoint and the code is posted to the token + /// endpoint. Metadata that names another host for either is not followed there. + #[test] + fn metadata_that_names_another_host_is_not_followed() { + let server = FakeOpenBot::start(Shape::MetadataElsewhere); + assert_eq!(kind(&server.address()), Some(Kind::TooOld)); + } + + /// A redirect to another host is not followed: the answer is read from the address typed. + #[test] + fn a_redirect_to_another_host_is_not_followed() { + let real = FakeOpenBot::start(Shape::Current); + let front = FakeOpenBot::start(Shape::RedirectsTo(real.address())); + assert_eq!(kind(&front.address()), Some(Kind::NotOpenBot)); + assert_eq!(real.requests(), Vec::::new()); + } +} diff --git a/desktop/src-tauri/src/connected/choice.rs b/desktop/src-tauri/src/connected/choice.rs new file mode 100644 index 0000000000..f9ba6c16d4 --- /dev/null +++ b/desktop/src-tauri/src/connected/choice.rs @@ -0,0 +1,183 @@ +//! Where the person's choice is kept: `connection.json` in the app's configuration folder. +//! +//! `{ "mode": "local" | "connected", "address": "https://..." }`. No file means local, which is +//! what every installation from before this choice is. Never a secret: the sign-in is in the +//! system's credential store (`credentials`). + +use serde::{Deserialize, Serialize}; +use std::path::{Path, PathBuf}; + +pub const FILE: &str = "connection.json"; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Mode { + /// OpenBot runs on this computer. + #[default] + Local, + /// The app is connected to an OpenBot at an address. + Connected, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Choice { + #[serde(default)] + pub mode: Mode, + /// The normalised address last connected to. Kept through a sign-out and a switch back to + /// this computer, so it can be offered again. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub address: Option, + /// The organisation the person picked in the app at that address, which the relay names on + /// every request. Not a secret. Gone at sign-out, with a new address, and back on this + /// computer. + #[serde( + default, + rename = "organizationId", + skip_serializing_if = "Option::is_none" + )] + pub organization_id: Option, +} + +/// Whether `id` can be an organisation's id: letters, digits, `_` and `-`, at most 128. +pub fn valid_organization(id: &str) -> bool { + (1..=128).contains(&id.len()) + && id + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') +} + +impl Choice { + /// The address, when the choice is to be connected to it. + pub fn connected_to(&self) -> Option<&str> { + match self.mode { + Mode::Connected => self.address.as_deref(), + Mode::Local => None, + } + } +} + +pub fn path(config_dir: &Path) -> PathBuf { + config_dir.join(FILE) +} + +/// The choice on record. No file, or one that cannot be read, is local: the app then behaves as +/// it did before there was a choice. +pub fn read(config_dir: &Path) -> Choice { + std::fs::read(path(config_dir)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + // Connected to nothing is not connected. + .filter(|choice| choice.mode == Mode::Local || choice.address.is_some()) + .map(|mut choice| { + // The file can be edited by hand; an id that is not one is not sent anywhere. + choice.organization_id = choice.organization_id.filter(|id| valid_organization(id)); + choice + }) + .unwrap_or_default() +} + +/// Keep `choice`, replacing the file whole so a reader never sees half of one. +pub fn write(config_dir: &Path, choice: &Choice) -> std::io::Result<()> { + std::fs::create_dir_all(config_dir)?; + let target = path(config_dir); + let partial = config_dir.join(format!("{FILE}.partial")); + std::fs::write(&partial, serde_json::to_vec_pretty(choice)?)?; + std::fs::rename(&partial, &target) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_support::temp_root; + + #[test] + fn no_file_is_local_and_a_written_choice_reads_back() { + let dir = temp_root("connection-choice"); + assert_eq!(read(&dir), Choice::default()); + assert_eq!(read(&dir).mode, Mode::Local); + + let connected = Choice { + mode: Mode::Connected, + address: Some("https://openbot.example.com".into()), + organization_id: None, + }; + write(&dir, &connected).unwrap(); + assert_eq!(read(&dir), connected); + assert_eq!( + read(&dir).connected_to(), + Some("https://openbot.example.com") + ); + // The file is the agreed shape, and nothing else is written beside it. + let file: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join(FILE)).unwrap()).unwrap(); + assert_eq!( + file, + serde_json::json!({ "mode": "connected", "address": "https://openbot.example.com" }) + ); + let names: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(names, [std::ffi::OsString::from(FILE)]); + + // Back on this computer, the address is remembered and not connected to. + let local = Choice { + mode: Mode::Local, + ..connected + }; + write(&dir, &local).unwrap(); + assert_eq!(read(&dir).connected_to(), None); + assert_eq!( + read(&dir).address.as_deref(), + Some("https://openbot.example.com") + ); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn the_organisation_is_kept_beside_the_address_and_a_bad_id_is_not() { + let dir = temp_root("connection-choice-organisation"); + let chosen = Choice { + mode: Mode::Connected, + address: Some("https://openbot.example.com".into()), + organization_id: Some("org_9fK2-a".into()), + }; + write(&dir, &chosen).unwrap(); + assert_eq!(read(&dir), chosen); + let file: serde_json::Value = + serde_json::from_slice(&std::fs::read(dir.join(FILE)).unwrap()).unwrap(); + assert_eq!(file["organizationId"], "org_9fK2-a"); + + for bad in ["", "two words", "a/b", "line\nbreak", &"x".repeat(129)] { + assert!(!valid_organization(bad), "{bad:?}"); + } + assert!(valid_organization(&"x".repeat(128))); + std::fs::write( + dir.join(FILE), + r#"{"mode":"connected","address":"https://openbot.example.com","organizationId":"a b"}"#, + ) + .unwrap(); + assert_eq!(read(&dir).organization_id, None); + assert_eq!( + read(&dir).connected_to(), + Some("https://openbot.example.com") + ); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn a_file_that_cannot_be_read_or_names_no_address_is_local() { + let dir = temp_root("connection-choice-bad"); + std::fs::create_dir_all(&dir).unwrap(); + for bad in [ + "", + "not json", + r#"{"mode":"connected"}"#, + r#"{"mode":"elsewhere"}"#, + ] { + std::fs::write(dir.join(FILE), bad).unwrap(); + assert_eq!(read(&dir), Choice::default(), "{bad}"); + } + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/desktop/src-tauri/src/connected/credentials.rs b/desktop/src-tauri/src/connected/credentials.rs new file mode 100644 index 0000000000..721869266c --- /dev/null +++ b/desktop/src-tauri/src/connected/credentials.rs @@ -0,0 +1,146 @@ +//! The sign-in to an OpenBot that runs elsewhere, kept in the operating system's credential store. +//! +//! Keychain on macOS, Credential Manager on Windows, the Secret Service on Linux, through the +//! `keyring` crate. One entry per OpenBot: the service is this app's identifier and the account is +//! the normalised address. Only the refresh token is kept. The access token lives in memory for +//! its hour and is never written anywhere; nothing token-shaped is written to a file or a log. + +use super::{host_of, Kind}; +use crate::problem::Problem; +use std::sync::Arc; + +/// The service every entry is filed under: the app's identifier. +pub const SERVICE: &str = "ai.copilotkit.openbot.desktop"; + +type MakeEntry = dyn Fn(&str) -> keyring_core::Result + Send + Sync; + +/// Where sign-ins are kept. Cheap to clone; every clone is the same store. +#[derive(Clone)] +pub struct Store { + entry: Arc, +} + +impl Store { + /// The operating system's own store. + pub fn system() -> Self { + Self { + entry: Arc::new(|address| { + keyring::Entry::new(SERVICE, address).map(|entry| entry.inner) + }), + } + } + + /// A store of the caller's choosing: `keyring`'s in-memory one, in tests. + pub fn of(store: Arc) -> Self { + Self { + entry: Arc::new(move |address| store.build(SERVICE, address, None)), + } + } + + /// The refresh token kept for `address`, or None when there is no sign-in for it. + pub fn get(&self, address: &str) -> Result, Problem> { + match (self.entry)(address).and_then(|entry| entry.get_password()) { + Ok(token) if token.is_empty() => Ok(None), + Ok(token) => Ok(Some(token)), + Err(keyring_core::Error::NoEntry) => Ok(None), + Err(error) => Err(refused(address, "read", &error)), + } + } + + /// Keep `refresh_token` as the sign-in for `address`, in place of any earlier one. + pub fn set(&self, address: &str, refresh_token: &str) -> Result<(), Problem> { + (self.entry)(address) + .and_then(|entry| entry.set_password(refresh_token)) + .map_err(|error| refused(address, "save", &error)) + } + + /// Forget the sign-in for `address`. Forgetting one that is not there is not a failure. + pub fn forget(&self, address: &str) -> Result<(), Problem> { + match (self.entry)(address).and_then(|entry| entry.delete_credential()) { + Ok(()) | Err(keyring_core::Error::NoEntry) => Ok(()), + Err(error) => Err(refused(address, "remove", &error)), + } + } +} + +/// The store's own words go to the log. They name the failure, never the secret: `keyring`'s +/// errors carry no credential except `BadEncoding`, whose bytes are left out here. +fn refused(address: &str, what: &str, error: &keyring_core::Error) -> Problem { + let detail = match error { + keyring_core::Error::BadEncoding(_) => "the stored sign-in is not text".to_owned(), + keyring_core::Error::BadDataFormat(_, _) => "the stored sign-in is not readable".to_owned(), + other => other.to_string(), + }; + Kind::CredentialStore.problem( + &host_of(address), + format!("could not {what} the sign-in in the credential store: {detail}"), + ) +} + +#[cfg(test)] +pub(crate) fn in_memory() -> Store { + Store::of(keyring_core::mock::Store::new().expect("keyring's in-memory store")) +} + +#[cfg(test)] +mod tests { + use super::super::kind_of; + use super::*; + + const ADDRESS: &str = "https://openbot.example.com"; + + // Built at run time, so no token-shaped literal sits in the source for a scanner to stop. + fn refresh_token(body: &str) -> String { + format!("obr_{}", body.repeat(8)) + } + + #[test] + fn a_sign_in_is_kept_per_address_replaced_and_forgotten() { + let store = in_memory(); + assert_eq!(store.get(ADDRESS).unwrap(), None); + store.forget(ADDRESS).expect("forgetting nothing is fine"); + + let first = refresh_token("Ab3x"); + store.set(ADDRESS, &first).unwrap(); + assert_eq!(store.get(ADDRESS).unwrap(), Some(first)); + // Another OpenBot has a sign-in of its own. + assert_eq!(store.get("https://other.example.com").unwrap(), None); + + let second = refresh_token("Zq9k"); + store.set(ADDRESS, &second).unwrap(); + assert_eq!(store.clone().get(ADDRESS).unwrap(), Some(second)); + + store.forget(ADDRESS).unwrap(); + assert_eq!(store.get(ADDRESS).unwrap(), None); + } + + /// A store that refuses (a locked keychain, a Credential Manager that is turned off) is said + /// as that, with the next thing to do, and its failure never repeats the token. + #[test] + fn a_store_that_refuses_says_so_without_the_token() { + let mock = keyring_core::mock::Store::new().unwrap(); + let store = Store::of(mock.clone()); + let entry = { + use keyring_core::api::CredentialStoreApi; + mock.build(SERVICE, ADDRESS, None).unwrap() + }; + let cred: &keyring_core::mock::Cred = entry.as_any().downcast_ref().unwrap(); + cred.set_error(keyring_core::Error::NoStorageAccess( + "the keychain is locked".into(), + )); + let token = refresh_token("Lm4p"); + let problem = store.set(ADDRESS, &token).expect_err("the store refused"); + assert_eq!(kind_of(&problem), Some(Kind::CredentialStore)); + assert_eq!( + problem.said, + if cfg!(windows) { + "OpenBot couldn't save your sign-in on this computer. Check Windows Credential Manager, then try again." + } else { + "OpenBot couldn't save your sign-in on this computer. Unlock your keychain, then try again." + } + ); + let detail = problem.detail.unwrap(); + assert!(detail.contains("the keychain is locked"), "{detail}"); + assert!(!detail.contains(&token), "{detail}"); + } +} diff --git a/desktop/src-tauri/src/connected/fake_openbot.rs b/desktop/src-tauri/src/connected/fake_openbot.rs new file mode 100644 index 0000000000..72d87c0848 --- /dev/null +++ b/desktop/src-tauri/src/connected/fake_openbot.rs @@ -0,0 +1,775 @@ +/*! +A stand-in for an OpenBot that runs elsewhere, for this module's tests: a real HTTP server on a +loopback port that answers the addresses the app uses as the real one does. + +- the public deployment answer and the authorization server metadata (RFC 8414), at the real paths; +- the authorization endpoint, which accepts only the public client, `response_type=code`, an S256 + challenge and a redirect of exactly `http://127.0.0.1:/callback`, and sends the browser + back with a code or with `error=access_denied`; +- the token endpoint: form-encoded, the client's id in the body, the verifier really checked + against the challenge, a code that burns on its first use (right or wrong), and refresh tokens + that rotate, where one used a second time answers `invalid_grant` and ends the family; +- revocation (RFC 7009); +- `/api/me` and a few `/api/v2` addresses that honour a Bearer access token and nothing else, one + of them a stream and one a WebSocket. + +And a stand-in for the person's browser (`Browser`), which follows the authorization address the +app opens and the redirect back to the app's listener. +*/ + +use super::address::Metadata; +use super::credentials::Store; +use super::sign_in::{self, Attempt, Session}; +use super::CLIENT_ID; +use crate::provider_oauth::{pkce_challenge, random}; +use bytes::Bytes; +use futures_util::{SinkExt, StreamExt}; +use http_body_util::{combinators::BoxBody, BodyExt, Full, StreamBody}; +use hyper::body::{Frame, Incoming}; +use hyper::{Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use std::collections::{HashMap, HashSet}; +use std::convert::Infallible; +use std::io::{Read, Write}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// What is listening at the address. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Shape { + /// An OpenBot this app can connect to. + Current, + /// Some other website: every address answers a page. + WebPage, + /// Some other service that answers JSON. + OtherJson, + /// An OpenBot somebody is trying on their own computer. + LocalEvaluation, + /// The personal edition: one person, no sign-in. + Personal, + /// A team's OpenBot from before apps could sign in. + NoMetadata, + /// Metadata whose endpoints are on another host. + MetadataElsewhere, + /// Every address redirects to the same path at another address. + RedirectsTo(String), + /// Signs the app in, and then refuses the token on `/api/me`. + MeRefuses, +} + +const SCOPES: [&str; 4] = ["openid", "profile", "offline_access", "openbot"]; + +/// One request as the server received it. +#[derive(Clone, Debug)] +pub struct Seen { + pub method: String, + pub path: String, + pub headers: Vec<(String, String)>, +} + +impl Seen { + pub fn header(&self, name: &str) -> Option<&str> { + self.headers + .iter() + .find(|(header, _)| header.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.as_str()) + } +} + +struct Code { + challenge: String, + redirect: String, +} + +#[derive(Default)] +struct State { + seen: Vec, + codes: HashMap, + access: HashSet, + /// Every refresh token ever issued, and whether it is the current one. + refresh: HashMap, + token_requests: Vec>, + revoke_requests: Vec>, + token_delay: Duration, +} + +pub struct FakeOpenBot { + address: String, + state: Arc>, + _runtime: tokio::runtime::Runtime, +} + +type Body = BoxBody; + +fn full(body: impl Into) -> Body { + Full::new(body.into()).boxed() +} + +fn json(status: StatusCode, value: serde_json::Value) -> Response { + Response::builder() + .status(status) + .header("content-type", "application/json") + .body(full(value.to_string())) + .unwrap() +} + +fn oauth_error(error: &str, description: &str) -> Response { + json( + StatusCode::BAD_REQUEST, + serde_json::json!({ "error": error, "error_description": description }), + ) +} + +fn form(body: &[u8]) -> HashMap { + reqwest::Url::parse(&format!("http://form/?{}", String::from_utf8_lossy(body))) + .map(|url| url.query_pairs().into_owned().collect()) + .unwrap_or_default() +} + +fn loopback_callback(redirect: &str) -> bool { + reqwest::Url::parse(redirect).is_ok_and(|url| { + url.scheme() == "http" + && url.host_str() == Some("127.0.0.1") + && url.port().is_some() + && url.path() == "/callback" + && url.query().is_none() + }) +} + +impl FakeOpenBot { + pub fn start(shape: Shape) -> Self { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let address = format!("http://{}", listener.local_addr().unwrap()); + let state = Arc::new(Mutex::new(State::default())); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let (serving_state, serving_address) = (state.clone(), address.clone()); + runtime.spawn(async move { + let listener = tokio::net::TcpListener::from_std(listener).unwrap(); + loop { + let Ok((stream, _)) = listener.accept().await else { + return; + }; + let (state, address, shape) = ( + serving_state.clone(), + serving_address.clone(), + shape.clone(), + ); + tokio::spawn(async move { + let service = hyper::service::service_fn(move |request| { + answer(request, state.clone(), address.clone(), shape.clone()) + }); + let _ = hyper::server::conn::http1::Builder::new() + .serve_connection(TokioIo::new(stream), service) + .with_upgrades() + .await; + }); + } + }); + Self { + address, + state, + _runtime: runtime, + } + } + + pub fn address(&self) -> String { + self.address.clone() + } + + /// Every request received, as `GET /path`. + pub fn requests(&self) -> Vec { + self.seen() + .iter() + .map(|seen| format!("{} {}", seen.method, seen.path)) + .collect() + } + + pub fn seen(&self) -> Vec { + self.state.lock().unwrap().seen.clone() + } + + /// The requests received for `path`. + pub fn seen_at(&self, path: &str) -> Vec { + self.seen() + .into_iter() + .filter(|seen| seen.path == path) + .collect() + } + + pub fn honours(&self, access: &str) -> bool { + self.state.lock().unwrap().access.contains(access) + } + + pub fn token_requests(&self) -> Vec> { + self.state.lock().unwrap().token_requests.clone() + } + + pub fn revoke_requests(&self) -> Vec> { + self.state.lock().unwrap().revoke_requests.clone() + } + + /// Access tokens and current refresh tokens that still work. + pub fn live_tokens(&self) -> usize { + let state = self.state.lock().unwrap(); + state.access.len() + state.refresh.values().filter(|current| **current).count() + } + + /// A code as the authorization endpoint issues one, for a test that exchanges it itself. + pub fn issue_code(&self, challenge: &str, redirect: &str) -> String { + let code = random(); + self.state.lock().unwrap().codes.insert( + code.clone(), + Code { + challenge: challenge.into(), + redirect: redirect.into(), + }, + ); + code + } + + /// What the authorization endpoint says to a request with `redirect` as its redirect. + pub fn authorize_refuses(&self, redirect: &str) -> String { + let mut url = + reqwest::Url::parse(&format!("{}/api/auth/oauth2/authorize", self.address)).unwrap(); + url.query_pairs_mut().extend_pairs([ + ("response_type", "code"), + ("client_id", CLIENT_ID), + ("redirect_uri", redirect), + ("scope", "openid offline_access"), + ("state", "state"), + ("code_challenge", &pkce_challenge("verifier")), + ("code_challenge_method", "S256"), + ]); + let answered = no_redirects() + .get(url) + .header("x-fake-person", "approve") + .send() + .unwrap(); + assert_eq!(answered.status(), 400); + answered.text().unwrap() + } + + /// Every access token stops working, as after its hour. Refresh tokens still work. + pub fn expire_access_tokens(&self) { + self.state.lock().unwrap().access.clear(); + } + + /// Signed out elsewhere, or removed: nothing issued so far works any more. + pub fn end_sessions(&self) { + let mut state = self.state.lock().unwrap(); + state.access.clear(); + for current in state.refresh.values_mut() { + *current = false; + } + } + + pub fn slow_token_endpoint(&self, delay: Duration) { + self.state.lock().unwrap().token_delay = delay; + } + + pub fn metadata(&self) -> Metadata { + super::address::probe(&self.address).unwrap() + } + + /// A whole sign-in with a person who approves. + pub fn sign_in(&self, store: Store) -> Session { + let browser = Browser::approves(); + let session = sign_in::sign_in( + &self.address, + &self.metadata(), + store, + &Attempt::default(), + Duration::from_secs(20), + browser.opener(), + ) + .unwrap(); + browser.tab(); + session + } +} + +fn bearer(request: &Request) -> Option { + request + .headers() + .get("authorization")? + .to_str() + .ok()? + .strip_prefix("Bearer ") + .map(str::to_owned) +} + +async fn answer( + request: Request, + state: Arc>, + address: String, + shape: Shape, +) -> Result, Infallible> { + let method = request.method().as_str().to_owned(); + let path = request.uri().path().to_owned(); + let query = request.uri().query().unwrap_or("").to_owned(); + let headers: Vec<(String, String)> = request + .headers() + .iter() + .map(|(name, value)| { + ( + name.as_str().to_owned(), + value.to_str().unwrap_or("").to_owned(), + ) + }) + .collect(); + state.lock().unwrap().seen.push(Seen { + method: method.clone(), + path: path.clone(), + headers: headers.clone(), + }); + + match &shape { + Shape::WebPage => { + return Ok(Response::builder() + .header("content-type", "text/html") + .body(full("A website")) + .unwrap()) + } + Shape::OtherJson => { + return Ok(json( + StatusCode::OK, + serde_json::json!({ "name": "some other service", "version": 3 }), + )) + } + Shape::RedirectsTo(other) => { + return Ok(Response::builder() + .status(StatusCode::FOUND) + .header("location", format!("{other}{path}")) + .body(full("")) + .unwrap()) + } + _ => {} + } + + let authorized = bearer(&request).filter(|token| state.lock().unwrap().access.contains(token)); + let refused = || { + json( + StatusCode::UNAUTHORIZED, + serde_json::json!({ "error": "unauthorized" }), + ) + }; + Ok(match (method.as_str(), path.as_str()) { + ("GET", "/api/v2/organizations/default/deployment") => json( + StatusCode::OK, + serde_json::json!({ + "edition": if shape == Shape::Personal { "personal" } else { "team" }, + "localEvaluation": shape == Shape::LocalEvaluation, + "generativeUi": true, + "authProviders": ["google"], + "ssoConfigured": false, + "ssoRequired": false, + }), + ), + ("GET", "/.well-known/oauth-authorization-server/api/auth") => { + if matches!( + shape, + Shape::NoMetadata | Shape::Personal | Shape::LocalEvaluation + ) { + return Ok(json( + StatusCode::NOT_FOUND, + serde_json::json!({ "error": "not_found" }), + )); + } + let home = if shape == Shape::MetadataElsewhere { + "https://elsewhere.example".to_owned() + } else { + address.clone() + }; + json( + StatusCode::OK, + serde_json::json!({ + "issuer": format!("{address}/api/auth"), + "authorization_endpoint": format!("{home}/api/auth/oauth2/authorize"), + "token_endpoint": format!("{home}/api/auth/oauth2/token"), + "revocation_endpoint": format!("{home}/api/auth/oauth2/revoke"), + "scopes_supported": SCOPES, + "response_types_supported": ["code"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": ["none"], + }), + ) + } + ("GET", "/api/auth/oauth2/authorize") => { + let asked = form(query.as_bytes()); + let get = |name: &str| asked.get(name).map(String::as_str).unwrap_or(""); + let redirect = get("redirect_uri"); + if get("client_id") != CLIENT_ID { + return Ok(oauth_error("invalid_client", "unknown client_id")); + } + if !loopback_callback(redirect) { + return Ok(oauth_error( + "invalid_request", + "redirect_uri must be http://127.0.0.1:/callback", + )); + } + if get("response_type") != "code" + || get("code_challenge").is_empty() + || get("code_challenge_method") != "S256" + || get("state").is_empty() + { + return Ok(oauth_error( + "invalid_request", + "code, S256 and state are required", + )); + } + if !get("scope").split(' ').all(|scope| SCOPES.contains(&scope)) { + return Ok(oauth_error("invalid_scope", "unknown scope")); + } + // The person, signed in to OpenBot in their browser, answering the consent screen. + let approves = headers + .iter() + .any(|(name, value)| name == "x-fake-person" && value == "approve"); + let mut back = reqwest::Url::parse(redirect).unwrap(); + if approves { + let code = random(); + state.lock().unwrap().codes.insert( + code.clone(), + Code { + challenge: get("code_challenge").into(), + redirect: redirect.into(), + }, + ); + back.query_pairs_mut().append_pair("code", &code); + } else { + back.query_pairs_mut().append_pair("error", "access_denied"); + } + back.query_pairs_mut().append_pair("state", get("state")); + Response::builder() + .status(StatusCode::FOUND) + .header("location", back.as_str()) + .body(full("")) + .unwrap() + } + ("POST", "/api/auth/oauth2/token") => { + let encoded = headers.iter().any(|(name, value)| { + name == "content-type" && value.starts_with("application/x-www-form-urlencoded") + }); + let body = request.into_body().collect().await.unwrap().to_bytes(); + let sent = form(&body); + let delay = { + let mut state = state.lock().unwrap(); + state.token_requests.push(sent.clone()); + state.token_delay + }; + tokio::time::sleep(delay).await; + if !encoded { + return Ok(oauth_error("invalid_request", "the body must be a form")); + } + let get = |name: &str| sent.get(name).map(String::as_str).unwrap_or(""); + if get("client_id") != CLIENT_ID { + return Ok(oauth_error( + "invalid_client", + "client_id is required in the body", + )); + } + let mut state = state.lock().unwrap(); + let granted = match get("grant_type") { + "authorization_code" => { + // Burned whatever comes next: a code is good for one try. + let code = state.codes.remove(get("code")); + code.is_some_and(|code| { + code.redirect == get("redirect_uri") + && code.challenge == pkce_challenge(get("code_verifier")) + }) + } + "refresh_token" => match state.refresh.get(get("refresh_token")).copied() { + Some(true) => { + state.refresh.insert(get("refresh_token").to_owned(), false); + true + } + // Used a second time: the whole family ends. + Some(false) => { + state.access.clear(); + for current in state.refresh.values_mut() { + *current = false; + } + false + } + None => false, + }, + _ => return Ok(oauth_error("unsupported_grant_type", "unknown grant")), + }; + if !granted { + return Ok(oauth_error("invalid_grant", "the grant is not valid")); + } + let access = format!("oba_{}", random()); + let refresh = format!("obr_{}", random()); + state.access.insert(access.clone()); + state.refresh.insert(refresh.clone(), true); + json( + StatusCode::OK, + serde_json::json!({ + "access_token": access, + "refresh_token": refresh, + "token_type": "Bearer", + "expires_in": 3600, + "scope": SCOPES.join(" "), + }), + ) + } + ("POST", "/api/auth/oauth2/revoke") => { + let body = request.into_body().collect().await.unwrap().to_bytes(); + let sent = form(&body); + let mut state = state.lock().unwrap(); + state.revoke_requests.push(sent.clone()); + if sent.get("client_id").map(String::as_str) != Some(CLIENT_ID) { + return Ok(oauth_error( + "invalid_client", + "client_id is required in the body", + )); + } + if let Some(token) = sent.get("token") { + state.access.remove(token); + if let Some(current) = state.refresh.get_mut(token) { + *current = false; + } + } + // RFC 7009 §2.2: 200 whether or not the token was known. + json(StatusCode::OK, serde_json::json!({})) + } + ("GET", "/api/me") => match authorized { + Some(_) if shape != Shape::MeRefuses => { + json(StatusCode::OK, serde_json::json!({ "id": "person-1" })) + } + _ => refused(), + }, + (_, "/api/v2/echo") => { + if authorized.is_none() { + return Ok(refused()); + } + let body = request.into_body().collect().await.unwrap().to_bytes(); + json( + StatusCode::OK, + serde_json::json!({ + "method": method, + "query": query, + "headers": headers.iter().cloned().collect::>(), + "body": String::from_utf8_lossy(&body), + }), + ) + } + ("GET", "/api/v2/stream") => { + if authorized.is_none() { + return Ok(refused()); + } + // Three events, a moment apart, as a chat answer arrives. + let events = futures_util::stream::unfold(0u8, |sent| async move { + if sent == 3 { + return None; + } + if sent > 0 { + tokio::time::sleep(Duration::from_millis(400)).await; + } + let event = Bytes::from(format!("data: {sent}\n\n")); + Some((Ok::<_, Infallible>(Frame::data(event)), sent + 1)) + }); + Response::builder() + .header("content-type", "text/event-stream") + .body(BodyExt::boxed(StreamBody::new(events))) + .unwrap() + } + ("GET", "/api/v2/cookie") => Response::builder() + .header("set-cookie", "better-auth.session_token=upstream; Path=/") + .header("content-type", "text/plain") + .body(full("ok")) + .unwrap(), + ("GET", "/api/v2/home") => Response::builder() + .status(StatusCode::FOUND) + .header("location", format!("{address}/landing?from=home#top")) + .body(full("")) + .unwrap(), + ("GET", "/api/v2/away") => Response::builder() + .status(StatusCode::FOUND) + .header("location", "https://elsewhere.example/page") + .body(full("")) + .unwrap(), + ("GET", "/api/v2/socket") => { + let key = headers + .iter() + .find(|(name, _)| name == "sec-websocket-key") + .map(|(_, value)| value.clone()); + let (Some(_), Some(key)) = (authorized, key) else { + return Ok(refused()); + }; + let accept = + tokio_tungstenite::tungstenite::handshake::derive_accept_key(key.as_bytes()); + tokio::spawn(async move { + let Ok(upgraded) = hyper::upgrade::on(request).await else { + return; + }; + let mut socket = tokio_tungstenite::WebSocketStream::from_raw_socket( + TokioIo::new(upgraded), + tokio_tungstenite::tungstenite::protocol::Role::Server, + None, + ) + .await; + while let Some(Ok(message)) = socket.next().await { + if message.is_text() || message.is_binary() { + let echoed = format!("echo: {}", message.to_text().unwrap_or("")); + if socket.send(echoed.into()).await.is_err() { + return; + } + } + } + }); + Response::builder() + .status(StatusCode::SWITCHING_PROTOCOLS) + .header("connection", "Upgrade") + .header("upgrade", "websocket") + .header("sec-websocket-accept", accept) + .body(full("")) + .unwrap() + } + ("GET", "/" | "/landing") => Response::builder() + .header("content-type", "text/html") + .body(full("OpenBot")) + .unwrap(), + _ => json( + StatusCode::NOT_FOUND, + serde_json::json!({ "error": "not_found" }), + ), + }) +} + +fn no_redirects() -> reqwest::blocking::Client { + reqwest::blocking::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(10)) + .build() + .unwrap() +} + +/// One plain request over a socket, and everything that came back, status line and all. +pub fn raw_request(to: &str, request: &str) -> String { + let mut stream = std::net::TcpStream::connect(to).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(10))) + .unwrap(); + stream.write_all(request.as_bytes()).unwrap(); + let mut answer = Vec::new(); + let _ = stream.read_to_end(&mut answer); + String::from_utf8_lossy(&answer).into_owned() +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Person { + Approves, + Denies, + /// Something else on this computer answers the listener first, with a `state` it made up. + ForgedStateFirst, +} + +#[derive(Default)] +struct Visit { + asked: HashMap, + tab: String, + forged: String, +} + +/// The person's browser: opens the authorization address, lets the person answer, and follows +/// the redirect back to the app's listener. +pub struct Browser { + person: Person, + visit: Arc>, + done: Arc>>>, +} + +impl Browser { + fn with(person: Person) -> Self { + Self { + person, + visit: Arc::default(), + done: Arc::default(), + } + } + + pub fn approves() -> Self { + Self::with(Person::Approves) + } + + pub fn denies() -> Self { + Self::with(Person::Denies) + } + + pub fn forges_state_first() -> Self { + Self::with(Person::ForgedStateFirst) + } + + /// What the app hands the system: the address to open. + pub fn opener(&self) -> impl FnOnce(&str) -> Result<(), String> + 'static { + let (person, visit, done) = (self.person, self.visit.clone(), self.done.clone()); + move |address: &str| { + let address = reqwest::Url::parse(address).map_err(|error| error.to_string())?; + let finished = done.clone(); + *finished.lock().unwrap() = Some(std::thread::spawn(move || { + let asked: HashMap = address.query_pairs().into_owned().collect(); + let listener = reqwest::Url::parse(&asked["redirect_uri"]).unwrap(); + let listener = format!("127.0.0.1:{}", listener.port().unwrap()); + visit.lock().unwrap().asked = asked; + let get = |target: &str| { + raw_request( + &listener, + &format!("GET {target} HTTP/1.1\r\nHost: {listener}\r\n\r\n"), + ) + }; + if person == Person::ForgedStateFirst { + let forged = get("/callback?code=forged-code&state=made-up"); + visit.lock().unwrap().forged = forged; + } + let sent_back = no_redirects() + .get(address) + .header( + "x-fake-person", + if person == Person::Denies { + "deny" + } else { + "approve" + }, + ) + .send() + .unwrap(); + assert_eq!(sent_back.status(), 302, "{:?}", sent_back.text()); + let back = + reqwest::Url::parse(sent_back.headers()["location"].to_str().unwrap()).unwrap(); + let tab = get(&format!("{}?{}", back.path(), back.query().unwrap_or(""))); + visit.lock().unwrap().tab = tab; + })); + Ok(()) + } + } + + fn finish(&self) { + if let Some(visit) = self.done.lock().unwrap().take() { + visit.join().unwrap(); + } + } + + /// The authorization request's parameters. + pub fn asked(&self) -> HashMap { + self.finish(); + self.visit.lock().unwrap().asked.clone() + } + + /// What the tab showed at the end. + pub fn tab(&self) -> String { + self.finish(); + self.visit.lock().unwrap().tab.clone() + } + + /// What the forged callback was answered. + pub fn forged_answer(&self) -> String { + self.finish(); + self.visit.lock().unwrap().forged.clone() + } +} diff --git a/desktop/src-tauri/src/connected/mod.rs b/desktop/src-tauri/src/connected/mod.rs new file mode 100644 index 0000000000..51026de217 --- /dev/null +++ b/desktop/src-tauri/src/connected/mod.rs @@ -0,0 +1,215 @@ +/*! +OpenBot Desktop connected to an OpenBot that runs somewhere else. + +The person types one address. The app signs in to that OpenBot in the system browser (OAuth 2.1 +authorization code with PKCE and a loopback redirect, `sign_in`), keeps the sign-in in the operating +system's credential store (`credentials`), and shows that OpenBot's own pages in the window through +a relay on `127.0.0.1` (`relay`), which is the only thing that ever holds a token. Nothing of a local +installation is started, read or written while the app is connected. + +- `choice`: which of the two the person chose, in `connection.json`. +- `address`: a typed address made into one the app can use, and checked to be an OpenBot it can + connect to. +- `sign_in`: the browser sign-in, the token exchange, refresh and sign-out. +- `credentials`: the refresh token, in Keychain, Credential Manager or the Secret Service. +- `relay`: the loopback HTTP server the window loads. +*/ + +pub mod address; +pub mod choice; +pub mod credentials; +pub mod relay; +pub mod sign_in; + +#[cfg(test)] +pub(crate) mod fake_openbot; + +use crate::problem::Problem; + +/// The public client this app signs in as. It has no secret. +pub const CLIENT_ID: &str = "openbot-desktop-oauth"; + +/// Why a connection could not be made or kept, for the window to choose what to offer next. The +/// sentence for each is written here, once, and the window shows it as given. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + AddressInvalid, + Unreachable, + NotOpenBot, + SinglePerson, + TooOld, + SignInCancelled, + SignInFailed, + SessionEnded, + CredentialStore, +} + +impl Kind { + pub fn id(self) -> &'static str { + match self { + Kind::AddressInvalid => "address-invalid", + Kind::Unreachable => "unreachable", + Kind::NotOpenBot => "not-openbot", + Kind::SinglePerson => "single-person", + Kind::TooOld => "too-old", + Kind::SignInCancelled => "sign-in-cancelled", + Kind::SignInFailed => "sign-in-failed", + Kind::SessionEnded => "session-ended", + Kind::CredentialStore => "credential-store", + } + } + + /// The sentence for the person. `host` is the OpenBot's, as they typed it. + pub fn said(self, host: &str) -> String { + match self { + Kind::AddressInvalid => "That isn't an address OpenBot can connect to. Use one that \ + starts with https://, such as https://openbot.example.com." + .into(), + Kind::Unreachable => format!( + "OpenBot couldn't reach {host}. Check the address and your network, then try again." + ), + Kind::NotOpenBot => format!( + "There's no OpenBot at {host}. Check the address with whoever runs your OpenBot." + ), + Kind::SinglePerson => format!( + "The OpenBot at {host} is set up for one person on its own computer, so the app \ + can't connect to it." + ), + Kind::TooOld => format!( + "The OpenBot at {host} is on a release this app can't connect to yet. Ask whoever \ + runs it to update OpenBot, or open it in your browser." + ), + Kind::SignInCancelled => "Sign-in didn't finish. Try again when you're ready.".into(), + Kind::SignInFailed => format!( + "OpenBot couldn't sign you in at {host}. Try again, or ask whoever runs your OpenBot." + ), + Kind::SessionEnded => { + format!("Your sign-in to {host} has ended. Sign in again to keep going.") + } + Kind::CredentialStore => if cfg!(windows) { + "OpenBot couldn't save your sign-in on this computer. Check Windows Credential \ + Manager, then try again." + } else { + "OpenBot couldn't save your sign-in on this computer. Unlock your keychain, then \ + try again." + } + .into(), + } + } + + /// The problem the window is given: the sentence, this kind, and `detail` for the log. Never a + /// token: callers pass a status, an error code or a transport error. + pub fn problem(self, host: &str, detail: impl Into) -> Problem { + let mut problem = Problem::with(self.said(host), detail); + problem.kind = Some(self.id()); + problem + } +} + +/// Which kind a problem from this module is, when it is one. +pub fn kind_of(problem: &Problem) -> Option { + [ + Kind::AddressInvalid, + Kind::Unreachable, + Kind::NotOpenBot, + Kind::SinglePerson, + Kind::TooOld, + Kind::SignInCancelled, + Kind::SignInFailed, + Kind::SessionEnded, + Kind::CredentialStore, + ] + .into_iter() + .find(|kind| problem.kind == Some(kind.id())) +} + +/// The host of a normalised address, as the sentences name it: `openbot.example.com`, with its +/// port when it has one. +pub fn host_of(address: &str) -> String { + reqwest::Url::parse(address) + .ok() + .and_then(|url| { + let host = url.host_str()?.to_owned(); + Some(match url.port() { + Some(port) => format!("{host}:{port}"), + None => host, + }) + }) + .unwrap_or_else(|| address.to_owned()) +} + +/// A client for the few requests the shell itself makes to that OpenBot: short timeouts, and a +/// redirect followed only while it stays on the same host. +pub(crate) fn http() -> Result { + reqwest::blocking::Client::builder() + .connect_timeout(std::time::Duration::from_secs(10)) + .timeout(std::time::Duration::from_secs(20)) + .redirect(reqwest::redirect::Policy::custom(|attempt| { + let same_host = attempt.previous().last().is_some_and(|from| { + from.scheme() == attempt.url().scheme() + && from.host_str() == attempt.url().host_str() + && from.port_or_known_default() == attempt.url().port_or_known_default() + }); + if same_host && attempt.previous().len() < 5 { + attempt.follow() + } else { + attempt.stop() + } + })) + .user_agent("OpenBot/desktop") + .build() + .map_err(|error| error.to_string()) +} + +/// A transport error without the address's query, which a sign-in address carries a code in. +pub(crate) fn transport(error: reqwest::Error) -> String { + let error = error.without_url(); + let mut said = error.to_string(); + let mut source = std::error::Error::source(&error); + while let Some(inner) = source { + said.push_str(": "); + said.push_str(&inner.to_string()); + source = inner.source(); + } + said +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The window reads `kind` beside the sentence, and the sentences are the agreed ones. + #[test] + fn a_problem_carries_its_kind_and_the_agreed_sentence() { + let problem = Kind::Unreachable.problem("openbot.example.com", "connection refused"); + let sent = serde_json::to_value(&problem).unwrap(); + assert_eq!(sent["kind"], "unreachable"); + assert_eq!( + sent["said"], + "OpenBot couldn't reach openbot.example.com. Check the address and your network, then try again." + ); + assert_eq!(sent["detail"], "connection refused"); + assert_eq!(kind_of(&problem), Some(Kind::Unreachable)); + // A problem from anywhere else carries none, and reads as it always did. + let plain = serde_json::to_value(Problem::plain("OpenBot has stopped.")).unwrap(); + assert!(plain.get("kind").is_none()); + assert_eq!( + Kind::SessionEnded.said("openbot.example.com"), + "Your sign-in to openbot.example.com has ended. Sign in again to keep going." + ); + assert_eq!( + Kind::TooOld.said("127.0.0.1:4000"), + "The OpenBot at 127.0.0.1:4000 is on a release this app can't connect to yet. Ask whoever runs it to update OpenBot, or open it in your browser." + ); + } + + #[test] + fn the_host_is_named_with_its_port_when_it_has_one() { + assert_eq!( + host_of("https://openbot.example.com"), + "openbot.example.com" + ); + assert_eq!(host_of("http://127.0.0.1:4000"), "127.0.0.1:4000"); + assert_eq!(host_of("http://[::1]:4000"), "[::1]:4000"); + } +} diff --git a/desktop/src-tauri/src/connected/relay.rs b/desktop/src-tauri/src/connected/relay.rs new file mode 100644 index 0000000000..0976a2e12d --- /dev/null +++ b/desktop/src-tauri/src/connected/relay.rs @@ -0,0 +1,1171 @@ +/*! +The relay between the window and an OpenBot that runs elsewhere. + +The window's page cannot hold a token, and that OpenBot sends no CORS headers, so the window loads +the app from `http://127.0.0.1:/` and this server passes each request on to the one address +the person typed, with `Authorization: Bearer ` added. The page never sees the token. + +What keeps it to that: + +- It listens on `127.0.0.1` only, at a port the system picks. Never `0.0.0.0`, never `[::1]`. +- A request whose `Host` is not exactly its own `127.0.0.1:` is refused (421): a name that + resolves here (DNS rebinding) is not this relay. +- A request from another site is refused (403): an `Origin` other than its own, or + `Sec-Fetch-Site: cross-site` or `same-site`. +- Every request needs a secret only the window has. The shell makes one per run and opens the + window at `ENTER_PATH` with it; the relay answers with a cookie (`HttpOnly`, `SameSite=Strict`) + and from then on refuses (403) anything that does not carry it. A page in the person's browser, + or another program on this computer, has no way to learn it. +- It forwards to the typed address and nowhere else: only origin-form request targets (no absolute + URL, no CONNECT), and a redirect is handed back to the page, never followed. +- On the way out it drops `Origin`, `Cookie`, `Referer`, `Forwarded` and `X-Forwarded-*`, and any + `Authorization` the page sent. On the way back it drops `Set-Cookie`. + +Bodies are passed on as they arrive, both ways, so a chat answer streams. A WebSocket upgrade is +passed on and the two connections are joined. + +The access token is replaced shortly before it ends, and when that OpenBot answers 401 to a request +with no body the request is sent once more with a new one. When the refresh itself is refused the +sign-in is over: the relay says so once (`Ended::SessionEnded`) and stops answering. +*/ + +use super::sign_in::Session; +use super::{kind_of, Kind}; +use bytes::Bytes; +use futures_util::StreamExt; +use http_body_util::{combinators::BoxBody, BodyExt, Empty, Full, StreamBody}; +use hyper::body::{Frame, Incoming}; +use hyper::header::{self, HeaderMap, HeaderName, HeaderValue}; +use hyper::{Method, Request, Response, StatusCode}; +use hyper_util::rt::TokioIo; +use std::net::{Ipv4Addr, SocketAddr}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +/// Where the window first goes, with the run's secret as `key`. Nothing under this prefix is ever +/// forwarded. +pub const ENTER_PATH: &str = "/.openbot-relay/enter"; +const OWN_PREFIX: &str = "/.openbot-relay/"; +/// The cookie that carries the run's secret from the window. +pub const COOKIE: &str = "openbot-relay"; + +/// The request header that names the organisation the person is working in. A token carries no +/// session, and a person can belong to several, so every request says which. Set by the shell +/// from the person's choice (`choice::Choice::organization_id`), never taken from the page. +pub const ORGANIZATION_HEADER: &str = "OpenBot-Organization"; + +fn organization_header(organization: Option<&str>) -> Option { + organization + .filter(|id| super::choice::valid_organization(id)) + .and_then(|id| HeaderValue::from_str(id).ok()) +} + +/// Why the connection stopped working, told to the shell. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ended { + /// The refresh was refused. The relay has stopped answering. + SessionEnded, + /// The OpenBot did not answer. The relay keeps going; said at most once in a while. + Unreachable, +} + +/// How often `Ended::Unreachable` is said while the OpenBot stays unreachable. +const UNREACHABLE_SAID_EVERY: Duration = Duration::from_secs(30); + +type Body = BoxBody>; +type OnEnded = dyn Fn(Ended) + Send + Sync; + +struct Shared { + session: Arc, + /// `127.0.0.1:`, the only `Host` answered. + host: String, + /// `http://127.0.0.1:`, the only `Origin` answered. + origin: String, + upstream: reqwest::Url, + secret: String, + client: reqwest::Client, + organization: Arc>>, + on_ended: Box, + session_ended: AtomicBool, + unreachable_said: Mutex>, + stop: tokio::sync::watch::Sender, +} + +/// A running relay. Dropping it stops it. +pub struct Relay { + address: SocketAddr, + secret: String, + organization: Arc>>, + stop: tokio::sync::watch::Sender, + runtime: Option, +} + +impl Relay { + /// Start a relay for `session`, on `127.0.0.1` at a port the system picks, naming + /// `organization` on every request when there is one. + pub fn start( + session: Arc, + organization: Option<&str>, + on_ended: impl Fn(Ended) + Send + Sync + 'static, + ) -> Result { + let organization = Arc::new(Mutex::new(organization_header(organization))); + let upstream = reqwest::Url::parse(session.address()).map_err(|error| error.to_string())?; + let listener = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .and_then(|listener| listener.set_nonblocking(true).map(|()| listener)) + .map_err(|error| format!("could not listen on 127.0.0.1: {error}"))?; + let address = listener.local_addr().map_err(|error| error.to_string())?; + // No whole-request timeout: a chat answer and a socket stay open for as long as they do. + let client = reqwest::Client::builder() + .connect_timeout(Duration::from_secs(15)) + .redirect(reqwest::redirect::Policy::none()) + .http1_only() + .user_agent("OpenBot/desktop") + .build() + .map_err(|error| error.to_string())?; + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("openbot-relay") + .enable_all() + .build() + .map_err(|error| format!("could not start the relay: {error}"))?; + let (stop, stopped) = tokio::sync::watch::channel(false); + let secret = crate::provider_oauth::random(); + let shared = Arc::new(Shared { + session, + host: address.to_string(), + origin: format!("http://{address}"), + upstream, + secret: secret.clone(), + client, + organization: organization.clone(), + on_ended: Box::new(on_ended), + session_ended: AtomicBool::new(false), + unreachable_said: Mutex::new(None), + stop: stop.clone(), + }); + runtime.spawn(serve(listener, shared, stopped)); + log::info!("[relay] listening on {address}"); + Ok(Self { + address, + secret, + organization, + stop, + runtime: Some(runtime), + }) + } + + /// The organisation named on every request from now on, or none. + pub fn set_organization(&self, organization: Option<&str>) { + *self.organization.lock().unwrap() = organization_header(organization); + } + + /// The address it listens on: always `127.0.0.1`, and a port. + pub fn address(&self) -> SocketAddr { + self.address + } + + /// `http://127.0.0.1:`: the origin of the app's pages in the window. + pub fn origin(&self) -> String { + format!("http://{}", self.address) + } + + /// Where the window goes first: the address that gives it this run's cookie and sends it on + /// to the app. It holds the secret, so it is never logged. + pub fn entry(&self) -> String { + format!("{}{ENTER_PATH}?key={}", self.origin(), self.secret) + } +} + +impl Drop for Relay { + fn drop(&mut self) { + let _ = self.stop.send(true); + if let Some(runtime) = self.runtime.take() { + // Not waited for: a stream that is open would hold the wait, and this may run on a + // thread that must not block. + runtime.shutdown_background(); + } + log::info!("[relay] stopped"); + } +} + +async fn serve( + listener: std::net::TcpListener, + shared: Arc, + mut stopped: tokio::sync::watch::Receiver, +) { + let Ok(listener) = tokio::net::TcpListener::from_std(listener) else { + return; + }; + loop { + let accepted = tokio::select! { + accepted = listener.accept() => accepted, + _ = stopped.wait_for(|stopped| *stopped) => return, + }; + let Ok((stream, _)) = accepted else { + continue; + }; + let shared = shared.clone(); + let mut stopped = stopped.clone(); + tokio::spawn(async move { + let service = hyper::service::service_fn(move |request| { + let shared = shared.clone(); + async move { Ok::<_, std::convert::Infallible>(answer(request, shared).await) } + }); + let connection = hyper::server::conn::http1::Builder::new() + .serve_connection(TokioIo::new(stream), service) + .with_upgrades(); + tokio::select! { + _ = connection => {} + _ = stopped.wait_for(|stopped| *stopped) => {} + } + }); + } +} + +fn plain(status: StatusCode, said: &'static str) -> Response { + Response::builder() + .status(status) + .header(header::CONTENT_TYPE, "text/plain; charset=utf-8") + .header(header::CACHE_CONTROL, "no-store") + .body( + Full::new(Bytes::from_static(said.as_bytes())) + .map_err(|never| match never {}) + .boxed(), + ) + .expect("a plain response") +} + +/// Equal, in time that does not depend on where they differ. +fn same_secret(given: &str, secret: &str) -> bool { + given.len() == secret.len() + && given + .bytes() + .zip(secret.bytes()) + .fold(0u8, |differences, (a, b)| differences | (a ^ b)) + == 0 +} + +/// Whether the request carries the run's cookie. +fn has_cookie(headers: &HeaderMap, secret: &str) -> bool { + headers + .get_all(header::COOKIE) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|cookies| cookies.split(';')) + .filter_map(|cookie| cookie.trim().split_once('=')) + .any(|(name, value)| name == COOKIE && same_secret(value, secret)) +} + +/// Headers that belong to one connection, not to the request (RFC 9110 §7.6.1). +fn hop_by_hop(name: &HeaderName) -> bool { + matches!( + name.as_str(), + "connection" + | "keep-alive" + | "proxy-authenticate" + | "proxy-authorization" + | "proxy-connection" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + ) +} + +/// Headers of the page's request that are not passed on: where it came from, what the browser +/// keeps for this origin, and anything that claims to speak for another proxy. +fn dropped_on_the_way_out(name: &HeaderName) -> bool { + let name = name.as_str(); + matches!( + name, + "host" | "origin" | "cookie" | "referer" | "forwarded" | "authorization" + ) || name.starts_with("x-forwarded-") + || name.starts_with("sec-fetch-") + // The shell names the organisation, not the page. + || name.eq_ignore_ascii_case(ORGANIZATION_HEADER) +} + +async fn answer(mut request: Request, shared: Arc) -> Response { + // Only `GET /path`: an absolute address or a CONNECT names somewhere else to go. + let target = request.uri(); + if request.method() == Method::CONNECT + || target.scheme().is_some() + || target.authority().is_some() + || !target.path().starts_with('/') + { + return plain( + StatusCode::FORBIDDEN, + "This relay only serves its own pages.", + ); + } + let mut hosts = request.headers().get_all(header::HOST).iter(); + let host_is_ours = hosts + .next() + .is_some_and(|host| host == shared.host.as_str()) + && hosts.next().is_none(); + if !host_is_ours { + return plain( + StatusCode::MISDIRECTED_REQUEST, + "This relay answers only at its own address.", + ); + } + + // The window arriving with the run's secret. The key is the guard here, so this is answered + // before the checks below: the window's first navigation carries no cookie yet. + if request.uri().path() == ENTER_PATH { + let key = request + .uri() + .query() + .and_then(|query| query.split('&').find_map(|pair| pair.strip_prefix("key="))); + if request.method() != Method::GET + || !key.is_some_and(|key| same_secret(key, &shared.secret)) + { + return plain( + StatusCode::FORBIDDEN, + "This relay is for the OpenBot window.", + ); + } + return Response::builder() + .status(StatusCode::SEE_OTHER) + .header(header::LOCATION, "/") + .header( + header::SET_COOKIE, + format!( + "{COOKIE}={}; HttpOnly; SameSite=Strict; Path=/", + shared.secret + ), + ) + .header(header::CACHE_CONTROL, "no-store") + .body(Empty::new().map_err(|never| match never {}).boxed()) + .expect("the entry response"); + } + + let foreign_origin = request + .headers() + .get_all(header::ORIGIN) + .iter() + .any(|origin| origin != shared.origin.as_str()); + let from_another_site = request + .headers() + .get_all("sec-fetch-site") + .iter() + .any(|site| site == "cross-site" || site == "same-site"); + if foreign_origin || from_another_site || !has_cookie(request.headers(), &shared.secret) { + return plain( + StatusCode::FORBIDDEN, + "This relay is for the OpenBot window.", + ); + } + if request.uri().path().starts_with(OWN_PREFIX) { + return plain(StatusCode::NOT_FOUND, "Not found."); + } + if shared.session_ended.load(Ordering::SeqCst) { + return plain(StatusCode::UNAUTHORIZED, "The sign-in has ended."); + } + + // The typed address with this request's path and query, and nothing else of the request. + let path = request + .uri() + .path_and_query() + .map_or("/", |path| path.as_str()); + let address = format!("{}{path}", shared.session.address()); + let destination = reqwest::Url::parse(&address).ok().filter(|url| { + url.scheme() == shared.upstream.scheme() + && url.host_str() == shared.upstream.host_str() + && url.port_or_known_default() == shared.upstream.port_or_known_default() + }); + let Some(destination) = destination else { + return plain( + StatusCode::FORBIDDEN, + "This relay only serves its own pages.", + ); + }; + + let upgrading = request.headers().contains_key(header::UPGRADE); + let mut headers = HeaderMap::new(); + for (name, value) in request.headers() { + if dropped_on_the_way_out(name) || hop_by_hop(name) { + continue; + } + headers.append(name.clone(), value.clone()); + } + let organization = shared.organization.lock().unwrap().clone(); + if let (Some(organization), Ok(name)) = ( + organization, + HeaderName::from_bytes(ORGANIZATION_HEADER.as_bytes()), + ) { + headers.insert(name, organization); + } + if upgrading { + if let Some(protocol) = request.headers().get(header::UPGRADE) { + headers.insert(header::UPGRADE, protocol.clone()); + headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade")); + } + } + + let access = match token(&shared, None).await { + Ok(access) => access, + Err((status, said)) => return plain(status, said), + }; + let method = request.method().clone(); + let on_upgrade = upgrading.then(|| hyper::upgrade::on(&mut request)); + let no_body = hyper::body::Body::is_end_stream(request.body()); + let incoming = request.into_body(); + let body = (!no_body) + .then(|| reqwest::Body::wrap_stream(http_body_util::BodyDataStream::new(incoming))); + + let send = |access: &str, body: Option| { + let mut outgoing = shared + .client + .request(method.clone(), destination.clone()) + .headers(headers.clone()) + .bearer_auth(access); + if let Some(body) = body { + outgoing = outgoing.body(body); + } + outgoing.send() + }; + let mut answered = match send(&access, body).await { + Ok(answered) => answered, + Err(error) => return unreachable(&shared, error), + }; + if answered.status() == StatusCode::UNAUTHORIZED { + // The token was refused. A new one, and the request once more when it had no body to + // send again; a request with a body is answered as it was, and the next one is signed in. + match token(&shared, Some(access.clone())).await { + Ok(newer) if no_body && newer != access => { + answered = match send(&newer, None).await { + Ok(answered) => answered, + Err(error) => return unreachable(&shared, error), + }; + } + Ok(_) => {} + Err((status, said)) => return plain(status, said), + } + } + + let status = answered.status(); + let mut response = Response::builder().status(status); + for (name, value) in answered.headers() { + if name == header::SET_COOKIE { + continue; + } + if hop_by_hop(name) && status != StatusCode::SWITCHING_PROTOCOLS { + continue; + } + if name == header::LOCATION { + response = response.header(name, on_the_relay(&shared, value)); + continue; + } + response = response.header(name, value); + } + + if status == StatusCode::SWITCHING_PROTOCOLS { + let Some(on_upgrade) = on_upgrade else { + return plain( + StatusCode::BAD_GATEWAY, + "OpenBot answered with a socket nobody asked for.", + ); + }; + // The two connections joined, each way, until either closes. + tokio::spawn(async move { + let (Ok(page), Ok(mut openbot)) = (on_upgrade.await, answered.upgrade().await) else { + return; + }; + let mut page = TokioIo::new(page); + let _ = tokio::io::copy_bidirectional(&mut page, &mut openbot).await; + }); + return response + .body(Empty::new().map_err(|never| match never {}).boxed()) + .unwrap_or_else(|_| { + plain( + StatusCode::BAD_GATEWAY, + "OpenBot's answer could not be passed on.", + ) + }); + } + + // As it arrives: each piece is a frame of its own, so nothing waits for the end. + let pieces = answered + .bytes_stream() + .map(|piece| piece.map(Frame::data).map_err(Into::into)); + response + .body(BodyExt::boxed(StreamBody::new(pieces))) + .unwrap_or_else(|_| { + plain( + StatusCode::BAD_GATEWAY, + "OpenBot's answer could not be passed on.", + ) + }) +} + +/// An access token, off the async threads: a refresh is a blocking request. On a sign-in that has +/// ended, the relay says so and stops; the page is answered 401. +async fn token( + shared: &Arc, + refused: Option, +) -> Result { + let session = shared.session.clone(); + let got = tokio::task::spawn_blocking(move || match refused { + Some(used) => session.after_refused(&used), + None => session.access(), + }) + .await; + match got { + Ok(Ok(access)) => Ok(access), + Ok(Err(problem)) if kind_of(&problem) == Some(Kind::SessionEnded) => { + end_session(shared); + Err((StatusCode::UNAUTHORIZED, "The sign-in has ended.")) + } + Ok(Err(_)) | Err(_) => { + say_unreachable(shared); + Err((StatusCode::BAD_GATEWAY, "OpenBot could not be reached.")) + } + } +} + +fn end_session(shared: &Arc) { + if shared.session_ended.swap(true, Ordering::SeqCst) { + return; + } + log::info!("[relay] the sign-in has ended; no longer answering"); + let _ = shared.stop.send(true); + // On a thread of its own: the shell stops this relay from it, which this runtime's own + // threads must not wait for. + let shared = shared.clone(); + std::thread::spawn(move || (shared.on_ended)(Ended::SessionEnded)); +} + +fn say_unreachable(shared: &Arc) { + let mut said = shared.unreachable_said.lock().unwrap(); + if said.is_some_and(|at| at.elapsed() < UNREACHABLE_SAID_EVERY) { + return; + } + *said = Some(Instant::now()); + drop(said); + let shared = shared.clone(); + std::thread::spawn(move || (shared.on_ended)(Ended::Unreachable)); +} + +fn unreachable(shared: &Arc, error: reqwest::Error) -> Response { + log::warn!( + "[relay] OpenBot did not answer: {}", + super::transport(error) + ); + say_unreachable(shared); + plain(StatusCode::BAD_GATEWAY, "OpenBot could not be reached.") +} + +/// A redirect's `Location`, kept on the relay when it points at the typed address, so the window +/// stays on pages the relay serves. One that points anywhere else is handed back as it is: the +/// window opens it in the person's browser. +fn on_the_relay(shared: &Shared, location: &HeaderValue) -> HeaderValue { + let rewritten = location + .to_str() + .ok() + .and_then(|location| reqwest::Url::parse(location).ok()) + .filter(|url| { + url.scheme() == shared.upstream.scheme() + && url.host_str() == shared.upstream.host_str() + && url.port_or_known_default() == shared.upstream.port_or_known_default() + }) + .map(|url| { + let mut kept = format!("{}{}", shared.origin, url.path()); + if let Some(query) = url.query() { + kept.push('?'); + kept.push_str(query); + } + if let Some(fragment) = url.fragment() { + kept.push('#'); + kept.push_str(fragment); + } + kept + }) + .and_then(|kept| HeaderValue::from_str(&kept).ok()); + rewritten.unwrap_or_else(|| location.clone()) +} + +#[cfg(test)] +mod tests { + use super::super::credentials::{in_memory, Store}; + use super::super::fake_openbot::{raw_request, FakeOpenBot, Shape}; + use super::*; + use std::io::Read; + + const ECHO: &str = "/api/v2/echo"; + + /// An OpenBot, a sign-in to it, and a relay in front of it. + struct Rig { + openbot: FakeOpenBot, + store: Store, + session: Arc, + relay: Relay, + ended: Arc>>, + } + + fn rig() -> Rig { + let openbot = FakeOpenBot::start(Shape::Current); + let store = in_memory(); + let session = Arc::new(openbot.sign_in(store.clone())); + let ended = Arc::new(Mutex::new(Vec::new())); + let heard = ended.clone(); + let relay = Relay::start(session.clone(), None, move |why| { + heard.lock().unwrap().push(why) + }) + .unwrap(); + Rig { + openbot, + store, + session, + relay, + ended, + } + } + + fn http() -> reqwest::blocking::Client { + reqwest::blocking::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(15)) + .build() + .unwrap() + } + + /// The window: it went to the entry address first, and carries the cookie from then on. + struct Window { + origin: String, + host: String, + cookie: String, + } + + impl Rig { + fn window(&self) -> Window { + enter(&self.relay) + } + + fn echoes(&self) -> usize { + self.openbot.seen_at(ECHO).len() + } + } + + fn enter(relay: &Relay) -> Window { + let entered = http().get(relay.entry()).send().unwrap(); + assert_eq!(entered.status(), 303); + assert_eq!(entered.headers()["location"], "/"); + let cookie = entered.headers()["set-cookie"].to_str().unwrap().to_owned(); + assert!( + cookie.ends_with("; HttpOnly; SameSite=Strict; Path=/"), + "{cookie}" + ); + Window { + origin: relay.origin(), + host: relay.address().to_string(), + cookie: cookie.split(';').next().unwrap().to_owned(), + } + } + + impl Window { + fn request( + &self, + method: reqwest::Method, + path: &str, + ) -> reqwest::blocking::RequestBuilder { + http() + .request(method, format!("{}{path}", self.origin)) + .header("cookie", &self.cookie) + } + + fn get(&self, path: &str) -> reqwest::blocking::RequestBuilder { + self.request(reqwest::Method::GET, path) + } + + /// What `ECHO` says OpenBot received. + fn echo(&self, request: reqwest::blocking::RequestBuilder) -> serde_json::Value { + let answered = request.send().unwrap(); + assert_eq!(answered.status(), 200); + answered.json().unwrap() + } + + /// A request written by hand, for the ones no client will send. + fn raw(&self, first_line: &str, host: &str) -> String { + raw_request( + &self.host, + &format!( + "{first_line}\r\nHost: {host}\r\nCookie: {}\r\nConnection: close\r\n\r\n", + self.cookie + ), + ) + } + } + + fn status(answer: &str) -> &str { + answer.lines().next().unwrap_or("") + } + + #[test] + fn it_listens_on_127_0_0_1_only_at_a_port_of_its_own() { + let rig = rig(); + let second = Relay::start(rig.session.clone(), None, |_| {}).unwrap(); + for relay in [&rig.relay, &second] { + assert_eq!( + relay.address().ip(), + std::net::IpAddr::V4(Ipv4Addr::LOCALHOST) + ); + assert_ne!(relay.address().port(), 0); + assert_eq!( + relay.origin(), + format!("http://127.0.0.1:{}", relay.address().port()) + ); + // Not on the other loopback, and so not on every address either. + assert!(std::net::TcpStream::connect_timeout( + &SocketAddr::from((std::net::Ipv6Addr::LOCALHOST, relay.address().port())), + Duration::from_secs(2) + ) + .is_err()); + } + assert_ne!(rig.relay.address().port(), second.address().port()); + assert_ne!(rig.relay.entry(), second.entry()); + } + + /// A name that resolves to this computer is not this relay: only its own `127.0.0.1:`. + #[test] + fn a_request_for_another_host_is_refused_and_never_reaches_openbot() { + let rig = rig(); + let window = rig.window(); + let port = rig.relay.address().port(); + for host in [ + format!("localhost:{port}"), + "openbot.example.com".to_owned(), + format!("[::1]:{port}"), + "127.0.0.1".to_owned(), + format!("127.0.0.1:{}", port.wrapping_add(1)), + ] { + let answer = window.raw(&format!("GET {ECHO} HTTP/1.1"), &host); + assert_eq!( + status(&answer), + "HTTP/1.1 421 Misdirected Request", + "{host}" + ); + } + assert_eq!(rig.echoes(), 0); + // Its own name is answered. + let answer = window.raw(&format!("GET {ECHO} HTTP/1.1"), &window.host); + assert_eq!(status(&answer), "HTTP/1.1 200 OK"); + assert_eq!(rig.echoes(), 1); + } + + /// The relay goes to the typed address and nowhere else: a request that names another place + /// to go is refused, and nothing leaves for anywhere. + #[test] + fn an_absolute_address_or_a_connect_goes_nowhere() { + let rig = rig(); + let window = rig.window(); + for first_line in [ + format!("GET http://elsewhere.example{ECHO} HTTP/1.1"), + format!("GET {}{ECHO} HTTP/1.1", rig.openbot.address()), + "CONNECT elsewhere.example:443 HTTP/1.1".to_owned(), + ] { + let answer = window.raw(&first_line, &window.host); + assert_eq!(status(&answer), "HTTP/1.1 403 Forbidden", "{first_line}"); + } + assert_eq!( + rig.openbot + .requests() + .iter() + .filter(|seen| seen.contains("echo")) + .count(), + 0 + ); + // A path that only looks like another host is a path at the typed address. + let before = rig.openbot.seen().len(); + let answer = window.raw("GET //elsewhere.example/page HTTP/1.1", &window.host); + assert_eq!(status(&answer), "HTTP/1.1 404 Not Found"); + let seen = rig.openbot.seen(); + assert_eq!(seen.len(), before + 1); + assert_eq!(seen.last().unwrap().path, "//elsewhere.example/page"); + } + + /// OpenBot sees the app's token and none of what the browser adds: where the page is, its + /// cookies, or a header claiming to speak for another proxy. The rest goes through. + #[test] + fn openbot_sees_the_bearer_token_and_no_origin_cookie_or_forwarding_header() { + let rig = rig(); + let window = rig.window(); + let access = rig.session.access().unwrap(); + let sent = window.echo( + window + .request(reqwest::Method::POST, &format!("{ECHO}?thread=t-1&x=a%20b")) + .header("origin", &window.origin) + .header("cookie", format!("{}; theme=dark", window.cookie)) + .header("referer", format!("{}/channel/c-1", window.origin)) + .header("forwarded", "for=203.0.113.9") + .header("x-forwarded-for", "203.0.113.9") + .header("x-forwarded-host", "elsewhere.example") + .header("x-forwarded-proto", "https") + .header("authorization", "Bearer made-by-the-page") + .header("x-request-id", "kept-as-sent") + .header("content-type", "application/json") + .body(r#"{"message":"hello"}"#), + ); + let headers = sent["headers"].as_object().unwrap(); + assert_eq!(headers["authorization"], format!("Bearer {access}")); + for gone in [ + "origin", + "cookie", + "referer", + "forwarded", + "x-forwarded-for", + "x-forwarded-host", + "x-forwarded-proto", + ] { + assert!(!headers.contains_key(gone), "{gone} reached OpenBot"); + } + assert_eq!(headers["x-request-id"], "kept-as-sent"); + assert_eq!(headers["content-type"], "application/json"); + assert_eq!( + headers["host"], + rig.openbot.address().trim_start_matches("http://") + ); + assert_eq!(sent["method"], "POST"); + assert_eq!(sent["query"], "thread=t-1&x=a%20b"); + assert_eq!(sent["body"], r#"{"message":"hello"}"#); + // The token never comes back to the page. + assert!(!sent.to_string().contains(&window.cookie)); + } + + #[test] + fn a_cookie_openbot_sets_does_not_come_back() { + let rig = rig(); + let answered = rig.window().get("/api/v2/cookie").send().unwrap(); + assert_eq!(answered.status(), 200); + assert!(answered.headers().get("set-cookie").is_none()); + assert_eq!(answered.text().unwrap(), "ok"); + assert_eq!(rig.openbot.seen_at("/api/v2/cookie").len(), 1); + } + + /// A chat answer arrives as it is written. OpenBot sends three events 400 ms apart; the page + /// has the first well before the last is sent. + #[test] + fn a_stream_arrives_in_pieces_as_it_is_sent() { + let rig = rig(); + let started = Instant::now(); + let mut answered = rig.window().get("/api/v2/stream").send().unwrap(); + assert_eq!(answered.headers()["content-type"], "text/event-stream"); + let mut arrivals = Vec::new(); + let mut buffer = [0u8; 256]; + loop { + let read = answered.read(&mut buffer).unwrap(); + if read == 0 { + break; + } + arrivals.push(( + started.elapsed(), + String::from_utf8_lossy(&buffer[..read]).into_owned(), + )); + } + let all: String = arrivals.iter().map(|(_, text)| text.as_str()).collect(); + assert_eq!(all, "data: 0\n\ndata: 1\n\ndata: 2\n\n"); + let (first_at, first) = &arrivals[0]; + let (last_at, _) = arrivals.last().unwrap(); + assert_eq!(first, "data: 0\n\n", "{arrivals:?}"); + assert!(*first_at < Duration::from_millis(350), "{arrivals:?}"); + assert!( + *last_at - *first_at >= Duration::from_millis(600), + "{arrivals:?}" + ); + } + + fn socket_request( + window: &Window, + path: &str, + ) -> tokio_tungstenite::tungstenite::handshake::client::Request { + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + let mut request = format!("ws://{}{path}", window.host) + .into_client_request() + .unwrap(); + request + .headers_mut() + .insert("origin", window.origin.parse().unwrap()); + request + } + + /// A WebSocket through the relay: a real client on one side and a real server on the other, + /// messages both ways, and the upgrade itself carrying the token. + #[test] + fn a_websocket_upgrade_echoes_both_ways_and_carries_the_bearer_token() { + use futures_util::SinkExt; + let rig = rig(); + let window = rig.window(); + rig.relay.set_organization(Some("org_socket")); + let access = rig.session.access().unwrap(); + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let connect = |request| async { + let stream = tokio::net::TcpStream::connect(&window.host).await.unwrap(); + tokio_tungstenite::client_async(request, stream).await + }; + // Without the window's cookie there is no socket, and OpenBot is not asked. + let refused = connect(socket_request(&window, "/api/v2/socket")).await; + assert!(refused.is_err()); + assert_eq!(rig.openbot.seen_at("/api/v2/socket").len(), 0); + + let mut request = socket_request(&window, "/api/v2/socket"); + request + .headers_mut() + .insert("cookie", window.cookie.parse().unwrap()); + let (mut socket, answered) = connect(request).await.unwrap(); + assert_eq!(answered.status(), 101); + assert!(answered.headers().get("set-cookie").is_none()); + for said in ["hello", "and again"] { + socket.send(said.into()).await.unwrap(); + let heard = socket.next().await.unwrap().unwrap(); + assert_eq!(heard.to_text().unwrap(), format!("echo: {said}")); + } + socket.close(None).await.unwrap(); + }); + let upgrade = rig.openbot.seen_at("/api/v2/socket").remove(0); + assert_eq!( + upgrade.header("authorization"), + Some(format!("Bearer {access}").as_str()) + ); + assert_eq!(upgrade.header("upgrade"), Some("websocket")); + assert_eq!(upgrade.header(ORGANIZATION_HEADER), Some("org_socket")); + assert_eq!(upgrade.header("origin"), None); + assert_eq!(upgrade.header("cookie"), None); + } + + /// The access token ran out. OpenBot answers 401, the relay refreshes once, and the same + /// request is sent again with the new token: the page sees only the answer. + #[test] + fn a_401_after_expiry_leads_to_one_refresh_and_the_request_again() { + let rig = rig(); + let window = rig.window(); + let first = rig.session.access().unwrap(); + rig.openbot.expire_access_tokens(); + let refreshes = || { + rig.openbot + .token_requests() + .iter() + .filter(|request| request["grant_type"] == "refresh_token") + .count() + }; + assert_eq!(refreshes(), 0); + + let sent = window.echo(window.get(ECHO)); + + assert_eq!(refreshes(), 1); + let second = rig.session.access().unwrap(); + assert_ne!(second, first); + assert_eq!(sent["headers"]["authorization"], format!("Bearer {second}")); + let tries = rig.openbot.seen_at(ECHO); + assert_eq!(tries.len(), 2, "refused once, then answered"); + assert_eq!( + tries[0].header("authorization"), + Some(format!("Bearer {first}").as_str()) + ); + // And the next request needs no refresh. + window.echo(window.get(ECHO)); + assert_eq!(refreshes(), 1); + assert!(rig.ended.lock().unwrap().is_empty()); + } + + /// Signed out elsewhere, or removed. The refresh is refused: the shell is told once that the + /// session ended, the saved sign-in is forgotten, and the relay stops answering. + #[test] + fn a_refused_refresh_says_session_ended_and_the_relay_stops_answering() { + let rig = rig(); + let window = rig.window(); + rig.openbot.end_sessions(); + + let answered = window.get(ECHO).send().unwrap(); + assert_eq!(answered.status(), 401); + + let deadline = Instant::now() + Duration::from_secs(10); + while rig.ended.lock().unwrap().is_empty() { + assert!(Instant::now() < deadline, "the shell was never told"); + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(*rig.ended.lock().unwrap(), [Ended::SessionEnded]); + assert_eq!(rig.store.get(&rig.openbot.address()).unwrap(), None); + // No longer listening: a new connection is refused, or closed with no answer. + let seen = rig.openbot.seen().len(); + loop { + match window.get(ECHO).send() { + Err(_) => break, + Ok(answered) => { + assert_eq!(answered.status(), 401); + assert!(Instant::now() < deadline, "the relay kept answering"); + std::thread::sleep(Duration::from_millis(20)); + } + } + } + assert_eq!( + rig.openbot.seen().len(), + seen, + "nothing more reached OpenBot" + ); + assert_eq!( + *rig.ended.lock().unwrap(), + [Ended::SessionEnded], + "said once" + ); + } + + /// A page in the person's own browser, or another program on this computer, can send a + /// request to `127.0.0.1:` with the right `Host`. It does not have the run's secret, + /// so it is refused and OpenBot never hears of it. + #[test] + fn a_request_without_the_windows_cookie_is_refused_and_never_reaches_openbot() { + let rig = rig(); + let window = rig.window(); + let origin = rig.relay.origin(); + let refused = |request: reqwest::blocking::RequestBuilder| { + let answered = request.send().unwrap(); + assert_eq!(answered.status(), 403); + assert!(answered.headers().get("set-cookie").is_none()); + }; + // No cookie, a wrong one, and one that only starts like the right one. + refused(http().get(format!("{origin}{ECHO}"))); + refused( + http() + .get(format!("{origin}{ECHO}")) + .header("cookie", format!("{COOKIE}=guessed")), + ); + refused( + http() + .get(format!("{origin}{ECHO}")) + .header("cookie", format!("{}x", window.cookie)), + ); + refused(http().post(format!("{origin}{ECHO}")).body("{}")); + // The entry address with no key, or the wrong one, gives nothing. + refused(http().get(format!("{origin}{ENTER_PATH}"))); + refused(http().get(format!("{origin}{ENTER_PATH}?key=guessed"))); + refused(http().post(rig.relay.entry()).header("content-length", "0")); + assert_eq!(rig.openbot.seen_at(ECHO).len(), 0); + assert_eq!(rig.openbot.seen_at(ENTER_PATH).len(), 0); + + // With the cookie the window was given, the same request goes through. + window.echo(window.get(ECHO)); + assert_eq!(rig.echoes(), 1); + // Nothing of the relay's own is ever forwarded, the entry address included. + let own = window.get("/.openbot-relay/anything").send().unwrap(); + assert_eq!(own.status(), 404); + assert!(rig + .openbot + .requests() + .iter() + .all(|seen| !seen.contains(".openbot-relay"))); + } + + /// Even with the cookie, a request another site's page made is refused: its `Origin` is not + /// the relay's, or the browser says it came from another site. + #[test] + fn a_request_from_another_site_is_refused_even_with_the_cookie() { + let rig = rig(); + let window = rig.window(); + for (name, value) in [ + ("origin", "https://elsewhere.example"), + ("origin", "http://127.0.0.1:1"), + ("origin", "null"), + ("sec-fetch-site", "cross-site"), + ("sec-fetch-site", "same-site"), + ] { + let answered = window.get(ECHO).header(name, value).send().unwrap(); + assert_eq!(answered.status(), 403, "{name}: {value}"); + } + assert_eq!(rig.echoes(), 0); + // The page's own requests say same-origin, or nothing at all. + window.echo( + window + .get(ECHO) + .header("origin", &window.origin) + .header("sec-fetch-site", "same-origin"), + ); + assert_eq!(rig.echoes(), 1); + } + + /// A redirect is the page's to follow, not the relay's. One to the typed address is kept on + /// the relay; one to anywhere else is handed back untouched. + #[test] + fn a_redirect_is_handed_back_and_kept_on_the_relay_when_it_is_openbots() { + let rig = rig(); + let window = rig.window(); + let home = window.get("/api/v2/home").send().unwrap(); + assert_eq!(home.status(), 302); + assert_eq!( + home.headers()["location"], + format!("{}/landing?from=home#top", window.origin).as_str() + ); + let away = window.get("/api/v2/away").send().unwrap(); + assert_eq!(away.status(), 302); + assert_eq!(away.headers()["location"], "https://elsewhere.example/page"); + assert_eq!(rig.openbot.seen_at("/landing").len(), 0, "not followed"); + } + + /// The shell names the organisation on every request, and the page cannot. + #[test] + fn the_chosen_organisation_is_named_on_every_request_and_only_by_the_shell() { + let rig = rig(); + let window = rig.window(); + let named = |sent: &serde_json::Value| { + sent["headers"] + .get(ORGANIZATION_HEADER.to_ascii_lowercase()) + .cloned() + }; + // None chosen: none sent, whatever the page says. + assert_eq!(named(&window.echo(window.get(ECHO))), None); + assert_eq!( + named(&window.echo(window.get(ECHO).header(ORGANIZATION_HEADER, "org_forged"))), + None + ); + + rig.relay.set_organization(Some("org_A1-b")); + assert_eq!( + named(&window.echo(window.get(ECHO))), + Some("org_A1-b".into()) + ); + assert_eq!( + named(&window.echo(window.get(ECHO).header(ORGANIZATION_HEADER, "org_forged"))), + Some("org_A1-b".into()) + ); + // Something that is not an id is not sent. + rig.relay.set_organization(Some("not an id")); + assert_eq!(named(&window.echo(window.get(ECHO))), None); + rig.relay.set_organization(None); + assert_eq!(named(&window.echo(window.get(ECHO))), None); + + // A relay started again reads the choice back from connection.json. + let config = crate::test_support::temp_root("relay-organisation"); + let chosen = super::super::choice::Choice { + mode: super::super::choice::Mode::Connected, + address: Some(rig.openbot.address()), + organization_id: Some("org_kept".into()), + }; + super::super::choice::write(&config, &chosen).unwrap(); + let read = super::super::choice::read(&config); + let again = + Relay::start(rig.session.clone(), read.organization_id.as_deref(), |_| {}).unwrap(); + let window = enter(&again); + assert_eq!( + named(&window.echo(window.get(ECHO))), + Some("org_kept".into()) + ); + let _ = std::fs::remove_dir_all(config); + } + + /// The entry address holds the run's secret, and the log's redaction covers it. + #[test] + fn the_entry_address_and_the_cookie_are_redacted_in_a_log_line() { + let rig = rig(); + let window = rig.window(); + let secret = window.cookie.split_once('=').unwrap().1.to_owned(); + for line in [ + format!("[window] navigating to {}", rig.relay.entry()), + format!("[relay] refused {}", window.cookie), + ] { + let written = crate::logging::redact(&line); + assert!(!written.contains(&secret), "{written}"); + assert!(written.contains(crate::logging::REDACTED), "{written}"); + } + } +} diff --git a/desktop/src-tauri/src/connected/sign_in.rs b/desktop/src-tauri/src/connected/sign_in.rs new file mode 100644 index 0000000000..2457586e2f --- /dev/null +++ b/desktop/src-tauri/src/connected/sign_in.rs @@ -0,0 +1,1019 @@ +/*! +Signing in to an OpenBot that runs elsewhere, and staying signed in. + +OAuth 2.1 authorization code with PKCE (S256), as a public client with a loopback redirect +(RFC 8252): a listener on `127.0.0.1` at a port the system picks, the system browser sent to the +OpenBot's authorization endpoint, and the code it sends back to `/callback` exchanged for tokens. +The PKCE verifier, the `state` and the callback's first line are read with what +`provider_oauth` already has; nothing new is done with a hash or a random number here. + +A `Session` is what comes out: the access token in memory for its hour, and the refresh token in +the system's credential store (`credentials`). Refresh tokens rotate on every use and an old one +fails if it is used again, so one refresh runs at a time and the new token is stored before the old +one is let go. + +Nothing here logs or returns a token, a code or a verifier. A failure's detail is a status, an +OAuth error code or a transport error. +*/ + +use super::address::Metadata; +use super::credentials::Store; +use super::{host_of, http, transport, Kind, CLIENT_ID}; +use crate::problem::Problem; +use crate::provider_oauth::{pkce_challenge, random, read_callback_request}; +use std::io::Write; +use std::net::{Ipv4Addr, TcpListener, TcpStream}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +/// The redirect's path. The OpenBot accepts exactly `http://127.0.0.1:/callback`. +pub const CALLBACK_PATH: &str = "/callback"; + +/// How long the browser has to come back. +pub const WAIT: Duration = Duration::from_secs(600); + +/// An access token this close to its end is replaced before it is used. +const REFRESH_BEFORE_END: Duration = Duration::from_secs(60); + +/// An access token the OpenBot refused is replaced at most this often. Without it, an address +/// that answers 401 whatever the token would use a refresh token on every request. +const REFUSED_REFRESH_EVERY: Duration = Duration::from_secs(30); + +/// What the browser tab shows once the sign-in has come back. +pub const SIGNED_IN_PAGE: &str = "You're signed in. You can close this tab and go back to OpenBot."; +/// What it shows when the sign-in was refused or was not this app's. +pub const NOT_SIGNED_IN_PAGE: &str = + "Sign-in didn't finish. You can close this tab and go back to OpenBot."; + +/// A sign-in that is waiting for the browser, so Cancel can end it. +#[derive(Default)] +pub struct Attempt { + cancelled: AtomicBool, +} + +impl Attempt { + pub fn cancel(&self) { + self.cancelled.store(true, Ordering::SeqCst); + } + + fn cancelled(&self) -> bool { + self.cancelled.load(Ordering::SeqCst) + } +} + +/// A sign-in to one OpenBot. +pub struct Session { + address: String, + host: String, + token_endpoint: String, + revocation_endpoint: Option, + store: Store, + live: Mutex, + /// Held for the whole of a refresh, so two requests that both find the token stale make one. + refreshing: Mutex<()>, +} + +struct Live { + access: String, + refresh: String, + expires: Instant, + /// When a refused access token last led to a refresh (`REFUSED_REFRESH_EVERY`). + refreshed_after_refusal: Option, + ended: bool, +} + +/// Never the tokens. +impl std::fmt::Debug for Session { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Session") + .field("address", &self.address) + .finish_non_exhaustive() + } +} + +struct Granted { + access: String, + refresh: Option, + expires_in: u64, +} + +enum Refused { + /// The request never got an answer. + Transport(String), + /// The OpenBot answered no: its status and its OAuth error code. + Answer { status: u16, error: String }, +} + +impl Refused { + fn detail(&self, what: &str) -> String { + match self { + Refused::Transport(error) => format!("{what}: {error}"), + Refused::Answer { status, error } => format!("{what} answered {status} {error}"), + } + } +} + +/** +Sign in to the OpenBot at `address` in the person's browser. + +`open` is handed the address to open, the system browser in the app. The wait ends when the browser +comes back with a code, when the person refuses, when `attempt` is cancelled, or after `wait`. +Returns once the code is exchanged, the OpenBot has answered `/api/me` with the new token, and the +refresh token is in `store`. +*/ +pub fn sign_in( + address: &str, + metadata: &Metadata, + store: Store, + attempt: &Attempt, + wait: Duration, + open: impl FnOnce(&str) -> Result<(), String>, +) -> Result { + let host = host_of(address); + let failed = |detail: String| Kind::SignInFailed.problem(&host, detail); + // 127.0.0.1 only: the redirect names it, and nothing off this computer can reach it. + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .and_then(|listener| listener.set_nonblocking(true).map(|()| listener)) + .map_err(|error| failed(format!("could not listen for the browser: {error}")))?; + let port = listener + .local_addr() + .map_err(|error| failed(error.to_string()))? + .port(); + let redirect = format!("http://127.0.0.1:{port}{CALLBACK_PATH}"); + let verifier = random(); + let state = random(); + let challenge = pkce_challenge(&verifier); + let scope = metadata.scopes.join(" "); + let mut authorize = reqwest::Url::parse(&metadata.authorization_endpoint) + .map_err(|error| failed(error.to_string()))?; + authorize.query_pairs_mut().extend_pairs([ + ("response_type", "code"), + ("client_id", CLIENT_ID), + ("redirect_uri", redirect.as_str()), + ("scope", scope.as_str()), + ("state", state.as_str()), + ("code_challenge", challenge.as_str()), + ("code_challenge_method", "S256"), + ]); + open(authorize.as_str()) + .map_err(|error| failed(format!("could not open the browser: {error}")))?; + + let code = wait_for_code(&listener, &state, attempt, wait, &host)?; + drop(listener); + + let granted = token_request( + &metadata.token_endpoint, + &[ + ("grant_type", "authorization_code"), + ("code", &code), + ("redirect_uri", &redirect), + ("client_id", CLIENT_ID), + ("code_verifier", &verifier), + ], + ) + .map_err(|refused| match refused { + Refused::Transport(_) => { + Kind::Unreachable.problem(&host, refused.detail("the token exchange")) + } + Refused::Answer { .. } => failed(refused.detail("the token exchange")), + })?; + let Some(refresh) = granted.refresh else { + return Err(Kind::TooOld.problem(&host, "the token exchange gave no refresh token")); + }; + let session = Session { + address: address.to_owned(), + host: host.clone(), + token_endpoint: metadata.token_endpoint.clone(), + revocation_endpoint: metadata.revocation_endpoint.clone(), + store, + live: Mutex::new(Live { + access: granted.access, + refresh, + expires: Instant::now() + Duration::from_secs(granted.expires_in), + refreshed_after_refusal: None, + ended: false, + }), + refreshing: Mutex::new(()), + }; + // The app's screens start with who is signed in. An OpenBot that refuses its own new token + // there is one from before it honoured an app's sign-in on the addresses the screens need. + if let Err(problem) = session.serves_the_app() { + session.revoke(); + return Err(problem); + } + let kept = { + let live = session.live.lock().unwrap(); + session.store.set(&session.address, &live.refresh) + }; + if let Err(problem) = kept { + session.revoke(); + return Err(problem); + } + log::info!("[connect] signed in to {host}"); + Ok(session) +} + +/// The saved sign-in for `address`, made current: the stored refresh token exchanged for a new +/// access token. `session-ended` when there is none or the OpenBot no longer takes it. +pub fn resume(address: &str, metadata: &Metadata, store: Store) -> Result { + let host = host_of(address); + let Some(refresh) = store.get(address)? else { + return Err(Kind::SessionEnded.problem(&host, "no sign-in is saved for this address")); + }; + let session = Session { + address: address.to_owned(), + host, + token_endpoint: metadata.token_endpoint.clone(), + revocation_endpoint: metadata.revocation_endpoint.clone(), + store, + live: Mutex::new(Live { + access: String::new(), + refresh, + // Already over, so the first use refreshes. + expires: Instant::now(), + refreshed_after_refusal: None, + ended: false, + }), + refreshing: Mutex::new(()), + }; + session.access()?; + Ok(session) +} + +impl Session { + /// The normalised address this is a sign-in to. + pub fn address(&self) -> &str { + &self.address + } + + /// The address's host, as the sentences name it. + pub fn host(&self) -> &str { + &self.host + } + + /// An access token good for at least the next minute, refreshed first when it is not. + pub fn access(&self) -> Result { + self.current(None) + } + + /// The OpenBot answered 401 to `used`: a newer access token, from a refresh unless another + /// request already made one or one was made for a refusal moments ago. + pub fn after_refused(&self, used: &str) -> Result { + self.current(Some(used)) + } + + fn ended(&self, detail: impl Into) -> Problem { + Kind::SessionEnded.problem(&self.host, detail) + } + + fn current(&self, refused: Option<&str>) -> Result { + // Without waiting for a refresh, when the token in hand is good. + if let Some(access) = self.usable(refused)? { + return Ok(access); + } + let _one_at_a_time = self.refreshing.lock().unwrap(); + // Whoever held it may have refreshed. + if let Some(access) = self.usable(refused)? { + return Ok(access); + } + let old = self.live.lock().unwrap().refresh.clone(); + let granted = token_request( + &self.token_endpoint, + &[ + ("grant_type", "refresh_token"), + ("refresh_token", &old), + ("client_id", CLIENT_ID), + ], + ); + let granted = match granted { + Ok(granted) => granted, + Err(Refused::Transport(error)) => { + return Err(Kind::Unreachable.problem(&self.host, format!("the refresh: {error}"))) + } + // The OpenBot could not answer: the sign-in may still be good. + Err(Refused::Answer { status, error }) if status >= 500 => { + return Err(Kind::Unreachable + .problem(&self.host, format!("the refresh answered {status} {error}"))) + } + Err(refused) => { + // Signed out elsewhere, removed, or expired: this sign-in is over. + self.live.lock().unwrap().ended = true; + if let Err(problem) = self.store.forget(&self.address) { + log::warn!( + "[connect] could not forget the ended sign-in: {}", + problem.detail.unwrap_or(problem.said) + ); + } + log::info!("[connect] the sign-in to {} has ended", self.host); + return Err(self.ended(refused.detail("the refresh"))); + } + }; + // The new refresh token is kept before the old one is let go: the old one is already + // dead at the OpenBot, so losing the new one here would lose the sign-in. + let refresh = granted.refresh.unwrap_or(old); + if let Err(problem) = self.store.set(&self.address, &refresh) { + // Still signed in for as long as the app runs; the next launch asks again. + log::warn!( + "[connect] could not keep the refreshed sign-in: {}", + problem.detail.unwrap_or(problem.said) + ); + } + let mut live = self.live.lock().unwrap(); + live.access = granted.access.clone(); + live.refresh = refresh; + live.expires = Instant::now() + Duration::from_secs(granted.expires_in); + if refused.is_some() { + live.refreshed_after_refusal = Some(Instant::now()); + } + Ok(granted.access) + } + + /// The access token in hand, when it can be used as it is. + fn usable(&self, refused: Option<&str>) -> Result, Problem> { + let live = self.live.lock().unwrap(); + if live.ended { + return Err(self.ended("the sign-in has ended")); + } + let fresh = live.expires > Instant::now() + REFRESH_BEFORE_END; + Ok(match refused { + None => fresh.then(|| live.access.clone()), + // Another request has replaced the refused one since. + Some(used) if live.access != used => Some(live.access.clone()), + Some(_) => live + .refreshed_after_refusal + .is_some_and(|at| at.elapsed() < REFUSED_REFRESH_EVERY) + .then(|| live.access.clone()), + }) + } + + /// Whether the OpenBot serves the app's screens to this sign-in: `GET /api/me` with the token. + fn serves_the_app(&self) -> Result<(), Problem> { + let access = self.live.lock().unwrap().access.clone(); + let answered = http() + .map_err(|error| Kind::Unreachable.problem(&self.host, error))? + .get(format!("{}/api/me", self.address)) + .bearer_auth(access) + .header(reqwest::header::ACCEPT, "application/json") + .send() + .map_err(|error| Kind::Unreachable.problem(&self.host, transport(error)))?; + match answered.status().as_u16() { + 200..=299 => Ok(()), + 401 | 404 => Err(Kind::TooOld.problem( + &self.host, + format!( + "GET /api/me answered {} to a new sign-in", + answered.status() + ), + )), + status => { + Err(Kind::SignInFailed + .problem(&self.host, format!("GET /api/me answered {status}"))) + } + } + } + + /// Sign out: both tokens revoked at the OpenBot (RFC 7009), as far as it answers, then the + /// sign-in forgotten on this computer whatever it answered. + pub fn sign_out(&self) -> Result<(), Problem> { + let _one_at_a_time = self.refreshing.lock().unwrap(); + self.revoke(); + self.live.lock().unwrap().ended = true; + log::info!("[connect] signed out of {}", self.host); + self.store.forget(&self.address) + } + + /// Best effort: a token that could not be revoked ends by itself, the access token within the + /// hour. + fn revoke(&self) { + let Some(endpoint) = &self.revocation_endpoint else { + return; + }; + let (refresh, access) = { + let live = self.live.lock().unwrap(); + (live.refresh.clone(), live.access.clone()) + }; + for (token, hint) in [(refresh, "refresh_token"), (access, "access_token")] { + if token.is_empty() { + continue; + } + if let Err(error) = revoke_token(endpoint, &token, hint) { + log::warn!( + "[connect] could not revoke the {hint} at {}: {error}", + self.host + ); + } + } + } +} + +/// Revoke a saved sign-in with no session around it: the stored refresh token, when the OpenBot +/// can be asked, and then forgotten either way. +pub fn sign_out_saved( + address: &str, + metadata: Option<&Metadata>, + store: &Store, +) -> Result<(), Problem> { + if let (Some(endpoint), Ok(Some(refresh))) = ( + metadata.and_then(|metadata| metadata.revocation_endpoint.as_deref()), + store.get(address), + ) { + if let Err(error) = revoke_token(endpoint, &refresh, "refresh_token") { + log::warn!( + "[connect] could not revoke the saved sign-in at {}: {error}", + host_of(address) + ); + } + } + store.forget(address) +} + +fn revoke_token(endpoint: &str, token: &str, hint: &str) -> Result<(), String> { + let answered = http()? + .post(endpoint) + .form(&[ + ("token", token), + ("token_type_hint", hint), + ("client_id", CLIENT_ID), + ]) + .send() + .map_err(transport)?; + if answered.status().is_success() { + Ok(()) + } else { + Err(format!("it answered {}", answered.status())) + } +} + +/// One request to the token endpoint: form-encoded, with the client's id in the body. +fn token_request(endpoint: &str, form: &[(&str, &str)]) -> Result { + let answered = http() + .map_err(Refused::Transport)? + .post(endpoint) + .header(reqwest::header::ACCEPT, "application/json") + .form(form) + .send() + .map_err(|error| Refused::Transport(transport(error)))?; + let status = answered.status(); + let body: serde_json::Value = answered.json().unwrap_or(serde_json::Value::Null); + let text = |name: &str| { + body.get(name) + .and_then(serde_json::Value::as_str) + .filter(|value| !value.is_empty()) + .map(str::to_owned) + }; + if !status.is_success() { + return Err(Refused::Answer { + status: status.as_u16(), + // The error code only (RFC 6749 §5.2): a description may quote what was sent. + error: text("error").unwrap_or_else(|| "with no error code".into()), + }); + } + let Some(access) = text("access_token") else { + return Err(Refused::Answer { + status: status.as_u16(), + error: "with no access token".into(), + }); + }; + Ok(Granted { + access, + refresh: text("refresh_token"), + expires_in: body + .get("expires_in") + .and_then(serde_json::Value::as_u64) + .filter(|seconds| *seconds > 0) + .unwrap_or(3600), + }) +} + +/// Wait for the browser to come back to the listener with this sign-in's code. +fn wait_for_code( + listener: &TcpListener, + state: &str, + attempt: &Attempt, + wait: Duration, + host: &str, +) -> Result { + let deadline = Instant::now() + wait; + loop { + if attempt.cancelled() { + return Err(Kind::SignInCancelled.problem(host, "cancelled in the app")); + } + if Instant::now() >= deadline { + return Err( + Kind::SignInCancelled.problem(host, "the browser did not come back in time") + ); + } + match listener.accept() { + Ok((mut stream, _)) => match callback(&mut stream, state) { + Callback::Code(code) => return Ok(code), + Callback::Refused(error) if error == "access_denied" => { + return Err(Kind::SignInCancelled.problem(host, "consent was not given")) + } + Callback::Refused(error) => { + return Err(Kind::SignInFailed + .problem(host, format!("the sign-in came back with {error}"))) + } + // Not this sign-in's answer. Whoever sent it does not get to end the wait. + Callback::NotOurs => {} + }, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(50)); + } + Err(error) => { + return Err(Kind::SignInFailed + .problem(host, format!("could not hear from the browser: {error}"))) + } + } + } +} + +enum Callback { + Code(String), + /// The OpenBot sent the browser back with an OAuth error code. + Refused(String), + NotOurs, +} + +/// Read one request to the listener and answer the browser tab. +fn callback(stream: &mut TcpStream, state: &str) -> Callback { + let Ok(request) = read_callback_request(stream, Duration::from_secs(2)) else { + return Callback::NotOurs; + }; + let mut parts = request.lines().next().unwrap_or("").split_whitespace(); + let (method, target) = (parts.next().unwrap_or(""), parts.next().unwrap_or("")); + let parsed = reqwest::Url::parse(&format!("http://127.0.0.1{target}")).ok(); + let Some(parsed) = parsed.filter(|url| method == "GET" && url.path() == CALLBACK_PATH) else { + page(stream, "404 Not Found", NOT_SIGNED_IN_PAGE); + return Callback::NotOurs; + }; + let query: std::collections::HashMap<_, _> = parsed.query_pairs().into_owned().collect(); + if query.get("state").map(String::as_str) != Some(state) { + page(stream, "400 Bad Request", NOT_SIGNED_IN_PAGE); + return Callback::NotOurs; + } + if let Some(error) = query.get("error") { + page(stream, "200 OK", NOT_SIGNED_IN_PAGE); + // Only the code's own characters: it goes into the log. + return Callback::Refused( + error + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '_') + .take(64) + .collect(), + ); + } + match query.get("code").filter(|code| !code.is_empty()) { + Some(code) => { + page(stream, "200 OK", SIGNED_IN_PAGE); + Callback::Code(code.clone()) + } + None => { + page(stream, "400 Bad Request", NOT_SIGNED_IN_PAGE); + Callback::NotOurs + } + } +} + +/// A small plain page for the browser tab. +fn page(stream: &mut TcpStream, status: &str, sentence: &str) { + let body = format!( + "OpenBot\ + \ +

{sentence}

" + ); + let _ = stream.write_all( + format!( + "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\n\ + Cache-Control: no-store\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .as_bytes(), + ); + let _ = stream.flush(); +} + +#[cfg(test)] +mod tests { + use super::super::credentials::in_memory; + use super::super::fake_openbot::{Browser, FakeOpenBot, Shape}; + use super::super::kind_of; + use super::*; + use std::sync::Arc; + + fn check(openbot: &FakeOpenBot) -> (String, Metadata) { + super::super::address::check(&openbot.address()).unwrap() + } + + /// The whole sign-in, as a person does it: the browser goes to the OpenBot, they approve, + /// the tab says they are signed in, and the app holds a sign-in that OpenBot honours. + #[test] + fn a_full_sign_in_ends_with_a_session_and_the_refresh_token_in_the_store() { + let openbot = FakeOpenBot::start(Shape::Current); + let (address, metadata) = check(&openbot); + let store = in_memory(); + let browser = Browser::approves(); + let session = sign_in( + &address, + &metadata, + store.clone(), + &Attempt::default(), + Duration::from_secs(20), + browser.opener(), + ) + .unwrap(); + + // What the browser was sent to ask for. + let asked = browser.asked(); + assert_eq!(asked["client_id"], "openbot-desktop-oauth"); + assert_eq!(asked["response_type"], "code"); + assert_eq!(asked["code_challenge_method"], "S256"); + assert!(asked["state"].len() >= 32); + let redirect = reqwest::Url::parse(&asked["redirect_uri"]).unwrap(); + assert_eq!(redirect.host_str(), Some("127.0.0.1")); + assert_eq!(redirect.path(), "/callback"); + assert!(redirect.port().is_some()); + let scopes: Vec<&str> = asked["scope"].split(' ').collect(); + assert_eq!(scopes, metadata.scopes); + assert!(scopes.contains(&"offline_access")); + // What the tab said. + let tab = browser.tab(); + assert!(tab.contains(SIGNED_IN_PAGE), "{tab}"); + + // The access token is one that OpenBot honours, and only the refresh token is stored. + let access = session.access().unwrap(); + assert!(access.starts_with("oba_")); + assert!(openbot.honours(&access)); + let stored = store.get(&address).unwrap().unwrap(); + assert!(stored.starts_with("obr_")); + assert_ne!(stored, access); + // The exchange was form-encoded with the client's id in the body, and no secret. + let exchange = openbot.token_requests().remove(0); + assert_eq!(exchange["grant_type"], "authorization_code"); + assert_eq!(exchange["client_id"], "openbot-desktop-oauth"); + assert_eq!(exchange["redirect_uri"], asked["redirect_uri"]); + assert!(!exchange.contains_key("client_secret")); + } + + /// A request to the listener with another `state` is not this sign-in's answer: it is refused, + /// no code is exchanged for it, and the real answer still completes the sign-in. + #[test] + fn a_callback_with_the_wrong_state_is_refused_and_exchanges_nothing() { + let openbot = FakeOpenBot::start(Shape::Current); + let (address, metadata) = check(&openbot); + let browser = Browser::forges_state_first(); + let session = sign_in( + &address, + &metadata, + in_memory(), + &Attempt::default(), + Duration::from_secs(20), + browser.opener(), + ) + .unwrap(); + let forged = browser.forged_answer(); + assert!(forged.starts_with("HTTP/1.1 400"), "{forged}"); + assert!(forged.contains(NOT_SIGNED_IN_PAGE), "{forged}"); + // One exchange, for the real code; the forged one never reached the token endpoint. + assert_eq!(openbot.token_requests().len(), 1); + assert!(openbot.honours(&session.access().unwrap())); + } + + #[test] + fn consent_denied_reads_as_a_sign_in_that_did_not_finish() { + let openbot = FakeOpenBot::start(Shape::Current); + let (address, metadata) = check(&openbot); + let store = in_memory(); + let browser = Browser::denies(); + let problem = sign_in( + &address, + &metadata, + store.clone(), + &Attempt::default(), + Duration::from_secs(20), + browser.opener(), + ) + .expect_err("consent was denied"); + assert_eq!(kind_of(&problem), Some(Kind::SignInCancelled)); + assert_eq!( + problem.said, + "Sign-in didn't finish. Try again when you're ready." + ); + assert!(browser.tab().contains(NOT_SIGNED_IN_PAGE)); + assert_eq!(openbot.token_requests().len(), 0); + assert_eq!(store.get(&address).unwrap(), None); + } + + #[test] + fn cancel_and_a_browser_that_never_comes_back_both_end_the_wait() { + let openbot = FakeOpenBot::start(Shape::Current); + let (address, metadata) = check(&openbot); + // Cancel, while the browser is open and nothing has come back. + let attempt = Arc::new(Attempt::default()); + let cancelling = attempt.clone(); + let started = Instant::now(); + let problem = sign_in( + &address, + &metadata, + in_memory(), + &attempt, + Duration::from_secs(30), + move |_| { + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(200)); + cancelling.cancel(); + }); + Ok(()) + }, + ) + .expect_err("cancelled"); + assert_eq!(kind_of(&problem), Some(Kind::SignInCancelled)); + assert!(started.elapsed() < Duration::from_secs(10)); + + // The wait running out, here after a moment in place of ten minutes. + let problem = sign_in( + &address, + &metadata, + in_memory(), + &Attempt::default(), + Duration::from_millis(300), + |_| Ok(()), + ) + .expect_err("timed out"); + assert_eq!(kind_of(&problem), Some(Kind::SignInCancelled)); + assert_eq!(WAIT, Duration::from_secs(600)); + } + + /// An OpenBot that signs the app in and then refuses the new token on `/api/me` is on a + /// release that cannot serve the app. Nothing is kept, and the tokens are revoked. + #[test] + fn an_openbot_that_refuses_its_own_new_token_is_too_old() { + let openbot = FakeOpenBot::start(Shape::MeRefuses); + let (address, metadata) = check(&openbot); + let store = in_memory(); + let problem = sign_in( + &address, + &metadata, + store.clone(), + &Attempt::default(), + Duration::from_secs(20), + Browser::approves().opener(), + ) + .expect_err("too old"); + assert_eq!(kind_of(&problem), Some(Kind::TooOld)); + assert_eq!(store.get(&address).unwrap(), None); + assert_eq!(openbot.live_tokens(), 0, "the unused sign-in was revoked"); + } + + /// The fake checks S256 as the real one does: a code presented with another verifier is + /// refused and burns, so the exchange that follows with the right one fails too. + #[test] + fn the_fake_openbot_really_checks_the_verifier_and_burns_the_code() { + let openbot = FakeOpenBot::start(Shape::Current); + let (_, metadata) = check(&openbot); + let verifier = random(); + let redirect = "http://127.0.0.1:49152/callback"; + let code = openbot.issue_code(&pkce_challenge(&verifier), redirect); + let exchange = |verifier: &str, redirect: &str| { + token_request( + &metadata.token_endpoint, + &[ + ("grant_type", "authorization_code"), + ("code", &code), + ("redirect_uri", redirect), + ("client_id", CLIENT_ID), + ("code_verifier", verifier), + ], + ) + }; + let refused = |result: Result| match result { + Err(Refused::Answer { status, error }) => (status, error), + _ => panic!("the exchange was not refused"), + }; + assert_eq!( + refused(exchange(&random(), redirect)), + (400, "invalid_grant".into()) + ); + assert_eq!( + refused(exchange(&verifier, redirect)), + (400, "invalid_grant".into()), + "the code burned on the wrong verifier" + ); + // Another redirect than the one the code was issued for, and a redirect by name. + let code = openbot.issue_code(&pkce_challenge(&verifier), redirect); + let other = token_request( + &metadata.token_endpoint, + &[ + ("grant_type", "authorization_code"), + ("code", &code), + ("redirect_uri", "http://127.0.0.1:49153/callback"), + ("client_id", CLIENT_ID), + ("code_verifier", &verifier), + ], + ); + assert_eq!(refused(other), (400, "invalid_grant".into())); + assert!(openbot + .authorize_refuses("http://localhost:49152/callback") + .contains("redirect_uri")); + assert!(openbot + .authorize_refuses("http://127.0.0.1:49152/oauth/callback") + .contains("redirect_uri")); + } + + /// Refresh tokens rotate: after a refresh the store holds the new one, the old one no longer + /// works, and OpenBot honours the new access token. + #[test] + fn a_refresh_rotates_and_the_store_holds_the_new_token() { + let openbot = FakeOpenBot::start(Shape::Current); + let store = in_memory(); + let session = openbot.sign_in(store.clone()); + let address = openbot.address(); + let first_access = session.access().unwrap(); + let first_refresh = store.get(&address).unwrap().unwrap(); + + openbot.expire_access_tokens(); + let second_access = session.after_refused(&first_access).unwrap(); + assert_ne!(second_access, first_access); + assert!(openbot.honours(&second_access)); + let second_refresh = store.get(&address).unwrap().unwrap(); + assert_ne!(second_refresh, first_refresh); + assert!(second_refresh.starts_with("obr_")); + + // The next launch picks the sign-in up from the store alone. + let (_, metadata) = check(&openbot); + let resumed = resume(&address, &metadata, store.clone()).unwrap(); + assert!(openbot.honours(&resumed.access().unwrap())); + + // The old refresh token, used again, is refused as the real OpenBot refuses it. + let replayed = token_request( + &metadata.token_endpoint, + &[ + ("grant_type", "refresh_token"), + ("refresh_token", &first_refresh), + ("client_id", CLIENT_ID), + ], + ); + assert!(matches!( + replayed, + Err(Refused::Answer { status: 400, ref error }) if error == "invalid_grant" + )); + } + + /// Two requests find the same token refused at the same moment. One refresh is made: a second + /// would present a refresh token the first already used up, and end the sign-in. + #[test] + fn two_refreshes_at_once_make_one_request() { + let openbot = FakeOpenBot::start(Shape::Current); + let session = Arc::new(openbot.sign_in(in_memory())); + let stale = session.access().unwrap(); + openbot.expire_access_tokens(); + openbot.slow_token_endpoint(Duration::from_millis(300)); + let before = openbot.token_requests().len(); + + let together = Arc::new(std::sync::Barrier::new(2)); + let refreshes: Vec<_> = (0..2) + .map(|_| { + let (session, stale, together) = (session.clone(), stale.clone(), together.clone()); + std::thread::spawn(move || { + together.wait(); + session.after_refused(&stale).unwrap() + }) + }) + .collect(); + let tokens: Vec = refreshes + .into_iter() + .map(|refresh| refresh.join().unwrap()) + .collect(); + assert_eq!(tokens[0], tokens[1]); + assert_ne!(tokens[0], stale); + assert_eq!(openbot.token_requests().len() - before, 1); + assert!(openbot.honours(&tokens[0])); + } + + /// A refresh the OpenBot refuses ends the sign-in: the problem says so, and the stored token + /// is forgotten, so the next launch asks the person to sign in. + #[test] + fn a_refused_refresh_ends_the_session_and_forgets_it() { + let openbot = FakeOpenBot::start(Shape::Current); + let store = in_memory(); + let session = openbot.sign_in(store.clone()); + let access = session.access().unwrap(); + openbot.end_sessions(); + let problem = session.after_refused(&access).expect_err("ended"); + assert_eq!(kind_of(&problem), Some(Kind::SessionEnded)); + assert_eq!( + problem.said, + format!( + "Your sign-in to {} has ended. Sign in again to keep going.", + session.host() + ) + ); + assert_eq!(store.get(&openbot.address()).unwrap(), None); + assert_eq!( + kind_of(&session.access().expect_err("still ended")), + Some(Kind::SessionEnded) + ); + } + + /// Sign-out revokes both tokens at the OpenBot, then forgets the sign-in here. + #[test] + fn sign_out_revokes_then_forgets() { + let openbot = FakeOpenBot::start(Shape::Current); + let store = in_memory(); + let session = openbot.sign_in(store.clone()); + let access = session.access().unwrap(); + let refresh = store.get(&openbot.address()).unwrap().unwrap(); + assert_eq!(openbot.live_tokens(), 2); + + session.sign_out().unwrap(); + + let revoked = openbot.revoke_requests(); + assert_eq!(revoked.len(), 2); + assert_eq!(revoked[0]["token"], refresh); + assert_eq!(revoked[0]["token_type_hint"], "refresh_token"); + assert_eq!(revoked[1]["token"], access); + assert!(revoked + .iter() + .all(|request| request["client_id"] == "openbot-desktop-oauth")); + assert_eq!(openbot.live_tokens(), 0); + assert!(!openbot.honours(&access)); + assert_eq!(store.get(&openbot.address()).unwrap(), None); + assert!(session.access().is_err()); + } + + /// Nothing shaped like a token reaches a file under the app's configuration folder or a line + /// of the log, through a sign-in, a refresh, a refused refresh and a sign-out. + #[test] + fn no_token_is_written_to_the_configuration_folder_or_the_log() { + if crate::test_support::isolated_process( + "connected::sign_in::tests::no_token_is_written_to_the_configuration_folder_or_the_log", + ) { + return; + } + // Every line any crate logs in this process, as written, before any scrubbing. + struct Captured(Mutex>); + impl log::Log for Captured { + fn enabled(&self, _: &log::Metadata) -> bool { + true + } + fn log(&self, record: &log::Record) { + self.0.lock().unwrap().push(record.args().to_string()); + } + fn flush(&self) {} + } + let captured: &'static Captured = Box::leak(Box::new(Captured(Mutex::new(Vec::new())))); + log::set_logger(captured).expect("nothing else logs in this process"); + log::set_max_level(log::LevelFilter::Trace); + + let config = crate::test_support::temp_root("connected-no-token"); + let openbot = FakeOpenBot::start(Shape::Current); + let store = in_memory(); + let session = openbot.sign_in(store.clone()); + let address = openbot.address(); + super::super::choice::write( + &config, + &super::super::choice::Choice { + mode: super::super::choice::Mode::Connected, + address: Some(address.clone()), + organization_id: None, + }, + ) + .unwrap(); + let mut tokens = vec![ + session.access().unwrap(), + store.get(&address).unwrap().unwrap(), + ]; + openbot.expire_access_tokens(); + tokens.push(session.after_refused(&tokens[0]).unwrap()); + tokens.push(store.get(&address).unwrap().unwrap()); + session.sign_out().unwrap(); + // And a sign-in that ends by being refused. + let session = openbot.sign_in(store.clone()); + tokens.push(session.access().unwrap()); + tokens.push(store.get(&address).unwrap().unwrap()); + openbot.end_sessions(); + session.after_refused(&tokens[4]).expect_err("ended"); + + let lines = captured.0.lock().unwrap().join("\n"); + assert!(lines.contains("[connect] signed in to"), "{lines}"); + for token in &tokens { + assert!(!lines.contains(token.as_str()), "a token was logged"); + } + assert!( + !lines.contains("oba_") && !lines.contains("obr_"), + "{lines}" + ); + let mut files = 0; + for entry in std::fs::read_dir(&config).unwrap() { + let written = std::fs::read_to_string(entry.unwrap().path()).unwrap(); + files += 1; + assert!( + !written.contains("oba_") && !written.contains("obr_"), + "{written}" + ); + } + assert_eq!(files, 1, "only connection.json is written"); + let _ = std::fs::remove_dir_all(config); + } +} diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 4bdc30db9e..4f1b0af62f 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -4,6 +4,7 @@ pub mod ai_connection; pub mod app_update; pub mod cli_release; pub mod composio; +pub mod connected; pub mod deployment; pub mod deployment_release; pub mod docker_config; diff --git a/desktop/src-tauri/src/logging.rs b/desktop/src-tauri/src/logging.rs index 5cc9165104..97c5c6df62 100644 --- a/desktop/src-tauri/src/logging.rs +++ b/desktop/src-tauri/src/logging.rs @@ -472,6 +472,12 @@ static RULES: LazyLock> = LazyLock::new(|| { r"(?i)\b(?Pset-cookie|cookie)(?P\s*[:=]\s*)[^\r\n]+", "${name}${sep}[redacted]", ), + // The secret the window carries to the relay for an OpenBot that runs elsewhere + // (`connected::relay`), wherever it is written without the word Cookie in front. + rule( + r"(?i)\b(?Popenbot-relay=)[^\s;,\x22']+", + "${name}[redacted]", + ), // `Authorization: Bearer `, `Basic `. rule(r"(?i)\b(?Pbearer)\s+[^\s\x22',;]+", "${scheme} [redacted]"), rule(r"\b(?PBasic)\s+[A-Za-z0-9+/]{12,}={0,2}", "${scheme} [redacted]"), @@ -514,6 +520,8 @@ static RULES: LazyLock> = LazyLock::new(|| { r"|ya29\.[0-9A-Za-z_\-]+", r"|npm_[A-Za-z0-9]{36}", r"|hf_[A-Za-z0-9]{30,}", + // OpenBot's own: an app's access token (`oba_`) and refresh token (`obr_`). + r"|ob[ar]_[A-Za-z0-9_\-]{8,}", r"|eyJ[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]+\.[A-Za-z0-9_\-]*", r")", ), diff --git a/desktop/src-tauri/src/logging_file_tests.rs b/desktop/src-tauri/src/logging_file_tests.rs index 4f6e97ebcc..ecb0683464 100644 --- a/desktop/src-tauri/src/logging_file_tests.rs +++ b/desktop/src-tauri/src/logging_file_tests.rs @@ -144,6 +144,58 @@ mod logging_file { let _ = std::fs::remove_dir_all(folder); } + /// The tokens an OpenBot that runs elsewhere gives this app: an access token (`oba_`) and a + /// refresh token (`obr_`). Neither reaches the file, however the line carries it, and the line + /// still says what happened. + #[test] + fn an_openbot_access_or_refresh_token_in_a_line_is_redacted_in_the_file() { + let folder = temp_root("log-redact-openbot"); + let logger = logger_in(&folder, MAX_FILE_BYTES, KEPT_FILES); + // Short and all one case, so no general rule catches them: only the prefix says token. + let access = fake("oba_", "kq7m", 3); + let refresh = fake("obr_", "zt4w", 3); + // As the real ones are: 43 characters of base64url after the prefix. + let long_access = fake("oba_", "Ab3_x-Q", 6); + let long_refresh = fake("obr_", "Zq9-k_L", 6); + info( + logger.as_ref(), + "openbot_desktop_lib::connected::relay", + &format!("[relay] OpenBot refused {access} for GET /api/me"), + ); + info( + logger.as_ref(), + "openbot_desktop_lib::connected::sign_in", + &format!("[connect] the refresh with {refresh} answered 400 invalid_grant"), + ); + logger.log( + &log::Record::builder() + .level(log::Level::Warn) + .target("reqwest::async_impl::client") + .args(format_args!( + "request failed: {long_access} then {long_refresh} at https://openbot.example.com/api/v2/bots" + )) + .build(), + ); + let written = current(&folder); + for token in [&access, &refresh, &long_access, &long_refresh] { + assert!(!written.contains(token.as_str()), "{written}"); + } + assert!(!written.contains("oba_") && !written.contains("obr_"), "{written}"); + assert!( + written.contains("[relay] OpenBot refused [redacted] for GET /api/me"), + "{written}" + ); + assert!( + written.contains("[connect] the refresh with [redacted] answered 400 invalid_grant"), + "{written}" + ); + assert!( + written.contains("https://openbot.example.com/api/v2/bots"), + "{written}" + ); + let _ = std::fs::remove_dir_all(folder); + } + /// The folder never holds more than the current file and `kept` set-aside ones, the oldest /// going first, whatever earlier sessions left there. #[test] diff --git a/desktop/src-tauri/src/problem.rs b/desktop/src-tauri/src/problem.rs index 78cae3e7c4..e950184803 100644 --- a/desktop/src-tauri/src/problem.rs +++ b/desktop/src-tauri/src/problem.rs @@ -44,6 +44,10 @@ pub struct Problem { /// Only a Windows restart fixes this, so the window offers one instead of Try again. #[serde(skip_serializing_if = "std::ops::Not::not")] pub restart_windows: bool, + /// Which failure this is, for the commands that connect to an OpenBot that runs elsewhere, so + /// the window can choose what to offer next. See `connected::Kind`. + #[serde(skip_serializing_if = "Option::is_none")] + pub kind: Option<&'static str>, } /// Exactly what one confirmed reset removes: the containers first, then the volumes. @@ -67,6 +71,7 @@ impl Problem { database_reset: None, leftover: None, restart_windows: false, + kind: None, } } @@ -80,6 +85,7 @@ impl Problem { database_reset: None, leftover: None, restart_windows: false, + kind: None, } } diff --git a/desktop/src-tauri/src/provider_oauth.rs b/desktop/src-tauri/src/provider_oauth.rs index 6873a57a63..c96b12b8a4 100644 --- a/desktop/src-tauri/src/provider_oauth.rs +++ b/desktop/src-tauri/src/provider_oauth.rs @@ -95,11 +95,16 @@ static ACTIVE: OnceLock>>> = OnceLock::new(); fn active() -> &'static Mutex>> { ACTIVE.get_or_init(|| Mutex::new(None)) } -fn random() -> String { +/// 32 random bytes as text: a PKCE verifier, a `state`. +pub(crate) fn random() -> String { let mut bytes = [0; 32]; rand::rng().fill_bytes(&mut bytes); URL_SAFE_NO_PAD.encode(bytes) } +/// The S256 challenge for a PKCE verifier (RFC 7636 §4.2). +pub(crate) fn pkce_challenge(verifier: &str) -> String { + URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) +} fn configured(name: &str) -> Option { let embedded = match name { "OPENBOT_GOOGLE_MODEL_OAUTH_CLIENT_ID" => { @@ -185,7 +190,7 @@ pub fn begin(root: &Path, provider: &str) -> Result { ); let verifier = random(); let state = random(); - let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())); + let challenge = pkce_challenge(&verifier); let mut url = reqwest::Url::parse("https://accounts.google.com/o/oauth2/v2/auth").unwrap(); url.query_pairs_mut().extend_pairs([ From 01c4f52f89fc3cd77c11ccc285d11a38cd0d2097 Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 13:08:22 -0800 Subject: [PATCH 007/116] Let Desktop connect to an OpenBot that runs elsewhere The setup window and OpenBot's own page can now ask the shell to connect to an OpenBot at an address, and the shell behaves accordingly while it is connected. On this computer, nothing changes. For the setup window: connection, check_openbot_address, connect_to_openbot, cancel_connect, show_connected, sign_out_of_openbot, use_this_computer and take_connection_notice. A failure carries a kind beside its sentence so the window can choose what to offer. Connecting checks the address, signs in through the person's browser, stops an OpenBot running on this computer the way Stop does, starts the relay and points the window at it; the choice is kept only once that has worked. When a sign-in ends while OpenBot shows, the relay stops, setup comes back and the sentence waits for it. For OpenBot's page, through the openbot-desktop plugin: connection, sign_out, change_connection and set_organization, each with a permission of its own granted to the relay's origin as the others are. change_connection also works on this computer: it stops OpenBot as Stop does and asks setup to open at the choice. While connected, status answers the app's version, build and log folder without asking an engine, and restart, stop, intelligence, ai_connection and change_ai_connection are refused. The relay's origin is trusted the way a local OpenBot's is, so its page is OpenBot's own page to the window: the overlay title bar, the theme, notifications, dictation, zoom, and links to anywhere else (the typed address included) opening in the browser. While the choice is to be connected, nothing of an installation on this computer is started, read or written: the engine is not woken, nothing is downloaded or made ready, Start, Show and the upgrade are refused, the installation's folder is not looked for at launch, and Quit only stops the relay. The tray and the menu carry Show Window, Open Log Folder, Sign Out and Quit. The setup window's connect_openbot step is one the shell's telemetry knows; its events carry the step's name and never the address. docs/desktop-install.md says what the choice is, how sign-in and the relay work, and what is not there while connected. --- desktop/src-tauri/build.rs | 7 + .../src-tauri/gen/schemas/acl-manifests.json | 2 +- .../src-tauri/gen/schemas/capabilities.json | 2 +- .../src-tauri/gen/schemas/desktop-schema.json | 48 ++ .../src-tauri/gen/schemas/macOS-schema.json | 48 ++ desktop/src-tauri/src/connected_ipc_tests.rs | 631 ++++++++++++++++++ desktop/src-tauri/src/desktop_connected.rs | 617 +++++++++++++++++ desktop/src-tauri/src/desktop_page.rs | 78 ++- desktop/src-tauri/src/main.rs | 197 +++++- desktop/src-tauri/src/stop_ipc_tests.rs | 3 +- desktop/src-tauri/src/telemetry.rs | 47 +- docs/desktop-install.md | 39 +- 12 files changed, 1706 insertions(+), 13 deletions(-) create mode 100644 desktop/src-tauri/src/connected_ipc_tests.rs create mode 100644 desktop/src-tauri/src/desktop_connected.rs diff --git a/desktop/src-tauri/build.rs b/desktop/src-tauri/build.rs index 4bf6f01437..49064a119e 100644 --- a/desktop/src-tauri/build.rs +++ b/desktop/src-tauri/build.rs @@ -75,6 +75,13 @@ fn main() { "quit", // The zoom keys no menu carries. See `src/zoom-shortcut.js`. "zoom", + // Where OpenBot runs, and Settings' Sign out, Change and the organisation + // picked, for an app connected to an OpenBot that runs elsewhere. See + // `src/desktop_connected.rs`. + "connection", + "sign_out", + "change_connection", + "set_organization", ]), ), ) diff --git a/desktop/src-tauri/gen/schemas/acl-manifests.json b/desktop/src-tauri/gen/schemas/acl-manifests.json index ee1c172cef..fec8066a0b 100644 --- a/desktop/src-tauri/gen/schemas/acl-manifests.json +++ b/desktop/src-tauri/gen/schemas/acl-manifests.json @@ -1 +1 @@ -{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"deep-link":{"default_permission":{"identifier":"default","description":"Allows reading the opened deep link via the get_current command","permissions":["allow-get-current"]},"permissions":{"allow-get-current":{"identifier":"allow-get-current","description":"Enables the get_current command without any pre-configured scope.","commands":{"allow":["get_current"],"deny":[]}},"allow-is-registered":{"identifier":"allow-is-registered","description":"Enables the is_registered command without any pre-configured scope.","commands":{"allow":["is_registered"],"deny":[]}},"allow-register":{"identifier":"allow-register","description":"Enables the register command without any pre-configured scope.","commands":{"allow":["register"],"deny":[]}},"allow-unregister":{"identifier":"allow-unregister","description":"Enables the unregister command without any pre-configured scope.","commands":{"allow":["unregister"],"deny":[]}},"deny-get-current":{"identifier":"deny-get-current","description":"Denies the get_current command without any pre-configured scope.","commands":{"allow":[],"deny":["get_current"]}},"deny-is-registered":{"identifier":"deny-is-registered","description":"Denies the is_registered command without any pre-configured scope.","commands":{"allow":[],"deny":["is_registered"]}},"deny-register":{"identifier":"deny-register","description":"Denies the register command without any pre-configured scope.","commands":{"allow":[],"deny":["register"]}},"deny-unregister":{"identifier":"deny-unregister","description":"Denies the unregister command without any pre-configured scope.","commands":{"allow":[],"deny":["unregister"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"log":{"default_permission":{"identifier":"default","description":"Allows the log command","permissions":["allow-log"]},"permissions":{"allow-log":{"identifier":"allow-log","description":"Enables the log command without any pre-configured scope.","commands":{"allow":["log"],"deny":[]}},"deny-log":{"identifier":"deny-log","description":"Denies the log command without any pre-configured scope.","commands":{"allow":[],"deny":["log"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"openbot-desktop":{"default_permission":null,"permissions":{"allow-ai-connection":{"identifier":"allow-ai-connection","description":"Enables the ai_connection command without any pre-configured scope.","commands":{"allow":["ai_connection"],"deny":[]}},"allow-appearance":{"identifier":"allow-appearance","description":"Enables the appearance command without any pre-configured scope.","commands":{"allow":["appearance"],"deny":[]}},"allow-change-ai-connection":{"identifier":"allow-change-ai-connection","description":"Enables the change_ai_connection command without any pre-configured scope.","commands":{"allow":["change_ai_connection"],"deny":[]}},"allow-check-update":{"identifier":"allow-check-update","description":"Enables the check_update command without any pre-configured scope.","commands":{"allow":["check_update"],"deny":[]}},"allow-dismiss-update":{"identifier":"allow-dismiss-update","description":"Enables the dismiss_update command without any pre-configured scope.","commands":{"allow":["dismiss_update"],"deny":[]}},"allow-install-update":{"identifier":"allow-install-update","description":"Enables the install_update command without any pre-configured scope.","commands":{"allow":["install_update"],"deny":[]}},"allow-intelligence":{"identifier":"allow-intelligence","description":"Enables the intelligence command without any pre-configured scope.","commands":{"allow":["intelligence"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-open-logs":{"identifier":"allow-open-logs","description":"Enables the open_logs command without any pre-configured scope.","commands":{"allow":["open_logs"],"deny":[]}},"allow-quit":{"identifier":"allow-quit","description":"Enables the quit command without any pre-configured scope.","commands":{"allow":["quit"],"deny":[]}},"allow-restart":{"identifier":"allow-restart","description":"Enables the restart command without any pre-configured scope.","commands":{"allow":["restart"],"deny":[]}},"allow-set-usage-data":{"identifier":"allow-set-usage-data","description":"Enables the set_usage_data command without any pre-configured scope.","commands":{"allow":["set_usage_data"],"deny":[]}},"allow-speech-abort":{"identifier":"allow-speech-abort","description":"Enables the speech_abort command without any pre-configured scope.","commands":{"allow":["speech_abort"],"deny":[]}},"allow-speech-available":{"identifier":"allow-speech-available","description":"Enables the speech_available command without any pre-configured scope.","commands":{"allow":["speech_available"],"deny":[]}},"allow-speech-start":{"identifier":"allow-speech-start","description":"Enables the speech_start command without any pre-configured scope.","commands":{"allow":["speech_start"],"deny":[]}},"allow-speech-stop":{"identifier":"allow-speech-stop","description":"Enables the speech_stop command without any pre-configured scope.","commands":{"allow":["speech_stop"],"deny":[]}},"allow-status":{"identifier":"allow-status","description":"Enables the status command without any pre-configured scope.","commands":{"allow":["status"],"deny":[]}},"allow-stop":{"identifier":"allow-stop","description":"Enables the stop command without any pre-configured scope.","commands":{"allow":["stop"],"deny":[]}},"allow-update-offer":{"identifier":"allow-update-offer","description":"Enables the update_offer command without any pre-configured scope.","commands":{"allow":["update_offer"],"deny":[]}},"allow-usage-data":{"identifier":"allow-usage-data","description":"Enables the usage_data command without any pre-configured scope.","commands":{"allow":["usage_data"],"deny":[]}},"allow-zoom":{"identifier":"allow-zoom","description":"Enables the zoom command without any pre-configured scope.","commands":{"allow":["zoom"],"deny":[]}},"deny-ai-connection":{"identifier":"deny-ai-connection","description":"Denies the ai_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["ai_connection"]}},"deny-appearance":{"identifier":"deny-appearance","description":"Denies the appearance command without any pre-configured scope.","commands":{"allow":[],"deny":["appearance"]}},"deny-change-ai-connection":{"identifier":"deny-change-ai-connection","description":"Denies the change_ai_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["change_ai_connection"]}},"deny-check-update":{"identifier":"deny-check-update","description":"Denies the check_update command without any pre-configured scope.","commands":{"allow":[],"deny":["check_update"]}},"deny-dismiss-update":{"identifier":"deny-dismiss-update","description":"Denies the dismiss_update command without any pre-configured scope.","commands":{"allow":[],"deny":["dismiss_update"]}},"deny-install-update":{"identifier":"deny-install-update","description":"Denies the install_update command without any pre-configured scope.","commands":{"allow":[],"deny":["install_update"]}},"deny-intelligence":{"identifier":"deny-intelligence","description":"Denies the intelligence command without any pre-configured scope.","commands":{"allow":[],"deny":["intelligence"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-open-logs":{"identifier":"deny-open-logs","description":"Denies the open_logs command without any pre-configured scope.","commands":{"allow":[],"deny":["open_logs"]}},"deny-quit":{"identifier":"deny-quit","description":"Denies the quit command without any pre-configured scope.","commands":{"allow":[],"deny":["quit"]}},"deny-restart":{"identifier":"deny-restart","description":"Denies the restart command without any pre-configured scope.","commands":{"allow":[],"deny":["restart"]}},"deny-set-usage-data":{"identifier":"deny-set-usage-data","description":"Denies the set_usage_data command without any pre-configured scope.","commands":{"allow":[],"deny":["set_usage_data"]}},"deny-speech-abort":{"identifier":"deny-speech-abort","description":"Denies the speech_abort command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_abort"]}},"deny-speech-available":{"identifier":"deny-speech-available","description":"Denies the speech_available command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_available"]}},"deny-speech-start":{"identifier":"deny-speech-start","description":"Denies the speech_start command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_start"]}},"deny-speech-stop":{"identifier":"deny-speech-stop","description":"Denies the speech_stop command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_stop"]}},"deny-status":{"identifier":"deny-status","description":"Denies the status command without any pre-configured scope.","commands":{"allow":[],"deny":["status"]}},"deny-stop":{"identifier":"deny-stop","description":"Denies the stop command without any pre-configured scope.","commands":{"allow":[],"deny":["stop"]}},"deny-update-offer":{"identifier":"deny-update-offer","description":"Denies the update_offer command without any pre-configured scope.","commands":{"allow":[],"deny":["update_offer"]}},"deny-usage-data":{"identifier":"deny-usage-data","description":"Denies the usage_data command without any pre-configured scope.","commands":{"allow":[],"deny":["usage_data"]}},"deny-zoom":{"identifier":"deny-zoom","description":"Denies the zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["zoom"]}}},"permission_sets":{},"global_scope_schema":null},"openbot-intelligence":{"default_permission":null,"permissions":{"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-watch":{"identifier":"allow-watch","description":"Enables the watch command without any pre-configured scope.","commands":{"allow":["watch"],"deny":[]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-watch":{"identifier":"deny-watch","description":"Denies the watch command without any pre-configured scope.","commands":{"allow":[],"deny":["watch"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}},"shell":{"default_permission":{"identifier":"default","description":"This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n","permissions":["allow-open"]},"permissions":{"allow-execute":{"identifier":"allow-execute","description":"Enables the execute command without any pre-configured scope.","commands":{"allow":["execute"],"deny":[]}},"allow-kill":{"identifier":"allow-kill","description":"Enables the kill command without any pre-configured scope.","commands":{"allow":["kill"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-spawn":{"identifier":"allow-spawn","description":"Enables the spawn command without any pre-configured scope.","commands":{"allow":["spawn"],"deny":[]}},"allow-stdin-write":{"identifier":"allow-stdin-write","description":"Enables the stdin_write command without any pre-configured scope.","commands":{"allow":["stdin_write"],"deny":[]}},"deny-execute":{"identifier":"deny-execute","description":"Denies the execute command without any pre-configured scope.","commands":{"allow":[],"deny":["execute"]}},"deny-kill":{"identifier":"deny-kill","description":"Denies the kill command without any pre-configured scope.","commands":{"allow":[],"deny":["kill"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-spawn":{"identifier":"deny-spawn","description":"Denies the spawn command without any pre-configured scope.","commands":{"allow":[],"deny":["spawn"]}},"deny-stdin-write":{"identifier":"deny-stdin-write","description":"Denies the stdin_write command without any pre-configured scope.","commands":{"allow":[],"deny":["stdin_write"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"cmd":{"description":"The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"}},"required":["cmd","name"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"},"sidecar":{"description":"If this command is a sidecar command.","type":"boolean"}},"required":["name","sidecar"],"type":"object"}],"definitions":{"ShellScopeEntryAllowedArg":{"anyOf":[{"description":"A non-configurable argument that is passed to the command in the order it was specified.","type":"string"},{"additionalProperties":false,"description":"A variable that is set while calling the command from the webview API.","properties":{"raw":{"default":false,"description":"Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.","type":"boolean"},"validator":{"description":"[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: ","type":"string"}},"required":["validator"],"type":"object"}],"description":"A command argument allowed to be executed by the webview API."},"ShellScopeEntryAllowedArgs":{"anyOf":[{"description":"Use a simple boolean to allow all or disable all arguments to this command configuration.","type":"boolean"},{"description":"A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.","items":{"$ref":"#/definitions/ShellScopeEntryAllowedArg"},"type":"array"}],"description":"A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration."}},"description":"Shell scope entry.","title":"ShellScopeEntry"}},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null},"window-state":{"default_permission":{"identifier":"default","description":"This permission set configures what kind of\noperations are available from the window state plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n","permissions":["allow-filename","allow-restore-state","allow-save-window-state"]},"permissions":{"allow-filename":{"identifier":"allow-filename","description":"Enables the filename command without any pre-configured scope.","commands":{"allow":["filename"],"deny":[]}},"allow-restore-state":{"identifier":"allow-restore-state","description":"Enables the restore_state command without any pre-configured scope.","commands":{"allow":["restore_state"],"deny":[]}},"allow-save-window-state":{"identifier":"allow-save-window-state","description":"Enables the save_window_state command without any pre-configured scope.","commands":{"allow":["save_window_state"],"deny":[]}},"deny-filename":{"identifier":"deny-filename","description":"Denies the filename command without any pre-configured scope.","commands":{"allow":[],"deny":["filename"]}},"deny-restore-state":{"identifier":"deny-restore-state","description":"Denies the restore_state command without any pre-configured scope.","commands":{"allow":[],"deny":["restore_state"]}},"deny-save-window-state":{"identifier":"deny-save-window-state","description":"Denies the save_window_state command without any pre-configured scope.","commands":{"allow":[],"deny":["save_window_state"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file +{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"deep-link":{"default_permission":{"identifier":"default","description":"Allows reading the opened deep link via the get_current command","permissions":["allow-get-current"]},"permissions":{"allow-get-current":{"identifier":"allow-get-current","description":"Enables the get_current command without any pre-configured scope.","commands":{"allow":["get_current"],"deny":[]}},"allow-is-registered":{"identifier":"allow-is-registered","description":"Enables the is_registered command without any pre-configured scope.","commands":{"allow":["is_registered"],"deny":[]}},"allow-register":{"identifier":"allow-register","description":"Enables the register command without any pre-configured scope.","commands":{"allow":["register"],"deny":[]}},"allow-unregister":{"identifier":"allow-unregister","description":"Enables the unregister command without any pre-configured scope.","commands":{"allow":["unregister"],"deny":[]}},"deny-get-current":{"identifier":"deny-get-current","description":"Denies the get_current command without any pre-configured scope.","commands":{"allow":[],"deny":["get_current"]}},"deny-is-registered":{"identifier":"deny-is-registered","description":"Denies the is_registered command without any pre-configured scope.","commands":{"allow":[],"deny":["is_registered"]}},"deny-register":{"identifier":"deny-register","description":"Denies the register command without any pre-configured scope.","commands":{"allow":[],"deny":["register"]}},"deny-unregister":{"identifier":"deny-unregister","description":"Denies the unregister command without any pre-configured scope.","commands":{"allow":[],"deny":["unregister"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"log":{"default_permission":{"identifier":"default","description":"Allows the log command","permissions":["allow-log"]},"permissions":{"allow-log":{"identifier":"allow-log","description":"Enables the log command without any pre-configured scope.","commands":{"allow":["log"],"deny":[]}},"deny-log":{"identifier":"deny-log","description":"Denies the log command without any pre-configured scope.","commands":{"allow":[],"deny":["log"]}}},"permission_sets":{},"global_scope_schema":null},"notification":{"default_permission":{"identifier":"default","description":"This permission set configures which\nnotification features are by default exposed.\n\n#### Granted Permissions\n\nIt allows all notification related features.\n\n","permissions":["allow-is-permission-granted","allow-request-permission","allow-notify","allow-register-action-types","allow-register-listener","allow-remove-listener","allow-cancel","allow-get-pending","allow-remove-active","allow-get-active","allow-check-permissions","allow-show","allow-batch","allow-list-channels","allow-delete-channel","allow-create-channel","allow-permission-state"]},"permissions":{"allow-batch":{"identifier":"allow-batch","description":"Enables the batch command without any pre-configured scope.","commands":{"allow":["batch"],"deny":[]}},"allow-cancel":{"identifier":"allow-cancel","description":"Enables the cancel command without any pre-configured scope.","commands":{"allow":["cancel"],"deny":[]}},"allow-check-permissions":{"identifier":"allow-check-permissions","description":"Enables the check_permissions command without any pre-configured scope.","commands":{"allow":["check_permissions"],"deny":[]}},"allow-create-channel":{"identifier":"allow-create-channel","description":"Enables the create_channel command without any pre-configured scope.","commands":{"allow":["create_channel"],"deny":[]}},"allow-delete-channel":{"identifier":"allow-delete-channel","description":"Enables the delete_channel command without any pre-configured scope.","commands":{"allow":["delete_channel"],"deny":[]}},"allow-get-active":{"identifier":"allow-get-active","description":"Enables the get_active command without any pre-configured scope.","commands":{"allow":["get_active"],"deny":[]}},"allow-get-pending":{"identifier":"allow-get-pending","description":"Enables the get_pending command without any pre-configured scope.","commands":{"allow":["get_pending"],"deny":[]}},"allow-is-permission-granted":{"identifier":"allow-is-permission-granted","description":"Enables the is_permission_granted command without any pre-configured scope.","commands":{"allow":["is_permission_granted"],"deny":[]}},"allow-list-channels":{"identifier":"allow-list-channels","description":"Enables the list_channels command without any pre-configured scope.","commands":{"allow":["list_channels"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-permission-state":{"identifier":"allow-permission-state","description":"Enables the permission_state command without any pre-configured scope.","commands":{"allow":["permission_state"],"deny":[]}},"allow-register-action-types":{"identifier":"allow-register-action-types","description":"Enables the register_action_types command without any pre-configured scope.","commands":{"allow":["register_action_types"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-active":{"identifier":"allow-remove-active","description":"Enables the remove_active command without any pre-configured scope.","commands":{"allow":["remove_active"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-request-permission":{"identifier":"allow-request-permission","description":"Enables the request_permission command without any pre-configured scope.","commands":{"allow":["request_permission"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"deny-batch":{"identifier":"deny-batch","description":"Denies the batch command without any pre-configured scope.","commands":{"allow":[],"deny":["batch"]}},"deny-cancel":{"identifier":"deny-cancel","description":"Denies the cancel command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel"]}},"deny-check-permissions":{"identifier":"deny-check-permissions","description":"Denies the check_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_permissions"]}},"deny-create-channel":{"identifier":"deny-create-channel","description":"Denies the create_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["create_channel"]}},"deny-delete-channel":{"identifier":"deny-delete-channel","description":"Denies the delete_channel command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_channel"]}},"deny-get-active":{"identifier":"deny-get-active","description":"Denies the get_active command without any pre-configured scope.","commands":{"allow":[],"deny":["get_active"]}},"deny-get-pending":{"identifier":"deny-get-pending","description":"Denies the get_pending command without any pre-configured scope.","commands":{"allow":[],"deny":["get_pending"]}},"deny-is-permission-granted":{"identifier":"deny-is-permission-granted","description":"Denies the is_permission_granted command without any pre-configured scope.","commands":{"allow":[],"deny":["is_permission_granted"]}},"deny-list-channels":{"identifier":"deny-list-channels","description":"Denies the list_channels command without any pre-configured scope.","commands":{"allow":[],"deny":["list_channels"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-permission-state":{"identifier":"deny-permission-state","description":"Denies the permission_state command without any pre-configured scope.","commands":{"allow":[],"deny":["permission_state"]}},"deny-register-action-types":{"identifier":"deny-register-action-types","description":"Denies the register_action_types command without any pre-configured scope.","commands":{"allow":[],"deny":["register_action_types"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-active":{"identifier":"deny-remove-active","description":"Denies the remove_active command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_active"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-request-permission":{"identifier":"deny-request-permission","description":"Denies the request_permission command without any pre-configured scope.","commands":{"allow":[],"deny":["request_permission"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}}},"permission_sets":{},"global_scope_schema":null},"openbot-desktop":{"default_permission":null,"permissions":{"allow-ai-connection":{"identifier":"allow-ai-connection","description":"Enables the ai_connection command without any pre-configured scope.","commands":{"allow":["ai_connection"],"deny":[]}},"allow-appearance":{"identifier":"allow-appearance","description":"Enables the appearance command without any pre-configured scope.","commands":{"allow":["appearance"],"deny":[]}},"allow-change-ai-connection":{"identifier":"allow-change-ai-connection","description":"Enables the change_ai_connection command without any pre-configured scope.","commands":{"allow":["change_ai_connection"],"deny":[]}},"allow-change-connection":{"identifier":"allow-change-connection","description":"Enables the change_connection command without any pre-configured scope.","commands":{"allow":["change_connection"],"deny":[]}},"allow-check-update":{"identifier":"allow-check-update","description":"Enables the check_update command without any pre-configured scope.","commands":{"allow":["check_update"],"deny":[]}},"allow-connection":{"identifier":"allow-connection","description":"Enables the connection command without any pre-configured scope.","commands":{"allow":["connection"],"deny":[]}},"allow-dismiss-update":{"identifier":"allow-dismiss-update","description":"Enables the dismiss_update command without any pre-configured scope.","commands":{"allow":["dismiss_update"],"deny":[]}},"allow-install-update":{"identifier":"allow-install-update","description":"Enables the install_update command without any pre-configured scope.","commands":{"allow":["install_update"],"deny":[]}},"allow-intelligence":{"identifier":"allow-intelligence","description":"Enables the intelligence command without any pre-configured scope.","commands":{"allow":["intelligence"],"deny":[]}},"allow-notify":{"identifier":"allow-notify","description":"Enables the notify command without any pre-configured scope.","commands":{"allow":["notify"],"deny":[]}},"allow-open-logs":{"identifier":"allow-open-logs","description":"Enables the open_logs command without any pre-configured scope.","commands":{"allow":["open_logs"],"deny":[]}},"allow-quit":{"identifier":"allow-quit","description":"Enables the quit command without any pre-configured scope.","commands":{"allow":["quit"],"deny":[]}},"allow-restart":{"identifier":"allow-restart","description":"Enables the restart command without any pre-configured scope.","commands":{"allow":["restart"],"deny":[]}},"allow-set-organization":{"identifier":"allow-set-organization","description":"Enables the set_organization command without any pre-configured scope.","commands":{"allow":["set_organization"],"deny":[]}},"allow-set-usage-data":{"identifier":"allow-set-usage-data","description":"Enables the set_usage_data command without any pre-configured scope.","commands":{"allow":["set_usage_data"],"deny":[]}},"allow-sign-out":{"identifier":"allow-sign-out","description":"Enables the sign_out command without any pre-configured scope.","commands":{"allow":["sign_out"],"deny":[]}},"allow-speech-abort":{"identifier":"allow-speech-abort","description":"Enables the speech_abort command without any pre-configured scope.","commands":{"allow":["speech_abort"],"deny":[]}},"allow-speech-available":{"identifier":"allow-speech-available","description":"Enables the speech_available command without any pre-configured scope.","commands":{"allow":["speech_available"],"deny":[]}},"allow-speech-start":{"identifier":"allow-speech-start","description":"Enables the speech_start command without any pre-configured scope.","commands":{"allow":["speech_start"],"deny":[]}},"allow-speech-stop":{"identifier":"allow-speech-stop","description":"Enables the speech_stop command without any pre-configured scope.","commands":{"allow":["speech_stop"],"deny":[]}},"allow-status":{"identifier":"allow-status","description":"Enables the status command without any pre-configured scope.","commands":{"allow":["status"],"deny":[]}},"allow-stop":{"identifier":"allow-stop","description":"Enables the stop command without any pre-configured scope.","commands":{"allow":["stop"],"deny":[]}},"allow-update-offer":{"identifier":"allow-update-offer","description":"Enables the update_offer command without any pre-configured scope.","commands":{"allow":["update_offer"],"deny":[]}},"allow-usage-data":{"identifier":"allow-usage-data","description":"Enables the usage_data command without any pre-configured scope.","commands":{"allow":["usage_data"],"deny":[]}},"allow-zoom":{"identifier":"allow-zoom","description":"Enables the zoom command without any pre-configured scope.","commands":{"allow":["zoom"],"deny":[]}},"deny-ai-connection":{"identifier":"deny-ai-connection","description":"Denies the ai_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["ai_connection"]}},"deny-appearance":{"identifier":"deny-appearance","description":"Denies the appearance command without any pre-configured scope.","commands":{"allow":[],"deny":["appearance"]}},"deny-change-ai-connection":{"identifier":"deny-change-ai-connection","description":"Denies the change_ai_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["change_ai_connection"]}},"deny-change-connection":{"identifier":"deny-change-connection","description":"Denies the change_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["change_connection"]}},"deny-check-update":{"identifier":"deny-check-update","description":"Denies the check_update command without any pre-configured scope.","commands":{"allow":[],"deny":["check_update"]}},"deny-connection":{"identifier":"deny-connection","description":"Denies the connection command without any pre-configured scope.","commands":{"allow":[],"deny":["connection"]}},"deny-dismiss-update":{"identifier":"deny-dismiss-update","description":"Denies the dismiss_update command without any pre-configured scope.","commands":{"allow":[],"deny":["dismiss_update"]}},"deny-install-update":{"identifier":"deny-install-update","description":"Denies the install_update command without any pre-configured scope.","commands":{"allow":[],"deny":["install_update"]}},"deny-intelligence":{"identifier":"deny-intelligence","description":"Denies the intelligence command without any pre-configured scope.","commands":{"allow":[],"deny":["intelligence"]}},"deny-notify":{"identifier":"deny-notify","description":"Denies the notify command without any pre-configured scope.","commands":{"allow":[],"deny":["notify"]}},"deny-open-logs":{"identifier":"deny-open-logs","description":"Denies the open_logs command without any pre-configured scope.","commands":{"allow":[],"deny":["open_logs"]}},"deny-quit":{"identifier":"deny-quit","description":"Denies the quit command without any pre-configured scope.","commands":{"allow":[],"deny":["quit"]}},"deny-restart":{"identifier":"deny-restart","description":"Denies the restart command without any pre-configured scope.","commands":{"allow":[],"deny":["restart"]}},"deny-set-organization":{"identifier":"deny-set-organization","description":"Denies the set_organization command without any pre-configured scope.","commands":{"allow":[],"deny":["set_organization"]}},"deny-set-usage-data":{"identifier":"deny-set-usage-data","description":"Denies the set_usage_data command without any pre-configured scope.","commands":{"allow":[],"deny":["set_usage_data"]}},"deny-sign-out":{"identifier":"deny-sign-out","description":"Denies the sign_out command without any pre-configured scope.","commands":{"allow":[],"deny":["sign_out"]}},"deny-speech-abort":{"identifier":"deny-speech-abort","description":"Denies the speech_abort command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_abort"]}},"deny-speech-available":{"identifier":"deny-speech-available","description":"Denies the speech_available command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_available"]}},"deny-speech-start":{"identifier":"deny-speech-start","description":"Denies the speech_start command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_start"]}},"deny-speech-stop":{"identifier":"deny-speech-stop","description":"Denies the speech_stop command without any pre-configured scope.","commands":{"allow":[],"deny":["speech_stop"]}},"deny-status":{"identifier":"deny-status","description":"Denies the status command without any pre-configured scope.","commands":{"allow":[],"deny":["status"]}},"deny-stop":{"identifier":"deny-stop","description":"Denies the stop command without any pre-configured scope.","commands":{"allow":[],"deny":["stop"]}},"deny-update-offer":{"identifier":"deny-update-offer","description":"Denies the update_offer command without any pre-configured scope.","commands":{"allow":[],"deny":["update_offer"]}},"deny-usage-data":{"identifier":"deny-usage-data","description":"Denies the usage_data command without any pre-configured scope.","commands":{"allow":[],"deny":["usage_data"]}},"deny-zoom":{"identifier":"deny-zoom","description":"Denies the zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["zoom"]}}},"permission_sets":{},"global_scope_schema":null},"openbot-intelligence":{"default_permission":null,"permissions":{"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-watch":{"identifier":"allow-watch","description":"Enables the watch command without any pre-configured scope.","commands":{"allow":["watch"],"deny":[]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-watch":{"identifier":"deny-watch","description":"Denies the watch command without any pre-configured scope.","commands":{"allow":[],"deny":["watch"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}},"shell":{"default_permission":{"identifier":"default","description":"This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n","permissions":["allow-open"]},"permissions":{"allow-execute":{"identifier":"allow-execute","description":"Enables the execute command without any pre-configured scope.","commands":{"allow":["execute"],"deny":[]}},"allow-kill":{"identifier":"allow-kill","description":"Enables the kill command without any pre-configured scope.","commands":{"allow":["kill"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-spawn":{"identifier":"allow-spawn","description":"Enables the spawn command without any pre-configured scope.","commands":{"allow":["spawn"],"deny":[]}},"allow-stdin-write":{"identifier":"allow-stdin-write","description":"Enables the stdin_write command without any pre-configured scope.","commands":{"allow":["stdin_write"],"deny":[]}},"deny-execute":{"identifier":"deny-execute","description":"Denies the execute command without any pre-configured scope.","commands":{"allow":[],"deny":["execute"]}},"deny-kill":{"identifier":"deny-kill","description":"Denies the kill command without any pre-configured scope.","commands":{"allow":[],"deny":["kill"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-spawn":{"identifier":"deny-spawn","description":"Denies the spawn command without any pre-configured scope.","commands":{"allow":[],"deny":["spawn"]}},"deny-stdin-write":{"identifier":"deny-stdin-write","description":"Denies the stdin_write command without any pre-configured scope.","commands":{"allow":[],"deny":["stdin_write"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"cmd":{"description":"The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"}},"required":["cmd","name"],"type":"object"},{"additionalProperties":false,"properties":{"args":{"allOf":[{"$ref":"#/definitions/ShellScopeEntryAllowedArgs"}],"description":"The allowed arguments for the command execution."},"name":{"description":"The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.","type":"string"},"sidecar":{"description":"If this command is a sidecar command.","type":"boolean"}},"required":["name","sidecar"],"type":"object"}],"definitions":{"ShellScopeEntryAllowedArg":{"anyOf":[{"description":"A non-configurable argument that is passed to the command in the order it was specified.","type":"string"},{"additionalProperties":false,"description":"A variable that is set while calling the command from the webview API.","properties":{"raw":{"default":false,"description":"Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.","type":"boolean"},"validator":{"description":"[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: ","type":"string"}},"required":["validator"],"type":"object"}],"description":"A command argument allowed to be executed by the webview API."},"ShellScopeEntryAllowedArgs":{"anyOf":[{"description":"Use a simple boolean to allow all or disable all arguments to this command configuration.","type":"boolean"},{"description":"A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.","items":{"$ref":"#/definitions/ShellScopeEntryAllowedArg"},"type":"array"}],"description":"A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration."}},"description":"Shell scope entry.","title":"ShellScopeEntry"}},"updater":{"default_permission":{"identifier":"default","description":"This permission set configures which kind of\nupdater functions are exposed to the frontend.\n\n#### Granted Permissions\n\nThe full workflow from checking for updates to installing them\nis enabled.\n\n","permissions":["allow-check","allow-download","allow-install","allow-download-and-install"]},"permissions":{"allow-check":{"identifier":"allow-check","description":"Enables the check command without any pre-configured scope.","commands":{"allow":["check"],"deny":[]}},"allow-download":{"identifier":"allow-download","description":"Enables the download command without any pre-configured scope.","commands":{"allow":["download"],"deny":[]}},"allow-download-and-install":{"identifier":"allow-download-and-install","description":"Enables the download_and_install command without any pre-configured scope.","commands":{"allow":["download_and_install"],"deny":[]}},"allow-install":{"identifier":"allow-install","description":"Enables the install command without any pre-configured scope.","commands":{"allow":["install"],"deny":[]}},"deny-check":{"identifier":"deny-check","description":"Denies the check command without any pre-configured scope.","commands":{"allow":[],"deny":["check"]}},"deny-download":{"identifier":"deny-download","description":"Denies the download command without any pre-configured scope.","commands":{"allow":[],"deny":["download"]}},"deny-download-and-install":{"identifier":"deny-download-and-install","description":"Denies the download_and_install command without any pre-configured scope.","commands":{"allow":[],"deny":["download_and_install"]}},"deny-install":{"identifier":"deny-install","description":"Denies the install command without any pre-configured scope.","commands":{"allow":[],"deny":["install"]}}},"permission_sets":{},"global_scope_schema":null},"window-state":{"default_permission":{"identifier":"default","description":"This permission set configures what kind of\noperations are available from the window state plugin.\n\n#### Granted Permissions\n\nAll operations are enabled by default.\n\n","permissions":["allow-filename","allow-restore-state","allow-save-window-state"]},"permissions":{"allow-filename":{"identifier":"allow-filename","description":"Enables the filename command without any pre-configured scope.","commands":{"allow":["filename"],"deny":[]}},"allow-restore-state":{"identifier":"allow-restore-state","description":"Enables the restore_state command without any pre-configured scope.","commands":{"allow":["restore_state"],"deny":[]}},"allow-save-window-state":{"identifier":"allow-save-window-state","description":"Enables the save_window_state command without any pre-configured scope.","commands":{"allow":["save_window_state"],"deny":[]}},"deny-filename":{"identifier":"deny-filename","description":"Denies the filename command without any pre-configured scope.","commands":{"allow":[],"deny":["filename"]}},"deny-restore-state":{"identifier":"deny-restore-state","description":"Denies the restore_state command without any pre-configured scope.","commands":{"allow":[],"deny":["restore_state"]}},"deny-save-window-state":{"identifier":"deny-save-window-state","description":"Denies the save_window_state command without any pre-configured scope.","commands":{"allow":[],"deny":["save_window_state"]}}},"permission_sets":{},"global_scope_schema":null}} \ No newline at end of file diff --git a/desktop/src-tauri/gen/schemas/capabilities.json b/desktop/src-tauri/gen/schemas/capabilities.json index 9bec23ce41..2a3c14a01f 100644 --- a/desktop/src-tauri/gen/schemas/capabilities.json +++ b/desktop/src-tauri/gen/schemas/capabilities.json @@ -1 +1 @@ -{"default":{"identifier":"default","description":"What the setup window is allowed to do. Commands this app defines are always callable; everything under core: is not, and has to be granted here.","local":true,"windows":["main","status"],"permissions":["core:event:default","openbot-desktop:allow-quit","openbot-desktop:allow-zoom",{"identifier":"opener:allow-open-url","allow":[{"url":"https://*"},{"url":"http://*"}]}]}} \ No newline at end of file +{"default":{"identifier":"default","description":"What the setup window is allowed to do. Commands this app defines are always callable; everything under core: is not, and has to be granted here.","local":true,"windows":["main","status"],"permissions":["core:event:default","openbot-desktop:allow-quit","openbot-desktop:allow-zoom","openbot-desktop:allow-usage-data","openbot-desktop:allow-set-usage-data",{"identifier":"opener:allow-open-url","allow":[{"url":"https://*"},{"url":"http://*"}]}]}} \ No newline at end of file diff --git a/desktop/src-tauri/gen/schemas/desktop-schema.json b/desktop/src-tauri/gen/schemas/desktop-schema.json index 370501d5e6..a1504a7fa4 100644 --- a/desktop/src-tauri/gen/schemas/desktop-schema.json +++ b/desktop/src-tauri/gen/schemas/desktop-schema.json @@ -2960,12 +2960,24 @@ "const": "openbot-desktop:allow-change-ai-connection", "markdownDescription": "Enables the change_ai_connection command without any pre-configured scope." }, + { + "description": "Enables the change_connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-change-connection", + "markdownDescription": "Enables the change_connection command without any pre-configured scope." + }, { "description": "Enables the check_update command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:allow-check-update", "markdownDescription": "Enables the check_update command without any pre-configured scope." }, + { + "description": "Enables the connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-connection", + "markdownDescription": "Enables the connection command without any pre-configured scope." + }, { "description": "Enables the dismiss_update command without any pre-configured scope.", "type": "string", @@ -3008,12 +3020,24 @@ "const": "openbot-desktop:allow-restart", "markdownDescription": "Enables the restart command without any pre-configured scope." }, + { + "description": "Enables the set_organization command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-set-organization", + "markdownDescription": "Enables the set_organization command without any pre-configured scope." + }, { "description": "Enables the set_usage_data command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:allow-set-usage-data", "markdownDescription": "Enables the set_usage_data command without any pre-configured scope." }, + { + "description": "Enables the sign_out command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-sign-out", + "markdownDescription": "Enables the sign_out command without any pre-configured scope." + }, { "description": "Enables the speech_abort command without any pre-configured scope.", "type": "string", @@ -3086,12 +3110,24 @@ "const": "openbot-desktop:deny-change-ai-connection", "markdownDescription": "Denies the change_ai_connection command without any pre-configured scope." }, + { + "description": "Denies the change_connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-change-connection", + "markdownDescription": "Denies the change_connection command without any pre-configured scope." + }, { "description": "Denies the check_update command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:deny-check-update", "markdownDescription": "Denies the check_update command without any pre-configured scope." }, + { + "description": "Denies the connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-connection", + "markdownDescription": "Denies the connection command without any pre-configured scope." + }, { "description": "Denies the dismiss_update command without any pre-configured scope.", "type": "string", @@ -3134,12 +3170,24 @@ "const": "openbot-desktop:deny-restart", "markdownDescription": "Denies the restart command without any pre-configured scope." }, + { + "description": "Denies the set_organization command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-set-organization", + "markdownDescription": "Denies the set_organization command without any pre-configured scope." + }, { "description": "Denies the set_usage_data command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:deny-set-usage-data", "markdownDescription": "Denies the set_usage_data command without any pre-configured scope." }, + { + "description": "Denies the sign_out command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-sign-out", + "markdownDescription": "Denies the sign_out command without any pre-configured scope." + }, { "description": "Denies the speech_abort command without any pre-configured scope.", "type": "string", diff --git a/desktop/src-tauri/gen/schemas/macOS-schema.json b/desktop/src-tauri/gen/schemas/macOS-schema.json index 370501d5e6..a1504a7fa4 100644 --- a/desktop/src-tauri/gen/schemas/macOS-schema.json +++ b/desktop/src-tauri/gen/schemas/macOS-schema.json @@ -2960,12 +2960,24 @@ "const": "openbot-desktop:allow-change-ai-connection", "markdownDescription": "Enables the change_ai_connection command without any pre-configured scope." }, + { + "description": "Enables the change_connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-change-connection", + "markdownDescription": "Enables the change_connection command without any pre-configured scope." + }, { "description": "Enables the check_update command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:allow-check-update", "markdownDescription": "Enables the check_update command without any pre-configured scope." }, + { + "description": "Enables the connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-connection", + "markdownDescription": "Enables the connection command without any pre-configured scope." + }, { "description": "Enables the dismiss_update command without any pre-configured scope.", "type": "string", @@ -3008,12 +3020,24 @@ "const": "openbot-desktop:allow-restart", "markdownDescription": "Enables the restart command without any pre-configured scope." }, + { + "description": "Enables the set_organization command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-set-organization", + "markdownDescription": "Enables the set_organization command without any pre-configured scope." + }, { "description": "Enables the set_usage_data command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:allow-set-usage-data", "markdownDescription": "Enables the set_usage_data command without any pre-configured scope." }, + { + "description": "Enables the sign_out command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:allow-sign-out", + "markdownDescription": "Enables the sign_out command without any pre-configured scope." + }, { "description": "Enables the speech_abort command without any pre-configured scope.", "type": "string", @@ -3086,12 +3110,24 @@ "const": "openbot-desktop:deny-change-ai-connection", "markdownDescription": "Denies the change_ai_connection command without any pre-configured scope." }, + { + "description": "Denies the change_connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-change-connection", + "markdownDescription": "Denies the change_connection command without any pre-configured scope." + }, { "description": "Denies the check_update command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:deny-check-update", "markdownDescription": "Denies the check_update command without any pre-configured scope." }, + { + "description": "Denies the connection command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-connection", + "markdownDescription": "Denies the connection command without any pre-configured scope." + }, { "description": "Denies the dismiss_update command without any pre-configured scope.", "type": "string", @@ -3134,12 +3170,24 @@ "const": "openbot-desktop:deny-restart", "markdownDescription": "Denies the restart command without any pre-configured scope." }, + { + "description": "Denies the set_organization command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-set-organization", + "markdownDescription": "Denies the set_organization command without any pre-configured scope." + }, { "description": "Denies the set_usage_data command without any pre-configured scope.", "type": "string", "const": "openbot-desktop:deny-set-usage-data", "markdownDescription": "Denies the set_usage_data command without any pre-configured scope." }, + { + "description": "Denies the sign_out command without any pre-configured scope.", + "type": "string", + "const": "openbot-desktop:deny-sign-out", + "markdownDescription": "Denies the sign_out command without any pre-configured scope." + }, { "description": "Denies the speech_abort command without any pre-configured scope.", "type": "string", diff --git a/desktop/src-tauri/src/connected_ipc_tests.rs b/desktop/src-tauri/src/connected_ipc_tests.rs new file mode 100644 index 0000000000..5f979a4ec8 --- /dev/null +++ b/desktop/src-tauri/src/connected_ipc_tests.rs @@ -0,0 +1,631 @@ +// Included by main.rs: the app connected to an OpenBot that runs elsewhere, through the shell's own +// registered commands, its window rules and its Stop and Quit. The sign-in and the relay themselves +// are tested in the library (`connected`), against an OpenBot stand-in these tests do not have. +mod connected_ipc { + use super::*; + use openbot_desktop_lib::connected::{choice, credentials}; + use std::time::{Duration, Instant}; + + const SETUP: &str = if cfg!(any(windows, target_os = "android")) { + "http://tauri.localhost/" + } else { + "tauri://localhost/" + }; + /// A relay's origin, as `show` trusts it: 127.0.0.1 at a port the system picked. + const RELAY: &str = "http://127.0.0.1:49200"; + const ADDRESS: &str = "https://openbot.example.com"; + + struct Connected { + app: tauri::App, + window: tauri::WebviewWindow, + config: PathBuf, + store: credentials::Store, + } + + impl Connected { + /// The app as it is built, with the page's plugin stood in for under its own name so the + /// ACL that guards the real commands guards these, and a configuration folder and + /// credential store of the test's own. + fn new() -> Self { + let stand_in = + tauri::plugin::Builder::::new(desktop_page::PLUGIN) + .invoke_handler(|invoke| { + invoke.resolver.resolve(()); + true + }) + .build(); + let app = tauri::test::mock_builder() + .plugin(stand_in) + .plugin(tauri_plugin_notification::init()) + .plugin(intelligence_bridge::plugin()) + .manage(Shell::default()) + .invoke_handler(tauri::generate_handler![ + desktop_connected::connection, + desktop_connected::check_openbot_address, + desktop_connected::connect_to_openbot, + desktop_connected::cancel_connect, + desktop_connected::show_connected, + desktop_connected::sign_out_of_openbot, + desktop_connected::use_this_computer, + desktop_connected::take_connection_notice, + ]) + .build(side_by_side(tauri::generate_context!(test = true))) + .unwrap(); + know_app_page_grants(app.handle()); + let window = app.get_webview_window("main").unwrap_or_else(|| { + tauri::WebviewWindowBuilder::new(&app, "main", Default::default()) + .build() + .unwrap() + }); + *app.state::().setup_url.lock().unwrap() = Some(SETUP.into()); + let config = temp_root("openbot-connected-config"); + // keyring's own in-memory store, never the keychain of whoever runs the tests. + let store = credentials::Store::of(keyring_core::mock::Store::new().unwrap()); + desktop_connected::use_for_test(app.handle(), config.clone(), store.clone()); + Self { + app, + window, + config, + store, + } + } + + fn handle(&self) -> &tauri::AppHandle { + self.app.handle() + } + + fn choose(&self, mode: choice::Mode, address: &str, organization: Option<&str>) { + choice::write( + &self.config, + &choice::Choice { + mode, + address: Some(address.into()), + organization_id: organization.map(str::to_owned), + }, + ) + .unwrap(); + } + + fn ask(&self, from: &str, cmd: &str) -> Result { + tauri::test::get_ipc_response( + &self.window, + tauri::webview::InvokeRequest { + cmd: cmd.into(), + callback: tauri::ipc::CallbackFn(0), + error: tauri::ipc::CallbackFn(1), + url: from.parse().unwrap(), + body: tauri::ipc::InvokeBody::Json(serde_json::json!({})), + headers: Default::default(), + invoke_key: tauri::test::INVOKE_KEY.into(), + }, + ) + .map(|body| body.deserialize().unwrap()) + } + + /// What is in the configuration folder, by name. + fn config_files(&self) -> Vec { + let mut names: Vec = std::fs::read_dir(&self.config) + .map(|entries| { + entries + .filter_map(|entry| entry.ok()?.file_name().into_string().ok()) + .collect() + }) + .unwrap_or_default(); + names.sort(); + names + } + } + + impl Drop for Connected { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.config); + } + } + + fn wait_until(what: &str, mut condition: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(10); + while !condition() { + assert!(Instant::now() < deadline, "{what}"); + std::thread::sleep(Duration::from_millis(10)); + } + } + + /// An address nothing answers at: a loopback port that was free a moment ago. + fn nobody_home() -> String { + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + format!("http://127.0.0.1:{port}") + } + + /// The setup window asks where OpenBot runs and drives the connection; no page from anywhere + /// else can, OpenBot's own page through the relay included. + #[test] + fn the_setup_page_may_ask_the_connection_commands_and_no_other_origin_may() { + let shell = Connected::new(); + assert_eq!( + shell.ask(SETUP, "connection"), + Ok(serde_json::json!({ + "mode": "local", + "address": null, + "organizationId": null, + "signedIn": false + })) + ); + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::Value::Null) + ); + assert_eq!( + shell.ask(SETUP, "cancel_connect"), + Ok(serde_json::Value::Null) + ); + + desktop_connected::showing_for_test(shell.handle(), RELAY); + for elsewhere in [ + "http://127.0.0.1:3011/", + "https://openbot.example.com/", + "http://127.0.0.1:49200/settings", + ] { + for command in [ + "connection", + "check_openbot_address", + "connect_to_openbot", + "cancel_connect", + "show_connected", + "sign_out_of_openbot", + "use_this_computer", + "take_connection_notice", + ] { + assert!( + shell.ask(elsewhere, command).is_err(), + "{elsewhere} reached {command}" + ); + } + } + // Registered in the app itself, beside the commands setup already has. + let main = include_str!("main.rs"); + let handler = &main[main.find(".invoke_handler(tauri::generate_handler![").unwrap()..]; + let handler = &handler[..handler.find("])").unwrap()]; + for command in [ + "connection", + "check_openbot_address", + "connect_to_openbot", + "cancel_connect", + "show_connected", + "sign_out_of_openbot", + "use_this_computer", + "take_connection_notice", + ] { + assert!( + handler.contains(&format!("desktop_connected::{command},")), + "{command} is not registered" + ); + } + } + + /// OpenBot's page, served through the relay, may ask where it runs, sign out, change the + /// connection and name the organisation. A page on another loopback port may not. + #[test] + fn the_relays_page_may_ask_the_page_calls_and_another_loopback_port_may_not() { + let shell = Connected::new(); + let calls = [ + "plugin:openbot-desktop|connection", + "plugin:openbot-desktop|sign_out", + "plugin:openbot-desktop|change_connection", + "plugin:openbot-desktop|set_organization", + ]; + let page = "http://127.0.0.1:49200/settings/computer"; + // Before the relay is up and trusted, nothing at that address reaches them. + for call in calls { + assert!(shell.ask(page, call).is_err(), "{call}"); + } + desktop_connected::showing_for_test(shell.handle(), RELAY); + for call in calls { + assert_eq!(shell.ask(page, call), Ok(serde_json::Value::Null), "{call}"); + for other in [ + "http://127.0.0.1:49201/", + "http://localhost:49200/", + "http://[::1]:49200/", + "https://openbot.example.com/", + ] { + assert!(shell.ask(other, call).is_err(), "{other} reached {call}"); + } + } + // And each is one of the plugin's own commands, built with a permission of its own. + let build = include_str!("../build.rs"); + let page_source = include_str!("desktop_page.rs"); + for command in ["connection", "sign_out", "change_connection", "set_organization"] { + assert!(build.contains(&format!("\"{command}\",")), "{command}"); + assert!( + page_source.contains(&format!("async fn {command}(")), + "{command}" + ); + assert!(desktop_page::PERMISSIONS.contains( + &format!("openbot-desktop:allow-{}", command.replace('_', "-")).as_str() + )); + } + } + + /// The relay's page is OpenBot's own page to the window: the overlay title bar and everything + /// that goes with it. A link from it to anywhere outside, the typed address itself included, + /// is the person's browser's to open: it is not loaded in the window or sent through the relay. + #[test] + fn the_relays_page_is_openbots_own_and_a_link_to_the_typed_address_leaves_for_the_browser() { + let shell = Connected::new(); + shell.choose(choice::Mode::Connected, ADDRESS, None); + let page: tauri::Url = "http://127.0.0.1:49200/channel/c-1".parse().unwrap(); + assert_eq!(window_page(shell.handle(), &page), WindowPage::Other); + desktop_connected::showing_for_test(shell.handle(), RELAY); + assert_eq!(window_page(shell.handle(), &page), WindowPage::OwnedApp); + assert!(is_owned_app_origin(shell.handle(), &page)); + assert_eq!( + window_page( + shell.handle(), + &"http://127.0.0.1:49201/channel/c-1".parse().unwrap() + ), + WindowPage::Other + ); + // The relay's own pages stay in the window. + assert!(!outside_links::leaves(&page)); + // The OpenBot it is connected to, by its own address, is a site outside the window. + let typed: tauri::Url = format!("{ADDRESS}/settings/api-keys").parse().unwrap(); + assert!(outside_links::leaves(&typed)); + assert!(!outside_links::loads_in_a_frame(&typed)); + let mut opened = Vec::new(); + outside_links::new_window(&typed, |to| opened.push(to.to_owned())); + assert_eq!(opened, [typed.as_str()]); + // The window's guard hands a site that leaves, from one of OpenBot's own pages, to the + // browser and refuses the navigation. Read as text: the real webview cannot be built here. + let main = include_str!("main.rs"); + let guard = &main[main.find("fn outside_links_guard").unwrap()..]; + let guard = &guard[..guard.find("\n}\n").unwrap()]; + assert!(guard.contains("window_page(webview.app_handle(), ¤t)")); + assert!(guard.contains("WindowPage::OwnedApp | WindowPage::LocalApp")); + assert!(guard.contains(".open_url(destination.as_str(), None::<&str>);\n false")); + } + + /// With the choice on record saying connected, nothing of an installation on this computer is + /// asked, read or made: not by the page's status, Restart or Stop, not by Show, not by Quit. + /// The installation's folder is a path that does not exist and must still not exist after, + /// and the only engine on the PATH records every command it is given. + #[test] + fn connected_launch_status_and_quit_never_touch_the_local_installation() { + if crate::test_support::isolated_process( + "tests::connected_ipc::connected_launch_status_and_quit_never_touch_the_local_installation", + ) { + return; + } + let path = SerializedPath::set_only_with("docker", "stop-ipc"); + let base = temp_root("openbot-connected-local"); + std::fs::create_dir_all(&base).unwrap(); + let record = base.join("commands.log"); + std::env::set_var("OPENBOT_TEST_ENGINE_RECORD", &record); + let root = base.join("OpenBot"); + let asked_the_engine = || record.exists(); + + // On this computer, as before: the same status question asks the engine. + let local = Connected::new(); + let local_root = base.join("OpenBot on this computer"); + remember_selected_root(&local.app.state::(), &local_root); + let status = tauri::async_runtime::block_on(desktop_status(local.handle().clone(), None)) + .unwrap(); + assert_eq!( + serde_json::to_value(&status).unwrap()["root"], + local_root.display().to_string() + ); + assert!(asked_the_engine(), "a local status asks the engine"); + std::fs::remove_file(&record).unwrap(); + drop(local); + + let shell = Connected::new(); + shell.choose(choice::Mode::Connected, ADDRESS, Some("org_1")); + remember_selected_root(&shell.app.state::(), &root); + assert!(desktop_connected::is_connected(shell.handle())); + + // The page's status: the app's own facts, and nothing of an OpenBot here. + let status = tauri::async_runtime::block_on(desktop_status(shell.handle().clone(), None)) + .unwrap(); + let status = serde_json::to_value(&status).unwrap(); + assert_eq!(status["openbotRunning"], false); + assert_eq!(status["openbotHeld"], false); + assert_eq!(status["processes"], serde_json::json!([])); + assert_eq!(status["containers"], serde_json::json!([])); + assert_eq!(status["intelligenceStack"], serde_json::Value::Null); + assert_eq!(status["intelligenceContainers"], serde_json::json!([])); + assert_eq!(status["engine"], serde_json::Value::Null); + assert_eq!(status["root"], ""); + assert_eq!(status["appPort"], serde_json::Value::Null); + assert_eq!(status["version"], desktop_version(shell.handle())); + assert!(status["build"].as_str().unwrap().starts_with("Built ")); + assert_eq!( + status["logFolder"], + logging::folder(shell.handle()).unwrap().display().to_string() + ); + + // What is about this computer's own OpenBot is refused, in the agreed words. + let refused = "This app is connected to an OpenBot that runs somewhere else, so there's nothing to do here on this computer."; + assert_eq!( + tauri::async_runtime::block_on(desktop_page::restart(shell.handle().clone())), + Err(refused.to_owned()) + ); + assert_eq!( + tauri::async_runtime::block_on(desktop_page::stop(shell.handle().clone())), + Err(refused.to_owned()) + ); + let shown = tauri::async_runtime::block_on(show_openbot(shell.handle().clone())) + .expect_err("there is no OpenBot here to show"); + assert_eq!(shown.said, refused); + assert_eq!( + desktop_connected::local_only(shell.handle()).unwrap_err().said, + refused + ); + + // The page is told where it runs, and the window still knows its own pages. + assert_eq!( + serde_json::to_value(desktop_connected::connection_now(shell.handle(), false)).unwrap(), + serde_json::json!({ + "mode": "connected", + "address": ADDRESS, + "organizationId": "org_1" + }) + ); + desktop_connected::showing_for_test(shell.handle(), RELAY); + assert_eq!( + window_page(shell.handle(), &"http://127.0.0.1:49200/".parse().unwrap()), + WindowPage::OwnedApp + ); + + // Quit: nothing to stop, so no Shutting down screen and no failures. + let showing = shell.window.url().unwrap(); + assert_eq!(quit_cleanup_shown(shell.handle()), Vec::::new()); + assert_eq!(quit_status(shell.handle().clone()), None); + assert_eq!(shell.window.url().unwrap(), showing); + + assert!(!asked_the_engine(), "{:?}", std::fs::read_to_string(&record)); + assert!(!root.exists(), "the installation's folder was made"); + assert_eq!(shell.config_files(), ["connection.json"]); + drop(shell); + let _ = std::fs::remove_dir_all(&base); + let _ = std::fs::remove_dir_all(path.bin()); + } + + /// The organisation picked in the app is kept beside the address, told back to the page, and + /// gone at sign-out. Sign-out forgets the saved sign-in and keeps the address; back on this + /// computer the choice is local, with the address still remembered for another time. + #[test] + fn the_organisation_is_kept_then_cleared_at_sign_out_and_the_address_stays() { + let _ports = crate::test_support::hold_ports(); + let shell = Connected::new(); + let address = nobody_home(); + // On this computer there is no organisation to name. + assert!(desktop_connected::set_organization_now(shell.handle(), Some("org_1".into())) + .is_err()); + assert_eq!(shell.config_files(), Vec::::new()); + + shell.choose(choice::Mode::Connected, &address, None); + // Built at run time, so no token-shaped literal sits in the source. + let saved = format!("obr_{}", "Kq7m".repeat(8)); + shell.store.set(&address, &saved).unwrap(); + desktop_connected::set_organization_now(shell.handle(), Some("org_A1-b".into())).unwrap(); + assert_eq!( + choice::read(&shell.config).organization_id.as_deref(), + Some("org_A1-b") + ); + for bad in ["", "two words", "../etc", "org\r\nX-Injected: 1"] { + assert!( + desktop_connected::set_organization_now(shell.handle(), Some(bad.into())).is_err(), + "{bad:?}" + ); + } + assert_eq!( + choice::read(&shell.config).organization_id.as_deref(), + Some("org_A1-b"), + "a refused id changes nothing" + ); + assert_eq!( + serde_json::to_value(desktop_connected::connection_now(shell.handle(), true)).unwrap(), + serde_json::json!({ + "mode": "connected", + "address": address, + "organizationId": "org_A1-b", + "signedIn": true + }) + ); + + desktop_connected::sign_out_now(shell.handle()); + assert_eq!(shell.store.get(&address).unwrap(), None); + assert_eq!( + serde_json::to_value(desktop_connected::connection_now(shell.handle(), true)).unwrap(), + serde_json::json!({ + "mode": "connected", + "address": address, + "organizationId": null, + "signedIn": false + }) + ); + + // Back to OpenBot on this computer, from the setup window. + desktop_connected::set_organization_now(shell.handle(), Some("org_2".into())).unwrap(); + tauri::async_runtime::block_on(desktop_connected::use_this_computer( + shell.handle().clone(), + )) + .unwrap(); + assert!(!desktop_connected::is_connected(shell.handle())); + let kept = choice::read(&shell.config); + assert_eq!(kept.mode, choice::Mode::Local); + assert_eq!(kept.address.as_deref(), Some(address.as_str())); + assert_eq!(kept.organization_id, None); + assert_eq!(shell.window.url().unwrap().as_str(), SETUP); + // OpenBot's page on this computer is told local, and no address. + assert_eq!( + serde_json::to_value(desktop_connected::connection_now(shell.handle(), false)).unwrap(), + serde_json::json!({ "mode": "local", "address": null, "organizationId": null }) + ); + // Nothing token-shaped was ever written beside the choice. + assert_eq!(shell.config_files(), ["connection.json"]); + let written = std::fs::read_to_string(shell.config.join("connection.json")).unwrap(); + assert!(!written.contains("obr_") && !written.contains("oba_"), "{written}"); + } + + /// The sign-in ended while OpenBot was showing: the setup window is back, it is told so once + /// in the agreed words, and the event went out for a page that was listening. + #[test] + fn an_ended_session_puts_setup_back_and_keeps_its_sentence_for_it_once() { + use tauri::Listener; + let shell = Connected::new(); + shell.choose(choice::Mode::Connected, ADDRESS, None); + let (heard, events) = std::sync::mpsc::channel(); + shell.app.listen(desktop_connected::ENDED_EVENT, move |event| { + let _ = heard.send(event.payload().to_owned()); + }); + + desktop_connected::session_ended(shell.handle(), "openbot.example.com"); + + assert_eq!(shell.window.url().unwrap().as_str(), SETUP); + let said = serde_json::json!({ + "kind": "session-ended", + "message": "Your sign-in to openbot.example.com has ended. Sign in again to keep going." + }); + let event: serde_json::Value = + serde_json::from_str(&events.recv_timeout(Duration::from_secs(5)).unwrap()).unwrap(); + assert_eq!(event, said); + assert_eq!(shell.ask(SETUP, "take_connection_notice"), Ok(said)); + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::Value::Null) + ); + // Still the choice: setup shows the connect screen with the address filled in. + assert_eq!(choice::read(&shell.config).connected_to(), Some(ADDRESS)); + } + + /// Settings' Change, while connected: signed out, still connected to the address, and setup + /// told once to open at the choice. + #[test] + fn change_connection_while_connected_signs_out_and_asks_setup_to_choose() { + let _ports = crate::test_support::hold_ports(); + let shell = Connected::new(); + let address = nobody_home(); + shell.choose(choice::Mode::Connected, &address, Some("org_1")); + shell + .store + .set(&address, &format!("obr_{}", "Zt4w".repeat(8))) + .unwrap(); + + desktop_connected::change_connection_now(shell.handle()).unwrap(); + + assert_eq!(shell.store.get(&address).unwrap(), None); + assert_eq!(shell.window.url().unwrap().as_str(), SETUP); + let kept = choice::read(&shell.config); + assert_eq!(kept.connected_to(), Some(address.as_str())); + assert_eq!(kept.organization_id, None); + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::json!({ "kind": "choose", "message": null })) + ); + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::Value::Null) + ); + } + + /// Settings' Change, while OpenBot runs on this computer: OpenBot is stopped exactly as + /// Settings' Stop stops it, setup comes back told once to open at the choice, and the choice + /// on record is not changed by asking. + #[test] + fn change_connection_on_this_computer_stops_openbot_and_asks_setup_to_choose() { + if crate::test_support::isolated_process( + "tests::connected_ipc::change_connection_on_this_computer_stops_openbot_and_asks_setup_to_choose", + ) { + return; + } + let path = SerializedPath::set_only_with("docker", "stop-ipc"); + let root = temp_root("openbot-connected-change"); + std::fs::create_dir_all(root.join(".logs")).unwrap(); + std::fs::write(root.join("docker-compose.yml"), "services: {}\n").unwrap(); + let record = root.join("commands.log"); + std::env::set_var("OPENBOT_TEST_ENGINE_RECORD", &record); + let shell = Connected::new(); + *shell.app.state::().root.lock().unwrap() = Some(root.clone()); + *shell.app.state::().containers.lock().unwrap() = Some(ContainerDeployment { + root: root.clone(), + address: engine::Address::new(engine::Engine::Docker, None), + }); + // Compose down waits here, so the test sees what is true before it finishes. + let compose = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + std::fs::write( + root.join("stop-barrier-address"), + compose.local_addr().unwrap().to_string(), + ) + .unwrap(); + + desktop_connected::change_connection_now(shell.handle()).unwrap(); + let (mut stopping, _) = compose.accept().unwrap(); + // Not asked to choose until OpenBot has stopped. + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::Value::Null) + ); + stopping.write_all(&[0]).unwrap(); + + wait_until("setup came back", || { + shell.window.url().unwrap().as_str() == SETUP + }); + assert_compose_down_ran_under(&record, &root); + assert!(shell.app.state::().root.lock().unwrap().is_none()); + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::json!({ "kind": "choose", "message": null })) + ); + assert_eq!( + shell.ask(SETUP, "take_connection_notice"), + Ok(serde_json::Value::Null) + ); + // The choice is not changed by asking: still none on record, so still this computer. + assert_eq!(shell.config_files(), Vec::::new()); + assert!(!desktop_connected::is_connected(shell.handle())); + assert!(last_failure_now(shell.handle()).is_none()); + drop(shell); + let _ = std::fs::remove_dir_all(&root); + let _ = std::fs::remove_dir_all(path.bin()); + } + + /// The menus of a connected app carry Show Window, the app's log folder, Sign Out and Quit, and + /// nothing that starts, stops or reports on an OpenBot on this computer. Read as text, as the + /// other menu tests are: AppKit's menus cannot be built here. + #[test] + fn a_connected_apps_menus_offer_sign_out_and_the_log_folder_and_no_status() { + let main = include_str!("main.rs"); + let at = |pieces: &[&str]| main.find(&pieces.concat()).unwrap(); + let menus = &main[at(&["\nfn install", "_menus"])..]; + let menus = &menus[..menus.find("app.set_menu(").unwrap()]; + for entries in ["let tray_entries = ", "let window_entries = "] { + // From where the menu starts to where a connected app's menu is handed back. + let built = &menus[menus.find(entries).unwrap()..]; + let connected = &built[..built.find("return Ok(entries);").unwrap()]; + assert!(connected.contains("if connected {"), "{entries}"); + for carried in [ + "\"Show Window\"", + "CONNECTED_LOG_FOLDER_MENU_ID", + "CONNECTED_SIGN_OUT_MENU_ID", + "\"quit\"", + ] { + assert!(connected.contains(carried), "{entries} lacks {carried}"); + } + for absent in ["\"status\"", "\"logs\"", "\"state\"", "\"stop\""] { + assert!(!connected.contains(absent), "{entries} carries {absent}"); + } + } + assert_eq!(CONNECTED_SIGN_OUT_MENU_LABEL, "Sign Out"); + assert_eq!(CONNECTED_LOG_FOLDER_MENU_LABEL, "Open Log Folder"); + let chosen = &main[at(&["\nfn cho", "se(app"])..]; + let chosen = &chosen[..chosen.find("\n}\n").unwrap()]; + assert!(chosen.contains( + "CONNECTED_SIGN_OUT_MENU_ID => desktop_connected::sign_out_from_menu(app.clone())," + )); + assert!(chosen + .contains("\"stop\" | \"status\" | \"logs\" if desktop_connected::is_connected(app) => {}")); + } +} diff --git a/desktop/src-tauri/src/desktop_connected.rs b/desktop/src-tauri/src/desktop_connected.rs new file mode 100644 index 0000000000..d430d24015 --- /dev/null +++ b/desktop/src-tauri/src/desktop_connected.rs @@ -0,0 +1,617 @@ +/*! +The app connected to an OpenBot that runs somewhere else: what the setup window and OpenBot's own +page may ask, and what the window, the menus and Quit do differently while it is. + +The work is in `openbot_desktop_lib::connected`. This is the wiring: the choice read from +`connection.json`, the sign-in started and cancelled, the relay started and stopped with the window +pointed at it, and the sentence kept for the setup window when a sign-in ends. + +While the choice is to be connected, nothing of an installation on this computer is started, read +or written: `is_connected` is what every such path asks first. +*/ + +use crate::{Problem, Shell}; +use openbot_desktop_lib::connected::{address, choice, credentials, relay, sign_in, Kind}; +use serde::Serialize; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use tauri::{Emitter, Manager}; + +/// What a page that asks for something of this computer's own OpenBot is told while connected. +pub const NOTHING_HERE: &str = "This app is connected to an OpenBot that runs somewhere else, so \ + there's nothing to do here on this computer."; + +/// Told to the setup window while OpenBot shows in connected mode: `{ kind, message }`. +pub const ENDED_EVENT: &str = "connection-ended"; + +/// The connection this session holds, and what the setup window is to be told next. +#[derive(Default)] +pub struct State { + /// The relay the window shows OpenBot through, and its sign-in. None while not showing. + live: Mutex>, + /// A sign-in waiting for the browser, for Cancel. + attempt: Mutex>>, + /// Kept for the setup page that has not loaded yet, and given once (`take_connection_notice`). + notice: Mutex>, + /// In place of the app's configuration folder, in a test. + config_dir: Mutex>, + /// In place of the system's credential store, in a test. + store: Mutex>, + /// The origin of a relay taken to be showing, in a test of the window's own rules: a real one + /// needs an OpenBot to sign in to, which the library's tests have and these do not. + #[cfg(test)] + relay_for_test: Mutex>, +} + +struct Live { + relay: relay::Relay, + session: Arc, +} + +/// What the setup window shows when it loads after a connection ended, or after Settings asked to +/// change it (`choose`, with no sentence). +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct Notice { + pub kind: &'static str, + pub message: Option, +} + +/// The choice, as the setup window and OpenBot's page are told it. +#[derive(Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + pub mode: choice::Mode, + pub address: Option, + pub organization_id: Option, + /// Whether a sign-in for that address is in the credential store. Only the setup window asks. + #[serde(skip_serializing_if = "Option::is_none")] + pub signed_in: Option, +} + +fn state(app: &tauri::AppHandle) -> tauri::State<'_, Shell> { + app.state::() +} + +fn config_dir(app: &tauri::AppHandle) -> Option { + let given = state(app).connected.config_dir.lock().unwrap().clone(); + // A test never reads the choice of whoever runs it: only the folder it was given. + if cfg!(test) { + return given; + } + given.or_else(|| app.path().app_config_dir().ok()) +} + +fn store(app: &tauri::AppHandle) -> credentials::Store { + let given = state(app).connected.store.lock().unwrap().clone(); + given.unwrap_or_else(credentials::Store::system) +} + +/// The person's choice on record: on this computer unless `connection.json` says otherwise. +pub fn chosen(app: &tauri::AppHandle) -> choice::Choice { + config_dir(app) + .map(|dir| choice::read(&dir)) + .unwrap_or_default() +} + +fn keep( + app: &tauri::AppHandle, + chosen: &choice::Choice, +) -> Result<(), Problem> { + let written = config_dir(app) + .ok_or_else(|| "the app has no configuration folder".to_owned()) + .and_then(|dir| choice::write(&dir, chosen).map_err(|error| error.to_string())); + written.map_err(|detail| { + Problem::with( + "OpenBot couldn't save your choice on this computer. Try again.", + detail, + ) + }) +} + +/// Whether the app is connected to an OpenBot that runs elsewhere: it shows one now, or the choice +/// on record is to. Then nothing of this computer's own installation is touched. +pub fn is_connected(app: &tauri::AppHandle) -> bool { + state(app).connected.live.lock().unwrap().is_some() + || chosen(app).mode == choice::Mode::Connected +} + +/// The relay's origin, `http://127.0.0.1:`, while the window shows OpenBot through it. +pub fn relay_origin(app: &tauri::AppHandle) -> Option { + #[cfg(test)] + if let Some(origin) = state(app).connected.relay_for_test.lock().unwrap().clone() { + return Some(origin); + } + state(app) + .connected + .live + .lock() + .unwrap() + .as_ref() + .map(|live| live.relay.origin()) +} + +/// Whether `url` is a page the relay serves: OpenBot's own, from the OpenBot it is connected to. +pub fn is_relay_page(app: &tauri::AppHandle, url: &tauri::Url) -> bool { + relay_origin(app).is_some_and(|origin| origin == url.origin().ascii_serialization()) +} + +/// Refuse something that is about this computer's own OpenBot, while connected to another. +pub fn nothing_here(app: &tauri::AppHandle) -> Result<(), String> { + if is_connected(app) { + Err(NOTHING_HERE.into()) + } else { + Ok(()) + } +} + +/// The same refusal, for the setup window's commands that start or install something here. +pub fn local_only(app: &tauri::AppHandle) -> Result<(), Problem> { + nothing_here(app).map_err(Problem::plain) +} + +pub fn connection_now(app: &tauri::AppHandle, for_setup: bool) -> Connection { + let chosen = chosen(app); + let connected = chosen.mode == choice::Mode::Connected; + let signed_in = for_setup.then(|| { + chosen.connected_to().is_some_and(|address| { + state(app).connected.live.lock().unwrap().is_some() + || store(app).get(address).is_ok_and(|saved| saved.is_some()) + }) + }); + Connection { + mode: chosen.mode, + // The setup window is given a remembered address to offer again; OpenBot's page is told + // of one only while connected to it. + address: chosen.address.filter(|_| connected || for_setup), + organization_id: chosen.organization_id.filter(|_| connected), + signed_in, + } +} + +/// The setup window's first question: which of the two, where, and whether it is signed in. +#[tauri::command] +pub async fn connection(app: tauri::AppHandle) -> Connection { + tauri::async_runtime::spawn_blocking(move || connection_now(&app, true)) + .await + .unwrap_or(Connection { + mode: choice::Mode::Local, + address: None, + organization_id: None, + signed_in: Some(false), + }) +} + +#[derive(Serialize)] +pub struct Checked { + address: String, +} + +/// Whether there is an OpenBot this app can connect to at `address`, and the address as kept. +#[tauri::command] +pub async fn check_openbot_address(address: String) -> Result { + let asked = std::time::Instant::now(); + let checked = + blocking(move || address::check(&address).map(|(address, _)| Checked { address })).await; + openbot_desktop_lib::logging::outcome("connect check", asked, &checked); + checked +} + +/// Connect: check the address, sign in through the browser, start the relay and show OpenBot. +/// The choice is kept only once all of that has worked. +#[tauri::command] +pub async fn connect_to_openbot( + app: tauri::AppHandle, + address: String, +) -> Result<(), Problem> { + let asked = std::time::Instant::now(); + log::info!("[connect] asked"); + let connected = blocking(move || connect_now(&app, &address)).await; + openbot_desktop_lib::logging::outcome("connect", asked, &connected); + connected +} + +/// Stop a sign-in that is waiting for the browser. +#[tauri::command] +pub async fn cancel_connect(app: tauri::AppHandle) { + if let Some(attempt) = state(&app).connected.attempt.lock().unwrap().as_ref() { + attempt.cancel(); + } +} + +/// At launch, connected and signed in: the saved sign-in made current, the relay started, and the +/// window on OpenBot. `session-ended` when the saved sign-in no longer works. +#[tauri::command] +pub async fn show_connected(app: tauri::AppHandle) -> Result<(), Problem> { + let asked = std::time::Instant::now(); + log::info!("[connect] asked to show the connected OpenBot"); + let shown = blocking(move || show_connected_now(&app)).await; + openbot_desktop_lib::logging::outcome("connect show", asked, &shown); + shown +} + +/// Sign out, and the setup window. The address stays remembered. +#[tauri::command] +pub async fn sign_out_of_openbot( + app: tauri::AppHandle, +) -> Result<(), Problem> { + blocking(move || { + sign_out_now(&app); + crate::show_setup(app).map_err(Problem::from) + }) + .await +} + +/// Back to OpenBot on this computer: signed out, the choice switched, and the setup window, which +/// carries on as it does for an installation here. +#[tauri::command] +pub async fn use_this_computer(app: tauri::AppHandle) -> Result<(), Problem> { + blocking(move || { + sign_out_now(&app); + let mut chosen = chosen(&app); + chosen.mode = choice::Mode::Local; + chosen.organization_id = None; + keep(&app, &chosen)?; + log::info!("[connect] the choice is OpenBot on this computer"); + crate::refresh_menus(&app); + crate::show_setup(app).map_err(Problem::from) + }) + .await +} + +/// What the setup window is to show after a connection ended or was asked to change. Once. +#[tauri::command] +pub async fn take_connection_notice(app: tauri::AppHandle) -> Option { + state(&app).connected.notice.lock().unwrap().take() +} + +/// The setup window's next `take_connection_notice` says to open at the choice of where OpenBot +/// runs, showing no failure. +pub fn ask_to_choose(app: &tauri::AppHandle) { + *state(app).connected.notice.lock().unwrap() = Some(Notice { + kind: "choose", + message: None, + }); +} + +/// Settings' Change on where OpenBot runs, and the setup window at that choice. +/// +/// Connected: signed out, still connected to the address on record. On this computer: OpenBot +/// stopped, exactly as Settings' Stop stops it, and the choice on record left as it is. +pub fn change_connection_now(app: &tauri::AppHandle) -> Result<(), String> { + if !is_connected(app) { + crate::change_connection_from_settings(app.clone()); + return Ok(()); + } + sign_out_now(app); + ask_to_choose(app); + crate::show_setup(app.clone()) +} + +/// The organisation the person picked in OpenBot's switcher, kept beside the address and named by +/// the relay on every request from now on. None clears it. +pub fn set_organization_now( + app: &tauri::AppHandle, + organization_id: Option, +) -> Result<(), String> { + if let Some(id) = &organization_id { + if !choice::valid_organization(id) { + return Err("That isn't an organization OpenBot knows.".into()); + } + } + let mut chosen = chosen(app); + if chosen.connected_to().is_none() { + return Err("OpenBot isn't connected to an address.".into()); + } + chosen.organization_id = organization_id; + keep(app, &chosen).map_err(|problem| problem.said)?; + if let Some(live) = state(app).connected.live.lock().unwrap().as_ref() { + live.relay + .set_organization(chosen.organization_id.as_deref()); + } + Ok(()) +} + +async fn blocking( + work: impl FnOnce() -> Result + Send + 'static, +) -> Result { + tauri::async_runtime::spawn_blocking(work) + .await + .map_err(|error| Problem::with("OpenBot couldn't do that. Try again.", error.to_string())) + .and_then(|done| done) +} + +fn connect_now(app: &tauri::AppHandle, typed: &str) -> Result<(), Problem> { + let (address, metadata) = address::check(typed)?; + let attempt = Arc::new(sign_in::Attempt::default()); + if let Some(earlier) = state(app) + .connected + .attempt + .lock() + .unwrap() + .replace(attempt.clone()) + { + earlier.cancel(); + } + let signed_in = sign_in::sign_in( + &address, + &metadata, + store(app), + &attempt, + sign_in::WAIT, + // The person's own browser, where they are signed in to their accounts. + |authorize| { + tauri_plugin_opener::open_url(authorize, None::<&str>) + .map_err(|error| error.to_string()) + }, + ); + { + let shell = state(app); + let mut waiting = shell.connected.attempt.lock().unwrap(); + if waiting + .as_ref() + .is_some_and(|waiting| Arc::ptr_eq(waiting, &attempt)) + { + *waiting = None; + } + } + let session = Arc::new(signed_in?); + + // An OpenBot running on this computer is stopped first, as Stop stops it. + if let Err(problem) = stop_local_first(app) { + let _ = session.sign_out(); + return Err(problem); + } + let earlier = chosen(app); + let chosen = choice::Choice { + mode: choice::Mode::Connected, + // An organisation belongs to the OpenBot it was picked at. + organization_id: earlier + .organization_id + .filter(|_| earlier.address.as_deref() == Some(address.as_str())), + address: Some(address), + }; + let shown = show(app, session.clone(), chosen.organization_id.as_deref()) + .and_then(|()| keep(app, &chosen)); + if shown.is_err() { + stop_relay(app); + let _ = session.sign_out(); + } + shown +} + +fn show_connected_now(app: &tauri::AppHandle) -> Result<(), Problem> { + // Already showing in this session: the window goes back to it. + if let Some(origin) = relay_origin(app) { + return navigate(app, &origin); + } + let chosen = chosen(app); + let Some(address) = chosen.connected_to() else { + return Err(Problem::plain( + "OpenBot isn't connected to an address. Choose where OpenBot runs.", + )); + }; + let metadata = address::probe(address)?; + let session = sign_in::resume(address, &metadata, store(app))?; + show(app, Arc::new(session), chosen.organization_id.as_deref()) +} + +/// Start the relay for `session` and point the window at it. +fn show( + app: &tauri::AppHandle, + session: Arc, + organization: Option<&str>, +) -> Result<(), Problem> { + let host = session.host().to_owned(); + let listening = app.clone(); + let listening_host = host.clone(); + let relay = relay::Relay::start(session.clone(), organization, move |why| match why { + relay::Ended::SessionEnded => session_ended(&listening, &listening_host), + relay::Ended::Unreachable => { + let _ = listening.emit( + ENDED_EVENT, + Notice { + kind: Kind::Unreachable.id(), + message: Some(Kind::Unreachable.said(&listening_host)), + }, + ); + } + }) + .map_err(|detail| { + Problem::with( + "OpenBot couldn't open its connection on this computer. Try again.", + detail, + ) + })?; + let origin = relay.origin(); + let entry = relay.entry(); + stop_relay(app); + *state(app).connected.live.lock().unwrap() = Some(Live { relay, session }); + // The relay's pages are OpenBot's own: the window's controls, theme, notifications and the + // rest, exactly as for an OpenBot this computer runs. + crate::trust_owned_app(app, &origin); + crate::refresh_menus(app); + log::info!("[connect] showing the OpenBot at {host}"); + // First to the relay's entry, which gives the window this run's cookie and sends it on. + navigate(app, &entry)?; + crate::bring_to_front(app, "OpenBot is showing"); + Ok(()) +} + +fn navigate(app: &tauri::AppHandle, to: &str) -> Result<(), Problem> { + let window = app + .get_webview_window("main") + .ok_or("the OpenBot window is not there to show it in")?; + let destination: tauri::Url = to + .parse() + .map_err(|_| Problem::plain("OpenBot could not navigate to its app."))?; + window + .navigate(destination) + .map_err(|_| Problem::plain("OpenBot could not navigate to its app.")) +} + +/// Stop the relay, if one runs. The sign-in is left as it is. +pub fn stop_relay(app: &tauri::AppHandle) { + let live = state(app).connected.live.lock().unwrap().take(); + if let Some(live) = live { + forget_origin(app, &live.relay.origin()); + drop(live); + } +} + +/// A relay that has stopped is no longer OpenBot's page: its port is anybody's again. +fn forget_origin(app: &tauri::AppHandle, origin: &str) { + state(app) + .owned_app_origins + .lock() + .unwrap() + .retain(|trusted| trusted != origin); +} + +/// Sign out of the OpenBot on record: revoked there as far as it answers, forgotten here, the +/// relay stopped, and the organisation picked there cleared. The address stays. +pub fn sign_out_now(app: &tauri::AppHandle) { + if let Some(attempt) = state(app).connected.attempt.lock().unwrap().take() { + attempt.cancel(); + } + let live = state(app).connected.live.lock().unwrap().take(); + let mut chosen = chosen(app); + match live { + Some(live) => { + forget_origin(app, &live.relay.origin()); + if let Err(problem) = live.session.sign_out() { + log::warn!( + "[connect] could not forget the sign-in: {}", + problem.detail.unwrap_or(problem.said) + ); + } + } + None => { + if let Some(address) = chosen.connected_to() { + let metadata = address::probe(address).ok(); + if let Err(problem) = + sign_in::sign_out_saved(address, metadata.as_ref(), &store(app)) + { + log::warn!( + "[connect] could not forget the sign-in: {}", + problem.detail.unwrap_or(problem.said) + ); + } + } + } + } + if chosen.organization_id.take().is_some() { + if let Err(problem) = keep(app, &chosen) { + log::warn!( + "[connect] could not clear the organization: {}", + problem.detail.unwrap_or(problem.said) + ); + } + } + crate::refresh_menus(app); +} + +/// The relay said the sign-in is over: it is stopped, the setup window comes back, and the +/// sentence waits for it. +pub(crate) fn session_ended(app: &tauri::AppHandle, host: &str) { + stop_relay(app); + let notice = Notice { + kind: Kind::SessionEnded.id(), + message: Some(Kind::SessionEnded.said(host)), + }; + *state(app).connected.notice.lock().unwrap() = Some(notice.clone()); + crate::refresh_menus(app); + if let Err(error) = crate::show_setup(app.clone()) { + log::warn!("[connect] could not show setup after the sign-in ended: {error}"); + } + let _ = app.emit(ENDED_EVENT, notice); +} + +/// An OpenBot running on this computer when the person connects to another: stopped, the way Stop +/// stops it, before the app is connected. One that is not running is left exactly as it is. +fn stop_local_first(app: &tauri::AppHandle) -> Result<(), Problem> { + let shell = state(app); + let held = shell.root.lock().unwrap().is_some() || shell.containers.lock().unwrap().is_some(); + let root = crate::cleanup_root(&shell, &openbot_desktop_lib::stack::default_root()); + let running = held + || (openbot_desktop_lib::deployment::installed(&root).is_some() + && crate::already_running_now(app, &root.to_string_lossy())); + if !running { + return Ok(()); + } + log::info!("[connect] stopping OpenBot on this computer first"); + crate::stop_everything(app, &root) + .into_result() + .map_err(|detail| { + Problem::with( + "OpenBot on this computer couldn't finish stopping, so the app didn't connect. \ + Try again.", + detail, + ) + }) +} + +/// Show Window, from the tray or a second launch, while connected: OpenBot through the relay when +/// it is showing, and the setup window otherwise, which signs in or shows why it can't. +pub fn show_window(app: &tauri::AppHandle) { + let Some(window) = app.get_webview_window("main") else { + return; + }; + let current = window.url().ok(); + let destination = match relay_origin(app) { + Some(origin) => origin.parse::().ok(), + None => crate::setup_destination(app).ok(), + }; + if let Some(destination) = destination { + let already_showing = current + .as_ref() + .is_some_and(|current| crate::same_window_app(current, &destination)); + if !already_showing { + let _ = window.navigate(destination); + } + } + let _ = window.show(); + let _ = window.unminimize(); + crate::focus(&window, "OpenBot is showing"); +} + +/// What `status` answers OpenBot's page while connected: the app's own version, build and log +/// folder, and nothing of this computer's own OpenBot, which is not asked. +pub fn status(app: &tauri::AppHandle) -> crate::DesktopStatus { + crate::DesktopStatus::of_the_app_alone(app) +} + +/// Quit while connected: only the relay stops. Nothing on this computer runs because of it. +pub fn quit(app: &tauri::AppHandle) { + if let Some(attempt) = state(app).connected.attempt.lock().unwrap().take() { + attempt.cancel(); + } + stop_relay(app); + log::info!("[quit] connected to an OpenBot that runs elsewhere; nothing to stop here"); +} + +/// Sign Out in the tray and the window menu. +pub fn sign_out_from_menu(app: tauri::AppHandle) { + std::thread::spawn(move || { + sign_out_now(&app); + if let Err(error) = crate::show_setup_and_focus(app) { + log::warn!("[connect] could not show setup after signing out: {error}"); + } + }); +} + +#[cfg(test)] +pub(crate) fn use_for_test( + app: &tauri::AppHandle, + config_dir: PathBuf, + store: credentials::Store, +) { + *state(app).connected.config_dir.lock().unwrap() = Some(config_dir); + *state(app).connected.store.lock().unwrap() = Some(store); +} + +/// As `show` leaves things once a relay is up at `origin`: taken to be showing, and trusted. +#[cfg(test)] +pub(crate) fn showing_for_test(app: &tauri::AppHandle, origin: &str) { + *state(app).connected.relay_for_test.lock().unwrap() = Some(origin.to_owned()); + crate::trust_owned_app(app, origin); +} diff --git a/desktop/src-tauri/src/desktop_page.rs b/desktop/src-tauri/src/desktop_page.rs index 31b1155371..eac5acf852 100644 --- a/desktop/src-tauri/src/desktop_page.rs +++ b/desktop/src-tauri/src/desktop_page.rs @@ -23,6 +23,11 @@ //! And Quit (`quit`), for Ctrl+Q in the window on Windows (`QUIT_SHORTCUT_PAGE`), and Zoom //! (`zoom`), for the zoom keys no menu carries (`zoom::SHORTCUT_PAGE`). The setup and Status pages //! are granted both too (`capabilities/default.json`). +//! +//! And where OpenBot runs (`connection`, `sign_out`, `change_connection`, `set_organization`): on +//! this computer, or at an address the app is connected to (`desktop_connected`). While it is +//! connected, `status` answers the app's own facts only, and what is about an OpenBot on this +//! computer (`restart`, `stop`, `intelligence`, `ai_connection`, `change_ai_connection`) is refused. use openbot_desktop_lib::{app_update, local_eval, local_eval_state, speech, stack}; use tauri::Manager; @@ -33,7 +38,11 @@ pub const PLUGIN: &str = "openbot-desktop"; pub const QUIT_SHORTCUT_PAGE: &str = include_str!("quit-shortcut.js"); /// The permissions a page needs for every command here. -pub const PERMISSIONS: [&str; 21] = [ +pub const PERMISSIONS: [&str; 25] = [ + "openbot-desktop:allow-connection", + "openbot-desktop:allow-sign-out", + "openbot-desktop:allow-change-connection", + "openbot-desktop:allow-set-organization", "openbot-desktop:allow-appearance", "openbot-desktop:allow-status", "openbot-desktop:allow-restart", @@ -90,13 +99,57 @@ async fn status( #[tauri::command] pub async fn restart(app: tauri::AppHandle) -> Result<(), String> { + crate::desktop_connected::nothing_here(&app)?; crate::restart_openbot_from(app, crate::AskedFrom::Settings).await } /// Stops everything, as the menu's Stop did. The page asking goes with it; the window shows setup. +/// Refused while the app is connected to an OpenBot that runs elsewhere: there is none here. #[tauri::command] -pub async fn stop(app: tauri::AppHandle) { +pub async fn stop(app: tauri::AppHandle) -> Result<(), String> { + crate::desktop_connected::nothing_here(&app)?; crate::stop_from_menu(app, crate::AskedFrom::Settings); + Ok(()) +} + +/// Where OpenBot runs: on this computer, or at an address this app is connected to, with the +/// organisation picked there. Never a token. +#[tauri::command] +async fn connection(app: tauri::AppHandle) -> crate::desktop_connected::Connection { + crate::desktop_connected::connection_now(&app, false) +} + +/// Settings' Sign out, while connected: signed out of that OpenBot, and the setup window. The +/// page asking goes with it. +#[tauri::command] +async fn sign_out(app: tauri::AppHandle) -> Result<(), String> { + tauri::async_runtime::spawn_blocking(move || { + crate::desktop_connected::sign_out_now(&app); + crate::show_setup(app) + }) + .await + .map_err(|error| error.to_string())? +} + +/// Settings' Change on where OpenBot runs: the setup window at that choice, after signing out of +/// the OpenBot the app is connected to, or after stopping the one on this computer. +#[tauri::command] +async fn change_connection(app: tauri::AppHandle) -> Result<(), String> { + tauri::async_runtime::spawn_blocking(move || { + crate::desktop_connected::change_connection_now(&app) + }) + .await + .map_err(|error| error.to_string())? +} + +/// The organisation the person picked in the switcher, which every request names from now on. +/// None for no choice. Something that is not an organisation's id is refused. +#[tauri::command] +async fn set_organization( + app: tauri::AppHandle, + organization_id: Option, +) -> Result<(), String> { + crate::desktop_connected::set_organization_now(&app, organization_id) } /// `local status`, `start` or `stop` for the stack recorded for this installation. @@ -105,6 +158,10 @@ async fn intelligence( app: tauri::AppHandle, action: local_eval::Action, ) -> Result { + // Connected to an OpenBot that runs elsewhere: there is no backend on this computer to ask. + if crate::desktop_connected::is_connected(&app) { + return Err(local_eval::Failure::Unavailable); + } let root = crate::cleanup_root(&app.state::(), &stack::default_root()); let stack = local_eval_state::read(&root, None) .ok_or(local_eval::Failure::Unavailable)? @@ -207,15 +264,20 @@ async fn notify( /// Settings' AI model row: the provider and sign-in OpenBot starts with, the model when one was /// named, and a custom address's host. Never a key or a token. #[tauri::command] -async fn ai_connection(app: tauri::AppHandle) -> openbot_desktop_lib::ai_connection::AiConnection { - crate::ai_connection_now(&app) +async fn ai_connection( + app: tauri::AppHandle, +) -> Result { + crate::desktop_connected::nothing_here(&app)?; + Ok(crate::ai_connection_now(&app)) } /// The AI model row's Change: Stop, then the setup window at its AI screen, the one its Change AI /// connection opens. The page asking goes with OpenBot, as with Stop. #[tauri::command] -async fn change_ai_connection(app: tauri::AppHandle) { +async fn change_ai_connection(app: tauri::AppHandle) -> Result<(), String> { + crate::desktop_connected::nothing_here(&app)?; crate::change_ai_connection_from_settings(app); + Ok(()) } /// Settings' Share usage data: whether this installation shares, and whether the app's own @@ -273,7 +335,11 @@ pub fn plugin() -> tauri::plugin::TauriPlugin { usage_data, set_usage_data, quit, - zoom + zoom, + connection, + sign_out, + change_connection, + set_organization ]) .build() } diff --git a/desktop/src-tauri/src/main.rs b/desktop/src-tauri/src/main.rs index dea04a2089..4af8645e1f 100644 --- a/desktop/src-tauri/src/main.rs +++ b/desktop/src-tauri/src/main.rs @@ -4,6 +4,7 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; +mod desktop_connected; mod desktop_connection; mod desktop_host_access; mod desktop_page; @@ -126,6 +127,9 @@ struct Shell { app_update: app_update::Known, /// Wakes the thread that gets a newer version ready when the feed names one. update_ready: update_ready::Nudge, + /// The app connected to an OpenBot that runs somewhere else: its relay and sign-in while the + /// window shows it. See `desktop_connected`. + connected: desktop_connected::State, } /// The deployment whose Compose up may have created containers, including a partial failure. @@ -483,6 +487,7 @@ answers. */ #[tauri::command] async fn wake_engine(app: tauri::AppHandle, root: String) -> Result<(), Problem> { + desktop_connected::local_only(&app)?; let root = stack::root_from(&root); let shell_app = app.clone(); let up = tauri::async_runtime::spawn_blocking(move || { @@ -1919,6 +1924,7 @@ async fn upgrade_and_start( model: ChosenModel, harness: Option, ) -> Result { + desktop_connected::local_only(&app)?; let asked = std::time::Instant::now(); log::info!("[update] asked to update the installation in {root} and start it"); let ran = upgrade_and_start_now(app, root, api_url, gateway_ws_url, model, harness).await; @@ -2194,6 +2200,12 @@ fn get_updates_ready(app: &tauri::AppHandle) { let mut next = BEHIND_TICK; loop { handle.state::().update_ready.wait(next); + // Connected to an OpenBot that runs elsewhere: nothing is downloaded for an + // installation here. The app's own update is not this thread's. + if desktop_connected::is_connected(&handle) { + next = app_update::TICK; + continue; + } let behind = try_getting_own_release_ready(&handle, &mut own, &mut own_said); if fed { try_getting_update_ready(&handle, test.as_deref(), &mut lists, &mut said); @@ -2921,6 +2933,7 @@ async fn install_app_update(app: tauri::AppHandle) -> Result<(), Problem> { #[tauri::command] async fn prepare_engine(app: tauri::AppHandle) -> Result { + desktop_connected::local_only(&app)?; let asked = std::time::Instant::now(); let saved = { let shell = app.state::(); @@ -2936,6 +2949,10 @@ async fn prepare_engine(app: tauri::AppHandle) -> Result, ) -> Result<(), Problem> { + desktop_connected::local_only(&app)?; if app .state::() .updating @@ -4143,6 +4161,7 @@ async fn start_stack( // Both registers on the way out: see `problem.rs`. Anything that still returns a bare string // converts to the plain half, so a path without its own sentence reads as it always did. ) -> Result<(), openbot_desktop_lib::problem::Problem> { + desktop_connected::local_only(&app)?; let asked = std::time::Instant::now(); // The choices, never the values: which provider and how, not the key or the address. log::info!( @@ -5024,6 +5043,13 @@ the same cleanup runs in the same order and the exit follows. fn quit_cleanup_shown(app: &tauri::AppHandle) -> Vec { // A setup window that stopped answering and still has not: said before the flush below. desktop_stall::at_quit(app); + // Connected to an OpenBot that runs elsewhere: Quit closes. Nothing on this computer runs + // because of it, so there is nothing to stop and no Shutting down screen to show. + if desktop_connected::is_connected(app) { + desktop_telemetry::shutdown(app); + desktop_connected::quit(app); + return Vec::new(); + } show_shutting_down(app); desktop_telemetry::shutdown(app); let shell = app.state::(); @@ -6476,6 +6502,11 @@ where async fn show_openbot(app: tauri::AppHandle) -> Result<(), Problem> { let asked = std::time::Instant::now(); log::info!("[show] asked"); + // Connected to an OpenBot that runs elsewhere, this computer's own is not looked for. + if let Err(problem) = desktop_connected::local_only(&app) { + logging::outcome("show", asked, &Err::<(), _>(problem.clone())); + return Err(problem); + } let shown = tauri::async_runtime::spawn_blocking(move || { let ports = ports_for_shell(&app)?; show_openbot_on(app, &ports) @@ -6990,6 +7021,10 @@ fn saved_main_window(app: &tauri::AppHandle) -> Option(app: &tauri::AppHandle, url: &tauri::Url) -> WindowPage { if on_setup_page(app, url) { WindowPage::Setup + } else if desktop_connected::is_relay_page(app, url) { + // OpenBot from the OpenBot the app is connected to, through the relay: its own page, from + // a release that makes room for the window buttons. No installation here is asked. + WindowPage::OwnedApp } else if url.scheme() == "http" && matches!(url.host_str(), Some("127.0.0.1" | "localhost" | "[::1]")) && is_owned_app_origin(app, url) @@ -8111,6 +8146,10 @@ Its own window rather than a page of the main one, so looking at it never takes screen. Closing it hides it, as the main window does; it reads everything again when shown. */ fn show_status_window(app: &tauri::AppHandle) { + // Status is about OpenBot on this computer; a connected app has none to report on. + if desktop_connected::is_connected(app) { + return; + } if show_status_in_app(app) { return; } @@ -8218,12 +8257,43 @@ pub(crate) struct DesktopStatus { log_folder: Option, } +impl DesktopStatus { + /// What there is to say with no OpenBot on this computer in the picture: the app's version, + /// its build and its log folder. Nothing of an installation here is read to answer. + fn of_the_app_alone(app: &tauri::AppHandle) -> Self { + DesktopStatus { + openbot_running: false, + openbot_held: false, + processes: Vec::new(), + containers: Vec::new(), + intelligence_stack: None, + intelligence_containers: Vec::new(), + engine: None, + root: String::new(), + app_port: None, + version: desktop_version(app), + build: build_description( + env!("OPENBOT_BUILD_COMMIT"), + env!("OPENBOT_BUILD_BRANCH"), + env!("OPENBOT_BUILD_TIME").parse().unwrap_or_default(), + ), + log_folder: logging::folder(app) + .ok() + .map(|folder| folder.display().to_string()), + } + } +} + #[tauri::command] async fn desktop_status( app: tauri::AppHandle, memory: Option, ) -> Result { let memory = memory.unwrap_or(true); + // Connected to an OpenBot that runs elsewhere: the app's own facts, and no engine asked. + if desktop_connected::is_connected(&app) { + return Ok(desktop_connected::status(&app)); + } tauri::async_runtime::spawn_blocking(move || read_desktop_status(&app, memory)) .await .map_err(|error| format!("the status could not be read: {error}")) @@ -8579,6 +8649,10 @@ where /// there froze the window until the download finished. #[tauri::command] async fn already_running(app: tauri::AppHandle, root: String) -> bool { + // Connected to an OpenBot that runs elsewhere, none here is looked for. + if desktop_connected::is_connected(&app) { + return false; + } tauri::async_runtime::spawn_blocking(move || already_running_now(&app, &root)) .await .unwrap_or(false) @@ -10788,6 +10862,11 @@ fn show_setup_when_stopped( /// Used by the tray and by a second launch, both of which happen at moments when the caller has no /// idea which of the two the person should be looking at. fn show_whichever_applies(app: &tauri::AppHandle) { + // Connected to an OpenBot that runs elsewhere: that one, or setup to sign in to it. + if desktop_connected::is_connected(app) { + desktop_connected::show_window(app); + return; + } match ports_for_shell(app) { Ok(ports) => restore_window_on(app, &ports), Err(problem) => { @@ -11060,14 +11139,21 @@ fn publish_quit_notice_failure(app: tauri::AppHandle, erro /// Stop in the background, then the setup window: the menu's Stop, and the Status window's and /// Settings > This computer's, which `from` tells apart in the log. fn stop_from_menu(app: tauri::AppHandle, from: AskedFrom) { - stop_then_show_setup(app, from, false); + stop_then_show_setup(app, from, false, false); +} + +/// Settings' Change on where OpenBot runs, while it runs on this computer: the same Stop, then the +/// setup window at its choice of where OpenBot runs. The choice on record is not changed by +/// asking. A Stop that failed shows setup with its failure, as any failed Stop does. +pub(crate) fn change_connection_from_settings(app: tauri::AppHandle) { + stop_then_show_setup(app, AskedFrom::Settings, false, true); } /// Settings' Change on the AI model row: the same Stop, then the setup window at its AI screen, /// where the setup window's own Change AI connection goes. A Stop that failed shows setup as any /// failed Stop does, with its failure and Start, since OpenBot may still be running. pub(crate) fn change_ai_connection_from_settings(app: tauri::AppHandle) { - stop_then_show_setup(app, AskedFrom::Settings, true); + stop_then_show_setup(app, AskedFrom::Settings, true, false); } /// The setup page's one question on load: was it opened to change the AI connection? Answered @@ -11103,6 +11189,7 @@ fn stop_then_show_setup( app: tauri::AppHandle, from: AskedFrom, change_ai_connection: bool, + choose_connection: bool, ) { std::thread::spawn(move || { let asked = std::time::Instant::now(); @@ -11117,6 +11204,10 @@ fn stop_then_show_setup( }; logging::outcome("stop", asked, &settled); settle_change_ai_connection(&shell, settled.is_ok(), change_ai_connection); + // Asked for only once everything stopped, as the AI screen is. + if choose_connection && settled.is_ok() { + desktop_connected::ask_to_choose(&app); + } match settled { Ok(()) => report_plain(&app, "stopped", true, "OpenBot has stopped."), // Said rather than swallowed. A menu item that fails silently is worse than one @@ -11159,6 +11250,14 @@ fn settle_menu_stop(shell: &Shell, fallback_root: &Path, stopped: Stopped) -> Op fn chose(app: &tauri::AppHandle, item: &str) { match item { "open" => show_whichever_applies(app), + // The two a connected app's menus carry in place of Status and the troubleshooting logs. + CONNECTED_SIGN_OUT_MENU_ID => desktop_connected::sign_out_from_menu(app.clone()), + CONNECTED_LOG_FOLDER_MENU_ID => { + let _ = open_log_folder_now(app); + } + // Stop, Status and the engine's logs are about OpenBot on this computer. A connected app's + // menus do not carry them, and a shortcut or a stale menu does not reach them either. + "stop" | "status" | "logs" if desktop_connected::is_connected(app) => {} // Stop without quitting: the stack is what costs something to leave running, and somebody // who wants it stopped does not necessarily want the application gone. "stop" => stop_from_menu(app.clone(), AskedFrom::Menu), @@ -11418,6 +11517,13 @@ const TROUBLESHOOTING_MENU_LABEL: &str = "Get Troubleshooting Logs…"; /// The same item while the logs it asked for are being gathered, which can't be chosen. const TROUBLESHOOTING_MENU_GATHERING: &str = "Gathering Logs…"; +/// The menus' Sign Out and Open Log Folder while the app is connected to an OpenBot that runs +/// elsewhere. See `desktop_connected`. +const CONNECTED_SIGN_OUT_MENU_ID: &str = "sign-out"; +const CONNECTED_SIGN_OUT_MENU_LABEL: &str = "Sign Out"; +const CONNECTED_LOG_FOLDER_MENU_ID: &str = "log-folder"; +const CONNECTED_LOG_FOLDER_MENU_LABEL: &str = "Open Log Folder"; + /// The troubleshooting item's label, and whether it can be chosen. fn troubleshooting_menu_item(gathering: bool) -> (&'static str, bool) { if gathering { @@ -11439,6 +11545,9 @@ fn install_menus(app: &tauri::AppHandle) -> tauri::Result< // The menu bar menu follows the system's appearance; its icons are drawn for each. let dark = system_is_dark(app); let running = app.state::().root.lock().unwrap().is_some(); + // Connected to an OpenBot that runs elsewhere: Show Window, the app's log folder, Sign Out and + // Quit. Nothing here starts, stops or reports on OpenBot, because none runs on this computer. + let connected = desktop_connected::is_connected(app); // Check for Updates… only in a build offered updates: anywhere else it could only say no. let updates = app_update_feed(app).is_some(); let (logs_label, logs_enabled) = @@ -11465,6 +11574,50 @@ fn install_menus(app: &tauri::AppHandle) -> tauri::Result< */ let tray_entries = || -> tauri::Result>> { let icon = |name: &str| menu_icon(name, dark); + if connected { + let mut entries = vec![ + MenuEntry::Icon(IconMenuItem::with_id( + app, + "open", + "Show Window", + true, + icon("open"), + None::<&str>, + )?), + MenuEntry::Plain(MenuItem::with_id( + app, + CONNECTED_LOG_FOLDER_MENU_ID, + CONNECTED_LOG_FOLDER_MENU_LABEL, + true, + None::<&str>, + )?), + MenuEntry::Plain(MenuItem::with_id( + app, + CONNECTED_SIGN_OUT_MENU_ID, + CONNECTED_SIGN_OUT_MENU_LABEL, + true, + None::<&str>, + )?), + MenuEntry::Native(PredefinedMenuItem::separator(app)?), + MenuEntry::Native(PredefinedMenuItem::about( + app, + Some("About"), + Some(about_openbot(desktop_version(app))), + )?), + ]; + // The app itself still updates. + entries.extend(updates.then(check_for_updates).transpose()?); + entries.push(MenuEntry::Native(PredefinedMenuItem::separator(app)?)); + entries.push(MenuEntry::Icon(IconMenuItem::with_id( + app, + "quit", + "Quit", + true, + icon("quit"), + quit_menu_accelerator(), + )?)); + return Ok(entries); + } let mut entries = vec![ MenuEntry::Icon(IconMenuItem::with_id_and_native_icon( app, @@ -11546,6 +11699,30 @@ fn install_menus(app: &tauri::AppHandle) -> tauri::Result< true, None::<&str>, )?)); + if connected { + entries.push(MenuEntry::Plain(MenuItem::with_id( + app, + CONNECTED_LOG_FOLDER_MENU_ID, + CONNECTED_LOG_FOLDER_MENU_LABEL, + true, + None::<&str>, + )?)); + entries.push(MenuEntry::Plain(MenuItem::with_id( + app, + CONNECTED_SIGN_OUT_MENU_ID, + CONNECTED_SIGN_OUT_MENU_LABEL, + true, + None::<&str>, + )?)); + entries.push(MenuEntry::Plain(MenuItem::with_id( + app, + "quit", + "Quit", + true, + quit_menu_accelerator(), + )?)); + return Ok(entries); + } entries.push(MenuEntry::Plain(MenuItem::with_id( app, "status", @@ -12151,6 +12328,15 @@ fn main() { open_log_folder, troubleshooting_logs, save_troubleshooting_logs, + // The app connected to an OpenBot that runs elsewhere. See `desktop_connected`. + desktop_connected::connection, + desktop_connected::check_openbot_address, + desktop_connected::connect_to_openbot, + desktop_connected::cancel_connect, + desktop_connected::show_connected, + desktop_connected::sign_out_of_openbot, + desktop_connected::use_this_computer, + desktop_connected::take_connection_notice, ]) // A packaged application is not a browser tab. Left alone, WebView2 answers a right-click // with Back, Refresh, Save as and Print: Back walks the window out of OpenBot with nothing @@ -12300,10 +12486,16 @@ fn main() { get_updates_ready(app.handle()); desktop_telemetry::initialize(app.handle()); desktop_stall::initialize(app.handle()); + // Connected to an OpenBot that runs elsewhere, no installation here is looked for. + let connected = desktop_connected::is_connected(app.handle()); + if connected { + log::info!("[launch] connected to an OpenBot that runs elsewhere"); + } if let Some(root) = app .path() .app_config_dir() .ok() + .filter(|_| !connected) .and_then(|config| preparation::selected_root(&config)) { remember_selected_root(&app.state::(), &root); @@ -13149,6 +13341,7 @@ mod tests { include!("composio_ipc_tests.rs"); include!("local_eval_ipc_tests.rs"); include!("logging_file_tests.rs"); + include!("connected_ipc_tests.rs"); // The release half (it starts the install thread) is the app's own launch; a test runs a debug build. #[cfg(debug_assertions)] diff --git a/desktop/src-tauri/src/stop_ipc_tests.rs b/desktop/src-tauri/src/stop_ipc_tests.rs index b0170b18c9..93d6a7eea6 100644 --- a/desktop/src-tauri/src/stop_ipc_tests.rs +++ b/desktop/src-tauri/src/stop_ipc_tests.rs @@ -251,7 +251,8 @@ mod stop_ipc { let compose = fixture.compose_barrier(); // The command Settings > This computer invokes. - tauri::async_runtime::block_on(desktop_page::stop(fixture.app.handle().clone())); + tauri::async_runtime::block_on(desktop_page::stop(fixture.app.handle().clone())) + .expect("OpenBot on this computer stops as it did"); await_compose(&compose).write_all(&[0]).unwrap(); wait_until(|| fixture.window.url().unwrap().as_str() == setup); diff --git a/desktop/src-tauri/src/telemetry.rs b/desktop/src-tauri/src/telemetry.rs index 3117e28344..244c0f9995 100644 --- a/desktop/src-tauri/src/telemetry.rs +++ b/desktop/src-tauri/src/telemetry.rs @@ -1056,6 +1056,9 @@ pub enum Step { Model, Connect, Ask, + /// Connecting to an OpenBot that runs elsewhere: the address and the sign-in. The step's name + /// only; the address is never part of any event. + ConnectOpenbot, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] @@ -1392,7 +1395,14 @@ pub const APP_VERSION_PATTERN: &str = pub fn schema_json() -> serde_json::Value { let steps = [ - "welcome", "harness", "install", "account", "model", "connect", "ask", + "welcome", + "harness", + "install", + "account", + "model", + "connect", + "ask", + "connect_openbot", ]; serde_json::json!({ "schema_version": STATE_SCHEMA_VERSION, @@ -2025,6 +2035,41 @@ mod tests { ] } + /// The setup window's step for connecting to an OpenBot that runs elsewhere is one the shell + /// knows, so its events are sent. They say the step and nothing about where: an event with an + /// address, or any other property, is refused. + #[test] + fn the_connect_to_an_openbot_step_is_known_and_never_carries_the_address() { + let listed = &schema_json()["events"]["step_viewed"]["step"]; + assert!( + listed + .as_array() + .is_some_and(|steps| steps.iter().any(|step| step == "connect_openbot")), + "{listed}" + ); + for kind in ["step_viewed", "setup_abandoned"] { + let sent = serde_json::json!({ "kind": kind, "step": "connect_openbot" }); + let event = serde_json::from_value::(sent.clone()).unwrap(); + assert_eq!(serde_json::to_value(event).unwrap(), sent); + for (property, value) in [ + ("address", "https://openbot.example.com"), + ("host", "openbot.example.com"), + ("url", "https://openbot.example.com/api/me"), + ] { + let mut open = sent.clone(); + open[property] = serde_json::json!(value); + assert!( + serde_json::from_value::(open).is_err(), + "{kind} took {property}" + ); + } + } + // A step's name is one of the closed list, so an address cannot stand in for one. + let named = + serde_json::json!({ "kind": "step_viewed", "step": "https://openbot.example.com" }); + assert!(serde_json::from_value::(named).is_err()); + } + /// The two stall events carry closed values and numbers only: a step that is not one of the /// journeys' timed steps, any text, or any other property is refused. #[test] diff --git a/docs/desktop-install.md b/docs/desktop-install.md index ffd16c55dc..8cc4d64e4c 100644 --- a/docs/desktop-install.md +++ b/docs/desktop-install.md @@ -9,7 +9,8 @@ behind the design. The code comments named here hold the details; this page is t The desktop app installs and runs OpenBot for one person on one computer, with CopilotKit Intelligence running on the same computer. The person needs no terminal, no developer tools and no container engine of their own. The app is standalone: there is no hosted or self-hosted -Intelligence option, no organization sign-in and no Bot picker. It installs the default Bot. +Intelligence option, no organization sign-in and no Bot picker. It installs the default Bot. The +one other thing it can do is show an OpenBot that already runs somewhere else, described next. Installers are published for Apple silicon and Intel Macs and for Windows x64. On an Intel Mac the app cannot install Podman, because Podman publishes its Mac installer for Apple silicon only, so @@ -17,6 +18,42 @@ that person needs Docker Desktop or Podman Desktop first (`install::podman_downl ARM cannot run WSL 2 inside a virtual machine on Apple silicon, so test Windows builds on an x64 machine. +## On this computer, or connected to an OpenBot + +At setup, and later from Settings, a person chooses where OpenBot runs. **On this computer** is +everything the rest of this page describes. **Connect to an OpenBot** takes one address, such as +`https://openbot.example.com`, and shows that OpenBot in the app's window. Nothing is installed or +started on the computer, and no account, license or model key is asked for. The choice is kept in +`connection.json` in the app's configuration folder (`connected/choice.rs`), and switching back +leaves a local installation, its folder and its data exactly as they were. + +The person signs in to that OpenBot in their own browser: OAuth 2.1 authorization code with PKCE +and a redirect to `http://127.0.0.1:/callback` (`connected/sign_in.rs`). The refresh token is +kept in the operating system's credential store (Keychain, Credential Manager or the Secret +Service) and the access token only in memory; neither is written to a file or a log, and the page +never holds one. The window loads the app from a relay on `127.0.0.1` (`connected/relay.rs`), which +passes each request on to the one address the person typed with the access token added, and +refreshes the token before it ends. The relay answers only its own `127.0.0.1:`, only to the +window (a secret made for each run, carried in a cookie the relay sets), and never follows a +redirect to another host. + +What is about OpenBot on this computer is not there while the app is connected: + +| On this computer | Connected to an OpenBot | +|---|---| +| Start, Stop and Restart, the Status window, and their tray and menu items | Not shown. The tray and menu have Show Window, Open Log Folder, Sign Out and Quit. | +| Installing and updating OpenBot's services (downloads, the engine, the upgrade at Start) | Never run. The app still updates itself. | +| The local Intelligence, the account sign-in and the 30-day license | Not asked for. The OpenBot it connects to has its own. | +| Model keys and model sign-ins kept on this computer | Not shown. That OpenBot's admin sets its models. | +| Settings, Computer: services, memory and the engine | One Connection section: the address, Sign out, and using OpenBot on this computer. The app's version, updates and log folder stay. | +| Local folder access for Bots, and this computer as a Bot's computer | Not started. Bots use the computers that OpenBot gives them. | +| The connection watcher and Learning's model on this computer | Not started. | +| Quit stopping everything | Quit closes the app. Nothing on the computer runs because of it. | + +Dictation, notifications, zoom, the window's place, the theme, `openbot://` links and outside +links opening in the browser work the same either way. An OpenBot running on this computer when +the person connects to another is stopped first, as Stop stops it. + ## The flow The window shows four sections: **Account**, **Install**, **AI** and **Start** From 76d70717fc33601fac34a0283c48377e7461b097 Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 13:29:17 -0800 Subject: [PATCH 008/116] Name Desktop's connect addresses in the client boundary, and ask the runtime after sign-in The boundary check found the new addresses Desktop's native side writes by hand: the deployment question, OAuth's discovery document and the check after sign-in. Each is now listed with its rule. The check after sign-in asks the runtime's own address, which is what the app's screens need from an app's sign-in and an address that stays, in place of /api/me. The test stand-in's file name now ends in _tests.rs so the scan reads it as a test. --- api/client-boundary.allow.ts | 19 +++++++++++++++++++ ...{fake_openbot.rs => fake_openbot_tests.rs} | 6 +++--- desktop/src-tauri/src/connected/mod.rs | 3 +++ desktop/src-tauri/src/connected/sign_in.rs | 18 +++++++++--------- 4 files changed, 34 insertions(+), 12 deletions(-) rename desktop/src-tauri/src/connected/{fake_openbot.rs => fake_openbot_tests.rs} (99%) diff --git a/api/client-boundary.allow.ts b/api/client-boundary.allow.ts index 1938b4e6d4..31b6b72a1e 100644 --- a/api/client-boundary.allow.ts +++ b/api/client-boundary.allow.ts @@ -298,6 +298,25 @@ export const ALLOWED: Allowed[] = [ rule: "hand-built-v2", why: "the Recorder host's handoff, from Rust, which has no generated client", }, + // Desktop connecting to an OpenBot that runs somewhere else. + { + file: "desktop/src-tauri/src/connected/address.rs", + what: "/api/v2/organizations/default/deployment", + rule: "hand-built-v2", + why: "whether the address a person typed is an OpenBot, asked from Rust before anybody signs in", + }, + { + file: "desktop/src-tauri/src/connected/address.rs", + what: "/.well-known/oauth-authorization-server/api/auth", + rule: "before-sign-in", + why: "OAuth's discovery document, which names the sign-in's addresses", + }, + { + file: "desktop/src-tauri/src/connected/sign_in.rs", + what: "/api/copilotkit/info", + rule: "runtime", + why: "whether the OpenBot serves its runtime to an app's sign-in, asked once after signing in", + }, // Path tables the server registers today's routes from. ...["shared/bot-browser.ts", "shared/openbot-browser.ts"].map( (file): Allowed => ({ diff --git a/desktop/src-tauri/src/connected/fake_openbot.rs b/desktop/src-tauri/src/connected/fake_openbot_tests.rs similarity index 99% rename from desktop/src-tauri/src/connected/fake_openbot.rs rename to desktop/src-tauri/src/connected/fake_openbot_tests.rs index 72d87c0848..0e161e0e4e 100644 --- a/desktop/src-tauri/src/connected/fake_openbot.rs +++ b/desktop/src-tauri/src/connected/fake_openbot_tests.rs @@ -10,7 +10,7 @@ loopback port that answers the addresses the app uses as the real one does. against the challenge, a code that burns on its first use (right or wrong), and refresh tokens that rotate, where one used a second time answers `invalid_grant` and ends the family; - revocation (RFC 7009); -- `/api/me` and a few `/api/v2` addresses that honour a Bearer access token and nothing else, one +- `/api/copilotkit/info` and a few `/api/v2` addresses that honour a Bearer access token and nothing else, one of them a stream and one a WebSocket. And a stand-in for the person's browser (`Browser`), which follows the authorization address the @@ -53,7 +53,7 @@ pub enum Shape { MetadataElsewhere, /// Every address redirects to the same path at another address. RedirectsTo(String), - /// Signs the app in, and then refuses the token on `/api/me`. + /// Signs the app in, and then refuses the token on `/api/copilotkit/info`. MeRefuses, } @@ -538,7 +538,7 @@ async fn answer( // RFC 7009 §2.2: 200 whether or not the token was known. json(StatusCode::OK, serde_json::json!({})) } - ("GET", "/api/me") => match authorized { + ("GET", "/api/copilotkit/info") => match authorized { Some(_) if shape != Shape::MeRefuses => { json(StatusCode::OK, serde_json::json!({ "id": "person-1" })) } diff --git a/desktop/src-tauri/src/connected/mod.rs b/desktop/src-tauri/src/connected/mod.rs index 51026de217..36fde5df8f 100644 --- a/desktop/src-tauri/src/connected/mod.rs +++ b/desktop/src-tauri/src/connected/mod.rs @@ -21,7 +21,10 @@ pub mod credentials; pub mod relay; pub mod sign_in; +// The file's name ends in `_tests.rs` so the repository's scan of hand-written server addresses +// (api/client-boundary.test.ts) reads it as the test stand-in it is. #[cfg(test)] +#[path = "fake_openbot_tests.rs"] pub(crate) mod fake_openbot; use crate::problem::Problem; diff --git a/desktop/src-tauri/src/connected/sign_in.rs b/desktop/src-tauri/src/connected/sign_in.rs index 2457586e2f..a1403962ac 100644 --- a/desktop/src-tauri/src/connected/sign_in.rs +++ b/desktop/src-tauri/src/connected/sign_in.rs @@ -119,7 +119,7 @@ Sign in to the OpenBot at `address` in the person's browser. `open` is handed the address to open, the system browser in the app. The wait ends when the browser comes back with a code, when the person refuses, when `attempt` is cancelled, or after `wait`. -Returns once the code is exchanged, the OpenBot has answered `/api/me` with the new token, and the +Returns once the code is exchanged, the OpenBot has answered `/api/copilotkit/info` with the new token, and the refresh token is in `store`. */ pub fn sign_in( @@ -347,12 +347,12 @@ impl Session { }) } - /// Whether the OpenBot serves the app's screens to this sign-in: `GET /api/me` with the token. + /// Whether the OpenBot serves the app's screens to this sign-in: `GET /api/copilotkit/info` with the token. fn serves_the_app(&self) -> Result<(), Problem> { let access = self.live.lock().unwrap().access.clone(); let answered = http() .map_err(|error| Kind::Unreachable.problem(&self.host, error))? - .get(format!("{}/api/me", self.address)) + .get(format!("{}/api/copilotkit/info", self.address)) .bearer_auth(access) .header(reqwest::header::ACCEPT, "application/json") .send() @@ -362,14 +362,14 @@ impl Session { 401 | 404 => Err(Kind::TooOld.problem( &self.host, format!( - "GET /api/me answered {} to a new sign-in", + "GET /api/copilotkit/info answered {} to a new sign-in", answered.status() ), )), - status => { - Err(Kind::SignInFailed - .problem(&self.host, format!("GET /api/me answered {status}"))) - } + status => Err(Kind::SignInFailed.problem( + &self.host, + format!("GET /api/copilotkit/info answered {status}"), + )), } } @@ -745,7 +745,7 @@ mod tests { assert_eq!(WAIT, Duration::from_secs(600)); } - /// An OpenBot that signs the app in and then refuses the new token on `/api/me` is on a + /// An OpenBot that signs the app in and then refuses the new token on `/api/copilotkit/info` is on a /// release that cannot serve the app. Nothing is kept, and the tokens are revoked. #[test] fn an_openbot_that_refuses_its_own_new_token_is_too_old() { From 3b1307f5a4ad01669661858cf4d61246ccc28ebd Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 13:30:12 -0800 Subject: [PATCH 009/116] Say in the changelog that OpenBot Desktop can connect to an OpenBot elsewhere --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56df252441..ac8509bc41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,16 @@ every deployment: ### OpenBot Desktop +- **OpenBot Desktop can connect to an OpenBot that runs somewhere else.** At set-up, and later in + Settings, Computer, choose between OpenBot on this computer, as before, and an OpenBot at an + address you type, such as your company's. Connected, nothing is installed or started on this + computer and no CopilotKit account is asked for: you sign in to that OpenBot in your browser, and + the app keeps the sign-in in Keychain or Windows Credential Manager, never in a file. Settings + shows where the app is connected, with Sign out and a way back to OpenBot on this computer, + which loses nothing. Starting, stopping and updating OpenBot's services, model keys and local + folders for Bots belong to OpenBot on this computer and are not shown while connected. It needs + an OpenBot whose server honours an app's sign-in for its screens; an earlier one is refused with + a sentence saying so. - **OpenBot Desktop is one address.** With CopilotKit Intelligence on the same machine, the app used to open a second connection, straight to Intelligence's gateway on a port of its own. It now opens everything on OpenBot's own address: the server carries that socket From 30dcb17031cde70dfa392added7563dddb3c568d Mon Sep 17 00:00:00 2001 From: David McKay Date: Sun, 15 Nov 2026 13:39:24 -0800 Subject: [PATCH 010/116] Keep Book a demo on setup's first screen, under the Business choice A company with no OpenBot of its own has no address to type, and the booking link is how it asks for one. The link is back on the first screen whichever choice is picked: one line under the OpenBot for Business row, outside the row, so opening it does not pick the row. The connect form no longer repeats it. Two gaps on the first screen are a few pixels tighter, so everything on it still shows at the window's default size without scrolling. --- desktop/src/App.test.tsx | 31 +++++++++++++++++++++++++------ desktop/src/ConnectToOpenBot.tsx | 7 ------- desktop/src/Welcome.tsx | 13 +++++++++++-- desktop/src/styles.css | 19 ++++++++++++++++--- 4 files changed, 52 insertions(+), 18 deletions(-) diff --git a/desktop/src/App.test.tsx b/desktop/src/App.test.tsx index 160d101d3a..98605bfb4b 100644 --- a/desktop/src/App.test.tsx +++ b/desktop/src/App.test.tsx @@ -606,7 +606,7 @@ test("the first screen offers Self-hosted and OpenBot for Business, shows Cloud setupRootConfiguration("/tmp/local-eval-welcome", async () => emptyConfiguration(), ); - withLocalCli({}); + withLocalCli({ "plugin:opener|open_url": null }); const view = await renderApp(); expect(view.getByRole("heading", { name: "Set up OpenBot" })).toBeTruthy(); // Three ways to run OpenBot. This app sets up the first and connects to the third; OpenBot Cloud @@ -647,6 +647,17 @@ test("the first screen offers Self-hosted and OpenBot for Business, shows Cloud "40 GB of free disk space", ]); expect(buttons(view)).toEqual(["Install"]); + // The one booking link, for a company with no OpenBot of its own: under the Business row, not + // part of it, so opening it leaves the choice where it was. + const demo = view.getByRole("link", { name: "Book a demo" }); + expect(demo.getAttribute("href")).toBe("https://open.bot/business"); + expect(demo.parentElement?.textContent).toBe( + "No OpenBot at your company yet? Book a demo.", + ); + expect(demo.closest("label")).toBeNull(); + await userEvent.click(demo); + expect([self.checked, business.checked]).toEqual([true, false]); + expect(buttons(view)).toEqual(["Install"]); expectPlain(view); expect(localCliCalls()).toEqual([]); }); @@ -729,6 +740,7 @@ async function chooseConnect(shell: Record = {}) { withLocalCli({ connection: THIS_COMPUTER, record_setup_event: null, + "plugin:opener|open_url": null, ...shell, }); const view = await renderApp(); @@ -792,11 +804,18 @@ test("choosing OpenBot for Business asks for an address in place of Install, and "disabled", true, ); - // The one booking link, for somebody whose company has no OpenBot yet. - expect(view.getByText(/Don't have one yet\?/)).toBeTruthy(); - expect( - view.getByRole("link", { name: "Book a demo" }).getAttribute("href"), - ).toBe("https://open.bot/business"); + // The one booking link is still there, once, under the Business row, and opening it leaves the + // choice where it is. + const demo = view.getByRole("link", { name: "Book a demo" }); + expect(demo.getAttribute("href")).toBe("https://open.bot/business"); + expect(demo.parentElement?.textContent).toBe( + "No OpenBot at your company yet? Book a demo.", + ); + expect(demo.closest("label")).toBeNull(); + await userEvent.click(demo); + expect(business.checked).toBe(true); + expect(view.getByLabelText("OpenBot address")).toBeTruthy(); + expect(view.queryByText(/Don't have one yet\?/)).toBeNull(); // OpenBot Cloud is still to come. expect(view.getByRole("radio", { name: /^OpenBot Cloud/ })).toHaveProperty( "disabled", diff --git a/desktop/src/ConnectToOpenBot.tsx b/desktop/src/ConnectToOpenBot.tsx index 4aba407e6d..b10d1a09fe 100644 --- a/desktop/src/ConnectToOpenBot.tsx +++ b/desktop/src/ConnectToOpenBot.tsx @@ -4,9 +4,6 @@ import { ExternalLink } from "./ExternalLink"; import { asProblem, type Problem } from "./Problem"; import { StatusLine } from "./SetupProgress"; -/** OpenBot's one booking link. */ -export const BOOK_A_DEMO = "https://open.bot/business"; - /** * What the screen offers after something went wrong, chosen by the problem's `kind`. The sentence * is the shell's, shown as given. @@ -283,10 +280,6 @@ export function ConnectToOpenBot({ connecting }: { connecting: Connecting }) { {phase === "checking" && ( Checking the address… )} -

- Don't have one yet?{" "} - Book a demo. -

+ + + } + > + + + {(field) => { + const isInvalid = + field.state.meta.isTouched && !field.state.meta.isValid; + return ( + + Name + + field.handleChange(event.target.value) + } + placeholder="Sales" + value={field.state.value} + /> + {isInvalid ? ( + + ) : null} + + ); + }} + + + {(field) => { + const isInvalid = + field.state.meta.isTouched && !field.state.meta.isValid; + return ( + + Description + + Say what the team is for. You can leave this empty. + +