From a0a9e3eb8784fd6b825a8ce111eda9b2106d3dc4 Mon Sep 17 00:00:00 2001 From: Maxim Date: Thu, 3 Dec 2026 21:24:17 +0100 Subject: [PATCH 1/3] Embedded in another app's page, an app's sign-in opens in a tab of its own Embedded (configureEmbed), a screen that sent its tab to an app's sign-in sent the host app's page, and the vendor brought the person back to OpenBot's public address, where somebody signed in through the host has no session: a sign-in screen, out of the app they were using. - The API: returnTo window on connectApp, connectSharedApp and authorizeAction, a page that needs no sign-in and closes the tab the sign-in ran in, offered where getDeployment says windowConnections. - The web app, embedded: the sign-in opens in a tab claimed on the press (lib/plugins/consent-tab.ts), every connect asks for returnTo window where the server offers it, and the connection is read again once the person is back, as OpenBot Desktop's window does. Through Composio, OpenBot's step before the sign-in is left out when embedded: no page of OpenBot's runs on the host's origin to show it. Not embedded, nothing changes. - Docs: Connecting apps, under Embedded sign-in. Co-Authored-By: Claude Opus 5.5 --- api/openapi.yaml | 9 +- api/openapi/admin-settings.yaml | 8 + api/openapi/connections.yaml | 17 +- .../connections/add-server-page.tsx | 52 +++-- app/src/components/manage/plugin-page.tsx | 32 ++- .../plugins/brokered-account-row.tsx | 27 ++- .../components/plugins/connect-in-new-tab.ts | 10 +- app/src/components/plugins/grant-list.tsx | 16 +- .../generated/connections/connections.zod.ts | 16 +- .../api/generated/model/connectionReturnTo.ts | 3 +- app/src/lib/api/generated/model/deployment.ts | 2 + .../model/sharedConnectionReturnTo.ts | 3 +- .../organization-settings.zod.ts | 6 + app/src/lib/connections/connect-app.ts | 9 +- app/src/lib/deployment/queries.ts | 7 + app/src/lib/plugins/confirm-on-return.ts | 6 +- app/src/lib/plugins/consent-tab.ts | 120 ++++++++++ app/src/lib/plugins/grants.ts | 28 ++- app/src/lib/plugins/mutations.ts | 21 +- .../routes/_authed/_app/connections.$key.tsx | 18 +- app/tests/embedded-consent-window.test.ts | 219 ++++++++++++++++++ docs/configuration.md | 8 + .../api/generated/model/connectionReturnTo.ts | 3 +- mobile/src/api/generated/model/deployment.ts | 2 + .../model/sharedConnectionReturnTo.ts | 3 +- 25 files changed, 576 insertions(+), 69 deletions(-) create mode 100644 app/src/lib/plugins/consent-tab.ts create mode 100644 app/tests/embedded-consent-window.test.ts diff --git a/api/openapi.yaml b/api/openapi.yaml index bbfc2aa5f5..1f2a839123 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -32197,6 +32197,9 @@ components: mobileConnections: type: boolean description: Whether an app's sign-in page can send the person back to OpenBot Mobile (returnTo mobile on connectApp), so the phone can connect their apps. Absent from a server older than it. + windowConnections: + type: boolean + description: Whether an app's sign-in page can send the person back to a page that closes the window it ran in (returnTo window on connectApp, connectSharedApp and authorizeAction), so OpenBot embedded in another app's page can open the sign-in in a window of its own and stay where it is. Absent from a server older than it. durableHistory: type: boolean description: Whether conversations are kept between restarts. @@ -36698,8 +36701,9 @@ components: - apps - desktop - mobile + - window default: connections - description: 'Which of OpenBot''s own pages the app sends the person back to: connections, the person''s own page for the app; apps, the app''s page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection. Never an address. A client sends mobile only where getDeployment says mobileConnections.' + description: 'Which of OpenBot''s own pages the app sends the person back to: connections, the person''s own page for the app; apps, the app''s page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection; window, a page that needs no sign-in and closes the window the sign-in ran in, for OpenBot embedded in another app''s page, which opened that window and reads the connection again once the person is back. Never an address. A client sends mobile only where getDeployment says mobileConnections, and window only where it says windowConnections.' ConnectionValues: type: object description: What the person typed into the boxes a form answer asked for, by each box's name. Sent once to the app and never logged or kept here. @@ -37128,8 +37132,9 @@ components: enum: - apps - desktop + - window default: apps - description: 'Which of OpenBot''s own pages the app sends the administrator back to: apps, the app''s page for administrators; desktop, back to OpenBot Desktop. Never an address.' + description: 'Which of OpenBot''s own pages the app sends the administrator back to: apps, the app''s page for administrators; desktop, back to OpenBot Desktop; window, a page that needs no sign-in and closes the window the sign-in ran in (see ConnectionReturnTo). Never an address. A client sends window only where getDeployment says windowConnections.' ConnectSharedAppRequest: type: object additionalProperties: false diff --git a/api/openapi/admin-settings.yaml b/api/openapi/admin-settings.yaml index 2b940a742e..f606185529 100644 --- a/api/openapi/admin-settings.yaml +++ b/api/openapi/admin-settings.yaml @@ -1371,6 +1371,14 @@ components: Whether an app's sign-in page can send the person back to OpenBot Mobile (returnTo mobile on connectApp), so the phone can connect their apps. Absent from a server older than it. + windowConnections: + type: boolean + description: >- + Whether an app's sign-in page can send the person back to a page + that closes the window it ran in (returnTo window on connectApp, + connectSharedApp and authorizeAction), so OpenBot embedded in + another app's page can open the sign-in in a window of its own and + stay where it is. Absent from a server older than it. durableHistory: type: boolean description: Whether conversations are kept between restarts. diff --git a/api/openapi/connections.yaml b/api/openapi/connections.yaml index 313a3af5c6..13145787eb 100644 --- a/api/openapi/connections.yaml +++ b/api/openapi/connections.yaml @@ -1215,23 +1215,28 @@ components: URL-safe base64, the only form the cursor parameter accepts. ConnectionReturnTo: type: string - enum: [connections, apps, desktop, mobile] + enum: [connections, apps, desktop, mobile, window] default: connections description: >- Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to - OpenBot Mobile, which then calls confirmConnection. Never an address. - A client sends mobile only where getDeployment says - mobileConnections. + OpenBot Mobile, which then calls confirmConnection; window, a page that + needs no sign-in and closes the window the sign-in ran in, for OpenBot + embedded in another app's page, which opened that window and reads the + connection again once the person is back. Never an address. A client + sends mobile only where getDeployment says mobileConnections, and + window only where it says windowConnections. SharedConnectionReturnTo: type: string - enum: [apps, desktop] + enum: [apps, desktop, window] default: apps description: >- Which of OpenBot's own pages the app sends the administrator back to: apps, the app's page for administrators; desktop, back to OpenBot - Desktop. Never an address. + Desktop; window, a page that needs no sign-in and closes the window the + sign-in ran in (see ConnectionReturnTo). Never an address. A client + sends window only where getDeployment says windowConnections. ConnectionValues: type: object description: >- diff --git a/app/src/components/connections/add-server-page.tsx b/app/src/components/connections/add-server-page.tsx index a599733a81..b04f79d7f3 100644 --- a/app/src/components/connections/add-server-page.tsx +++ b/app/src/components/connections/add-server-page.tsx @@ -21,6 +21,8 @@ import { currentUserQueryOptions } from "@/lib/auth/queries"; import { isOrganizationAdmin } from "@/lib/auth/roles"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { desktopShell } from "@/lib/desktop/shell"; +import { embedConfig } from "@/lib/embed/config"; +import { useConsentTab } from "@/lib/plugins/consent-tab"; import { useAppsOpen } from "@/lib/enterprise/apps-open"; import { setEnterpriseSettingMutationOptions } from "@/lib/enterprise/mutations"; import { enterpriseOverviewQueryOptions } from "@/lib/enterprise/queries"; @@ -106,6 +108,8 @@ export function AddServerPage({ const connect = useMutation( connectAccountMutationOptions(admin ? "admin" : "settings"), ); + // Embedded in another app's page, the sign-in opens in a tab of its own (lib/plugins/consent-tab.ts). + const consent = useConsentTab(); const approve = useMutation(setEnterpriseSettingMutationOptions(queryClient)); const [refusal, setRefusal] = useState(null); const [signingIn, setSigningIn] = useState(null); @@ -127,6 +131,7 @@ export function AddServerPage({ try { start = await connect.mutateAsync(serverId); } catch (thrown) { + consent.drop(); setSigningIn(null); // Added, and the sign-in could not start: its page says so and offers Connect again. setRefusal({ @@ -137,6 +142,7 @@ export function AddServerPage({ return; } if (!start || !("authorizationUrl" in start)) { + consent.drop(); await openServer(serverId); return; } @@ -147,7 +153,13 @@ export function AddServerPage({ if (desktopShell()) { await openServer(serverId); } - window.location.href = start.authorizationUrl; + /* + * Embedded in another app's page, the sign-in opens in the tab claimed on the press, and this + * page goes on to the server's page, where the connection shows once the person is back + * (lib/plugins/consent-tab.ts). + */ + consent.go(start.authorizationUrl); + if (embedConfig()) await openServer(serverId); } async function submit(value: AddServerFormValues) { @@ -161,6 +173,7 @@ export function AddServerPage({ ...(tokenHeader ? { tokenHeader } : {}), }); if (!outcome.added) { + consent.drop(); setRefusal(outcome); return; } @@ -168,6 +181,7 @@ export function AddServerPage({ await signIn(outcome.server.id, outcome.server.title); return; } + consent.drop(); await added(outcome.server.id); } @@ -185,19 +199,25 @@ export function AddServerPage({ /** The admin's own step for a refused address: put it on the allowlist, then add it. */ async function approveAndAdd() { - const values = form.state.values; - const overview = await queryClient.fetchQuery( - enterpriseOverviewQueryOptions(), - ); - const allowlist = overview.settings.mcpAllowlist; - await approve.mutateAsync({ - key: "mcpAllowlist", - value: { - ...allowlist, - servers: [...allowlist.servers, values.url.trim()], - }, - }); - await submit(values); + // Claimed on the press, as the sign-in may come after approving and adding; let go once settled. + consent.claim(); + try { + const values = form.state.values; + const overview = await queryClient.fetchQuery( + enterpriseOverviewQueryOptions(), + ); + const allowlist = overview.settings.mcpAllowlist; + await approve.mutateAsync({ + key: "mcpAllowlist", + value: { + ...allowlist, + servers: [...allowlist.servers, values.url.trim()], + }, + }); + await submit(values); + } finally { + consent.drop(); + } } const busy = add.isPending || connect.isPending || approve.isPending; @@ -230,7 +250,9 @@ export function AddServerPage({ noValidate onSubmit={(event) => { event.preventDefault(); - void form.handleSubmit(); + // Claimed on the press, as the sign-in may come after adding it; let go once it settles. + consent.claim(); + void form.handleSubmit().finally(() => consent.drop()); }} > { + consent.drop(); + setError(thrown); + }, /* * A full page navigation, not a fetch. The consent screen is the vendor's own and has to be * shown to this person in their own browser; there is deliberately nothing here that could @@ -491,13 +497,14 @@ export function PluginPage({ ? start.authorizationUrl : null; if (authorizationUrl === null) { + consent.drop(); setError({ message: "Couldn't start connecting, so nothing was connected. Try again, or check this app's setup if it keeps happening.", }); return; } - window.location.href = authorizationUrl; + consent.go(authorizationUrl); }, }); /* @@ -673,12 +680,18 @@ export function PluginPage({ setDialog("instance"); return; } + // Claimed on the click: adding it and reading the catalogue come before the sign-in. + consent.claim(); if (await add()) await signInOnceAdded(); + else consent.drop(); }; /** What is left once Connect has added it, for an app reached as you: the sign-in. */ const signInOnceAdded = async () => { - if (auth !== "user-oauth") return; + if (auth !== "user-oauth") { + consent.drop(); + return; + } const fresh = await queryClient.fetchQuery({ ...appsQueryOptions(), staleTime: 0, @@ -689,6 +702,7 @@ export function PluginPage({ return; } // No client to consent against yet: its form, and the sign-in once it is saved. + consent.drop(); connectAfterClient.current = true; setDialog("client"); }; @@ -1398,6 +1412,7 @@ export function PluginPage({ disabled={connectSelf.isPending} onClick={() => { setError(null); + consent.claim(); connectSelf.mutate(key); }} size="sm" @@ -1426,6 +1441,7 @@ export function PluginPage({ disabled={connectSelf.isPending} onClick={() => { setError(null); + consent.claim(); connectSelf.mutate(key); }} size="sm" @@ -1905,20 +1921,24 @@ export function PluginPage({ onClick={() => { if (!server) { // Opened by Connect: Save adds it, and an app reached as you goes on to its sign-in. - void add().then((added) => - added ? signInOnceAdded() : undefined, - ); + consent.claim(); + void add().then((added) => { + if (added) return signInOnceAdded(); + consent.drop(); + }); return; } if (dialog === "client") { const thenConnect = connectAfterClient.current; connectAfterClient.current = false; + if (thenConnect) consent.claim(); registerClient.mutate( { serverId: key, ...client }, { onSuccess: () => { if (thenConnect) connectSelf.mutate(key); }, + onError: () => consent.drop(), }, ); } diff --git a/app/src/components/plugins/brokered-account-row.tsx b/app/src/components/plugins/brokered-account-row.tsx index f51da99921..6664ebe1ac 100644 --- a/app/src/components/plugins/brokered-account-row.tsx +++ b/app/src/components/plugins/brokered-account-row.tsx @@ -21,6 +21,7 @@ import { } from "@/components/ui/item"; import { Separator } from "@/components/ui/separator"; import { vendorNameOf } from "@/lib/apps/vendor-name"; +import { embedConfig } from "@/lib/embed/config"; import { type Failure, failureInstead, failureSaid } from "@/lib/load-failure"; import { useManagePaths } from "@/lib/manage-paths"; import { type AdminName, withAdmins } from "@/lib/organizations/admin-names"; @@ -29,6 +30,7 @@ import { brokeredConsentFor, type ConsentHandoff, } from "@/lib/plugins/consent-handoff"; +import { useConsentTab } from "@/lib/plugins/consent-tab"; import { finishOnReturn } from "@/lib/plugins/finish-on-return"; import { type BrokerField, @@ -432,15 +434,25 @@ export function useBrokeredAccount(input: { * Composio, so the row holds the sign-in here and the dialog says what is coming before it goes * (`ConsentHandoffDialog`). Anything else leaves at once, as it always did. */ + // Embedded in another app's page, the sign-in opens in a tab of its own (lib/plugins/consent-tab.ts). + const consent = useConsentTab(); const [handoff, setHandoff] = useState(null); + /* + * EMBEDDED IN ANOTHER APP'S PAGE, THE SIGN-IN OPENS STRAIGHT AWAY, in the tab claimed on the press + * (lib/plugins/consent-tab.ts). The step can't go first there: as a dialog it counts down to a + * sign-in no click opens, so the browser blocks its tab, and as a page it lives on the host's + * origin, which serves the host app and not OpenBot's. + */ const leaveFor = async (authorizationUrl: string) => { - const consent = await brokeredConsentFor(queryClient, serverId); - if (consent) { - setHandoff({ ...consent, url: authorizationUrl }); + const step = embedConfig() + ? null + : await brokeredConsentFor(queryClient, serverId); + if (step) { + setHandoff({ ...step, url: authorizationUrl }); return; } finishReturn(); - window.location.href = authorizationUrl; + consent.go(authorizationUrl); }; /* @@ -483,6 +495,8 @@ export function useBrokeredAccount(input: { const connect = useMutation({ ...connectAccountMutationOptions(returnTo, shared), onError: (thrown: Error) => report(thrown), + // Whatever the press came to, a tab claimed for it and not sent to a sign-in is closed. + onSettled: () => consent.drop(), /* * A full page navigation, not a fetch. The consent screen is the vendor's own and has to be * shown to this person in their own browser; there is deliberately nothing here that could @@ -689,6 +703,7 @@ export function useBrokeredAccount(input: { const connectAnother = useMutation({ ...connectAnotherAccountMutationOptions(returnTo), onError: (thrown: Error) => report(thrown), + onSettled: () => consent.drop(), onSuccess: (start) => { forgetConfirmation(); forgetRecheck(); @@ -795,6 +810,7 @@ export function useBrokeredAccount(input: { connect: () => { report(null); onArrival.current = false; + consent.claim(); connect.mutate(serverId); }, connectOnArrival: () => { @@ -841,6 +857,7 @@ export function useBrokeredAccount(input: { fieldsSubmitted: submission.isSuccess, connectAnother: () => { report(null); + consent.claim(); connectAnother.mutate(serverId); }, connectingAnother: connectAnother.isPending, @@ -862,7 +879,7 @@ export function useBrokeredAccount(input: { if (!handoff) return; setHandoff(null); finishReturn(); - window.location.href = handoff.url; + consent.go(handoff.url); }, cancelHandoff: () => setHandoff(null), }; diff --git a/app/src/components/plugins/connect-in-new-tab.ts b/app/src/components/plugins/connect-in-new-tab.ts index 9926961ce3..d63374fdd2 100644 --- a/app/src/components/plugins/connect-in-new-tab.ts +++ b/app/src/components/plugins/connect-in-new-tab.ts @@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; import { createElement, useCallback, useEffect, useRef, useState } from "react"; import { ConsentHandoffDialog } from "@/components/plugins/consent-handoff"; import { desktopShell } from "@/lib/desktop/shell"; +import { embedConfig } from "@/lib/embed/config"; import { failureOf } from "@/lib/load-failure"; import { markConnectReturn } from "@/lib/plugins/connect-return"; import { @@ -256,7 +257,14 @@ export function useConnectInNewTab( * THROUGH COMPOSIO, OPENBOT'S STEP COMES FIRST: what the next pages will say, for a countdown, * and then the sign-in. Anything else goes straight there. */ - const consent = await brokeredConsentFor(queryClient, serverId); + /* + * Embedded in another app's page, there is no step first: its page lives on the host's origin, + * which serves the host app and not OpenBot's, so the tab goes straight to the sign-in + * (lib/plugins/consent-tab.ts). + */ + const consent = embedConfig() + ? null + : await brokeredConsentFor(queryClient, serverId); /* * IN OPENBOT DESKTOP'S WINDOW THE STEP IS A DIALOG HERE, and the sign-in opens after it. The * window opens no tab of its own: its tab is a stand-in that hands its address to the person's diff --git a/app/src/components/plugins/grant-list.tsx b/app/src/components/plugins/grant-list.tsx index 1ff3192046..4fb49228c5 100644 --- a/app/src/components/plugins/grant-list.tsx +++ b/app/src/components/plugins/grant-list.tsx @@ -23,6 +23,7 @@ import { groupGrants, RANK, } from "@/lib/plugins/grants"; +import { useConsentTab } from "@/lib/plugins/consent-tab"; /** * What one account holds at one app, action by action, grouped by the permission each action needs. @@ -65,12 +66,18 @@ export function GrantList({ const [choosing, setChoosing] = useState(null); // The refusal itself, not its words: a hold is drawn calmly (`failureSaid`). const [notice, setNotice] = useState(null); + // Embedded in another app's page, the consent opens in a tab of its own (lib/plugins/consent-tab.ts). + const consent = useConsentTab(); const authorize = useMutation({ ...authorizeActionMutationOptions(returnTo, shared), - onError: (thrown: Error) => setNotice(thrown), + onError: (thrown: Error) => { + consent.drop(); + setNotice(thrown); + }, /* A full page navigation: the consent screen is the vendor's own and shown in this browser. */ onSuccess: (authorizationUrl) => { if (authorizationUrl === null) { + consent.drop(); setNotice({ message: "OpenBot answered without a consent link, so nothing was authorized. Try again, or ask an admin if it keeps happening.", @@ -78,7 +85,7 @@ export function GrantList({ return; } finishOnReturn(); - window.location.href = authorizationUrl; + consent.go(authorizationUrl); }, }); @@ -242,7 +249,10 @@ export function GrantList({ action={choosing} busy={authorize.isPending} onCancel={() => setChoosing(null)} - onContinue={() => authorize.mutate({ serverId, action: choosing })} + onContinue={() => { + consent.claim(); + authorize.mutate({ serverId, action: choosing }); + }} sentence={consentCopy(choosing, consentActions).sentence} /> ) : null} diff --git a/app/src/lib/api/generated/connections/connections.zod.ts b/app/src/lib/api/generated/connections/connections.zod.ts index 432df4ad43..cf6d3ccbc4 100644 --- a/app/src/lib/api/generated/connections/connections.zod.ts +++ b/app/src/lib/api/generated/connections/connections.zod.ts @@ -290,10 +290,10 @@ export const connectAppBodyValuesMaxOne = 16384; export const ConnectAppBody = zod.object({ returnTo: zod - .enum(["connections", "apps", "desktop", "mobile"]) + .enum(["connections", "apps", "desktop", "mobile", "window"]) .default(connectAppBodyReturnToDefault) .describe( - "Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection. Never an address. A client sends mobile only where getDeployment says mobileConnections.", + "Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection; window, a page that needs no sign-in and closes the window the sign-in ran in, for OpenBot embedded in another app's page, which opened that window and reads the connection again once the person is back. Never an address. A client sends mobile only where getDeployment says mobileConnections, and window only where it says windowConnections.", ), anotherAccount: zod .boolean() @@ -795,10 +795,10 @@ export const AuthorizeConnectionActionBody = zod.object({ "The action's name, exactly as getConnectionAuthorizations lists it.", ), returnTo: zod - .enum(["connections", "apps", "desktop", "mobile"]) + .enum(["connections", "apps", "desktop", "mobile", "window"]) .default(authorizeConnectionActionBodyReturnToDefault) .describe( - "Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection. Never an address. A client sends mobile only where getDeployment says mobileConnections.", + "Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection; window, a page that needs no sign-in and closes the window the sign-in ran in, for OpenBot embedded in another app's page, which opened that window and reads the connection again once the person is back. Never an address. A client sends mobile only where getDeployment says mobileConnections, and window only where it says windowConnections.", ), }); @@ -1194,10 +1194,10 @@ export const connectSharedAppBodyValuesMaxOne = 16384; export const ConnectSharedAppBody = zod.object({ returnTo: zod - .enum(["apps", "desktop"]) + .enum(["apps", "desktop", "window"]) .default(connectSharedAppBodyReturnToDefault) .describe( - "Which of OpenBot's own pages the app sends the administrator back to: apps, the app's page for administrators; desktop, back to OpenBot Desktop. Never an address.", + "Which of OpenBot's own pages the app sends the administrator back to: apps, the app's page for administrators; desktop, back to OpenBot Desktop; window, a page that needs no sign-in and closes the window the sign-in ran in (see ConnectionReturnTo). Never an address. A client sends window only where getDeployment says windowConnections.", ), values: zod .record(zod.string(), zod.string().max(connectSharedAppBodyValuesMaxOne)) @@ -1589,10 +1589,10 @@ export const AuthorizeSharedConnectionActionBody = zod.object({ "The action's name, exactly as getConnectionAuthorizations lists it.", ), returnTo: zod - .enum(["connections", "apps", "desktop", "mobile"]) + .enum(["connections", "apps", "desktop", "mobile", "window"]) .default(authorizeSharedConnectionActionBodyReturnToDefault) .describe( - "Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection. Never an address. A client sends mobile only where getDeployment says mobileConnections.", + "Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection; window, a page that needs no sign-in and closes the window the sign-in ran in, for OpenBot embedded in another app's page, which opened that window and reads the connection again once the person is back. Never an address. A client sends mobile only where getDeployment says mobileConnections, and window only where it says windowConnections.", ), }); diff --git a/app/src/lib/api/generated/model/connectionReturnTo.ts b/app/src/lib/api/generated/model/connectionReturnTo.ts index b257bcc570..c14cc49c84 100644 --- a/app/src/lib/api/generated/model/connectionReturnTo.ts +++ b/app/src/lib/api/generated/model/connectionReturnTo.ts @@ -3,7 +3,7 @@ */ /** - * Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection. Never an address. A client sends mobile only where getDeployment says mobileConnections. + * Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection; window, a page that needs no sign-in and closes the window the sign-in ran in, for OpenBot embedded in another app's page, which opened that window and reads the connection again once the person is back. Never an address. A client sends mobile only where getDeployment says mobileConnections, and window only where it says windowConnections. */ export type ConnectionReturnTo = (typeof ConnectionReturnTo)[keyof typeof ConnectionReturnTo]; @@ -13,4 +13,5 @@ export const ConnectionReturnTo = { apps: "apps", desktop: "desktop", mobile: "mobile", + window: "window", } as const; diff --git a/app/src/lib/api/generated/model/deployment.ts b/app/src/lib/api/generated/model/deployment.ts index ce29ccc182..608a2e49a8 100644 --- a/app/src/lib/api/generated/model/deployment.ts +++ b/app/src/lib/api/generated/model/deployment.ts @@ -26,6 +26,8 @@ export interface Deployment { runStop?: boolean; /** Whether an app's sign-in page can send the person back to OpenBot Mobile (returnTo mobile on connectApp), so the phone can connect their apps. Absent from a server older than it. */ mobileConnections?: boolean; + /** Whether an app's sign-in page can send the person back to a page that closes the window it ran in (returnTo window on connectApp, connectSharedApp and authorizeAction), so OpenBot embedded in another app's page can open the sign-in in a window of its own and stay where it is. Absent from a server older than it. */ + windowConnections?: boolean; /** Whether conversations are kept between restarts. */ durableHistory: boolean; /** The social sign-ins offered, by id. */ diff --git a/app/src/lib/api/generated/model/sharedConnectionReturnTo.ts b/app/src/lib/api/generated/model/sharedConnectionReturnTo.ts index 28e8283533..e1de29d9bd 100644 --- a/app/src/lib/api/generated/model/sharedConnectionReturnTo.ts +++ b/app/src/lib/api/generated/model/sharedConnectionReturnTo.ts @@ -3,7 +3,7 @@ */ /** - * Which of OpenBot's own pages the app sends the administrator back to: apps, the app's page for administrators; desktop, back to OpenBot Desktop. Never an address. + * Which of OpenBot's own pages the app sends the administrator back to: apps, the app's page for administrators; desktop, back to OpenBot Desktop; window, a page that needs no sign-in and closes the window the sign-in ran in (see ConnectionReturnTo). Never an address. A client sends window only where getDeployment says windowConnections. */ export type SharedConnectionReturnTo = (typeof SharedConnectionReturnTo)[keyof typeof SharedConnectionReturnTo]; @@ -11,4 +11,5 @@ export type SharedConnectionReturnTo = export const SharedConnectionReturnTo = { apps: "apps", desktop: "desktop", + window: "window", } as const; diff --git a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts index a2d43a4d7d..134a9db922 100644 --- a/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts +++ b/app/src/lib/api/generated/organization-settings/organization-settings.zod.ts @@ -77,6 +77,12 @@ export const GetDeploymentResponse = zod .describe( "Whether an app's sign-in page can send the person back to OpenBot Mobile (returnTo mobile on connectApp), so the phone can connect their apps. Absent from a server older than it.", ), + windowConnections: zod + .boolean() + .optional() + .describe( + "Whether an app's sign-in page can send the person back to a page that closes the window it ran in (returnTo window on connectApp, connectSharedApp and authorizeAction), so OpenBot embedded in another app's page can open the sign-in in a window of its own and stay where it is. Absent from a server older than it.", + ), durableHistory: zod .boolean() .describe("Whether conversations are kept between restarts."), diff --git a/app/src/lib/connections/connect-app.ts b/app/src/lib/connections/connect-app.ts index 3c89fdad79..3bcb732a3f 100644 --- a/app/src/lib/connections/connect-app.ts +++ b/app/src/lib/connections/connect-app.ts @@ -8,6 +8,7 @@ import { connectAccountMutationOptions, invalidatePlugins, } from "@/lib/plugins/mutations"; +import { useConsentTab } from "@/lib/plugins/consent-tab"; import { connectionsQueryOptions } from "@/lib/plugins/queries"; /** @@ -31,6 +32,8 @@ export function useConnectApp( const navigate = useNavigate(); const add = useMutation(addCuratedServerMutationOptions(queryClient)); const connect = useMutation(connectAccountMutationOptions("settings")); + // Embedded in another app's page, the sign-in opens in a tab of its own (lib/plugins/consent-tab.ts). + const consent = useConsentTab(); const [pending, setPending] = useState(null); // The refusal itself, not its words: a hold is drawn calmly (`failureSaid`). const [error, setError] = useState(null); @@ -46,6 +49,8 @@ export function useConnectApp( async function run(key: string, action: "connect" | "add") { setError(null); setPending(key); + // Claimed on the press: adding the app and asking for its sign-in come first. + if (action === "connect") consent.claim(); try { if (!(await freshServer(key))) await add.mutateAsync({ key }); if (action === "add") { @@ -59,7 +64,7 @@ export function useConnectApp( } const start = await connect.mutateAsync(key); if (start && "authorizationUrl" in start) { - window.location.href = start.authorizationUrl; + consent.go(start.authorizationUrl); return; } await queryClient.invalidateQueries({ @@ -68,6 +73,8 @@ export function useConnectApp( } catch (thrown) { setError(failureOf(thrown, "Couldn't connect that app.")); } finally { + // A tab claimed for a press that opened no sign-in (refused, a form first, connected at once). + consent.drop(); setPending(null); } } diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 20dd1f3ba2..087bac9866 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -58,6 +58,12 @@ export type DeploymentCapabilities = { * what they use most of Admin under Settings too. A server from before the switch reads as `team`. */ edition: "team" | "personal"; + /** + * Whether an app's sign-in can come back to a page that closes the window it ran in + * (`returnTo: window`), which OpenBot embedded in another app's page asks for + * (lib/plugins/consent-tab.ts). Absent from a server older than it. + */ + windowConnections?: boolean; transcription?: boolean; voice?: boolean; /** Whether a Bot can run inside OpenBot, with no address of its own. */ @@ -386,6 +392,7 @@ export function deploymentCapabilitiesQueryOptions() { runPartsByReference: body.runPartsByReference === true, runStateByReference: body.runStateByReference === true, managedWindowsComputers: body.managedWindowsComputers === true, + windowConnections: body.windowConnections === true, }; }, }); diff --git a/app/src/lib/plugins/confirm-on-return.ts b/app/src/lib/plugins/confirm-on-return.ts index edf0f37358..c8cd4aa2f5 100644 --- a/app/src/lib/plugins/confirm-on-return.ts +++ b/app/src/lib/plugins/confirm-on-return.ts @@ -1,6 +1,7 @@ import type { QueryClient } from "@tanstack/react-query"; import { appSetupQueryOptions, appsQueryOptions } from "@/lib/apps/queries"; import { desktopShell } from "@/lib/desktop/shell"; +import { embedConfig } from "@/lib/embed/config"; import { fromDirectory } from "./provider-vocabulary"; import { pluginKeys } from "./queries"; @@ -12,6 +13,9 @@ let client: QueryClient | null = null; /** * Confirm an app's consent once OpenBot Desktop's window is back in front, whatever screen it is on. + * The same for OpenBot embedded in another app's page, where the consent ran in a tab of its own + * (lib/plugins/consent-tab.ts) that comes back to a page that closes it: the host page has the + * focus again once the person is done there. * * The window sends the consent to the person's default browser, and that browser comes back to * `/desktop-return`, which is not signed in and asks the API nothing. So the window, which is signed @@ -30,7 +34,7 @@ export function confirmOnReturn( serverId: string, confirm: () => Promise, ): void { - if (!desktopShell()) return; + if (!desktopShell() && embedConfig() === undefined) return; pending.set(serverId, confirm); client = queryClient; // One listener for every consent waiting, on whichever window this is. diff --git a/app/src/lib/plugins/consent-tab.ts b/app/src/lib/plugins/consent-tab.ts new file mode 100644 index 0000000000..0e2bd59c9a --- /dev/null +++ b/app/src/lib/plugins/consent-tab.ts @@ -0,0 +1,120 @@ +import type { QueryClient } from "@tanstack/react-query"; +import { useMemo } from "react"; +import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; +import { embedConfig } from "@/lib/embed/config"; +import { pluginKeys } from "@/lib/plugins/queries"; + +/** + * WHERE AN APP'S SIGN-IN OPENS, EMBEDDED IN ANOTHER APP'S PAGE. + * + * In OpenBot's own tab a screen sends that tab to the vendor's sign-in, and the vendor sends it back + * to OpenBot. Embedded (lib/embed/config.ts), that tab is the host app's page: the sign-in took it + * over, and the vendor brought the person back to OpenBot's public address, where somebody signed in + * through the host has no session, so they ended on a sign-in screen, out of the app they were using. + * + * So, embedded, the sign-in opens in a tab of its own and the host page stays where it is. The tab is + * claimed on the click (`claim`), because a browser only lets a page open one while a click is + * recent, and asking the server for the sign-in's address comes first (as `useConnectInNewTab` + * claims its tab). The vendor sends that tab back to a page that closes it (`returnTo: window`, + * {@link connectsInWindow}), and when the person is back the screens read the connection again + * (`confirmOnReturn`). + * + * Not embedded, `claim` does nothing and `go` sends this page to the sign-in, as before. + */ +export type ConsentTab = { + /** On the click itself: claim the tab the sign-in will open in, embedded. */ + claim(): void; + /** Send the person to the sign-in: the claimed tab, a new one, or this page when not embedded. */ + go(url: string): void; + /** The press ended with no sign-in to open (refused, or connected at once): close the claimed tab. */ + drop(): void; +}; + +/** What a consent tab needs of the browser, replaced in tests. */ +export type ConsentTabWindow = { + embedded(): boolean; + /** `window.open(url, "_blank")`: the tab, or null when the browser blocked it. */ + open(url: string): Window | null; + /** Send this page to `url`. */ + navigate(url: string): void; +}; + +const browserWindow: ConsentTabWindow = { + embedded: () => embedConfig() !== undefined, + open: (url) => window.open(url, "_blank"), + navigate: (url) => { + window.location.href = url; + }, +}; + +export function createConsentTab( + win: ConsentTabWindow = browserWindow, +): ConsentTab { + let claimed: Window | null = null; + /* + * `noopener` can't be passed to `open`: it makes it answer null, which can't be told from a + * blocked tab and can't be navigated later. The opener is severed on the handle instead, so the + * vendor's page can't reach back into the host page. + */ + const openTab = (url: string): Window | null => { + const tab = win.open(url); + if (tab) tab.opener = null; + return tab; + }; + return { + claim() { + if (!win.embedded()) return; + claimed?.close(); + claimed = openTab(""); + }, + go(url) { + if (!win.embedded()) { + win.navigate(url); + return; + } + const tab = claimed; + claimed = null; + if (tab && !tab.closed) { + tab.location.replace(url); + return; + } + /* + * BLOCKED, THE SIGN-IN STILL OPENS. A browser that refused the tab on the click may let one + * open now; one that refuses again leaves only this page, which is how the sign-in always + * opened, and better than a press that does nothing. + */ + if (!openTab(url)) win.navigate(url); + }, + drop() { + claimed?.close(); + claimed = null; + }, + }; +} + +/** One consent tab per screen, for the screen's presses. */ +export function useConsentTab(): ConsentTab { + return useMemo(() => createConsentTab(), []); +} + +/** + * Whether this press asks the vendor to send the person back to a page that closes the sign-in's + * window (`returnTo: window`): embedded, and only where the server says it has that page + * (`windowConnections`). A server older than it has none, and the sign-in comes back to OpenBot's + * own pages as before, in the tab of its own. + */ +export async function connectsInWindow( + queryClient: QueryClient, +): Promise { + if (embedConfig() === undefined) return false; + const capabilities = await queryClient + // Cached for good once read (configuration, not data), so this asks the server once. + .fetchQuery(deploymentCapabilitiesQueryOptions()) + .catch(() => null); + return capabilities?.windowConnections === true; +} + +/** Read every plugin list again, as a screen does once the person is back from a sign-in. */ +export function readConnectionsAgain(queryClient: QueryClient): Promise { + return queryClient.invalidateQueries({ queryKey: pluginKeys.all }); +} diff --git a/app/src/lib/plugins/grants.ts b/app/src/lib/plugins/grants.ts index 593cbead97..50b3319a77 100644 --- a/app/src/lib/plugins/grants.ts +++ b/app/src/lib/plugins/grants.ts @@ -1,4 +1,8 @@ -import { mutationOptions, queryOptions } from "@tanstack/react-query"; +import { + type MutationFunctionContext, + mutationOptions, + queryOptions, +} from "@tanstack/react-query"; import { authorizeConnectionAction, authorizeSharedConnectionAction, @@ -8,6 +12,7 @@ import { import type { ActionAuthorizations } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { desktopShell } from "@/lib/desktop/shell"; +import { connectsInWindow } from "./consent-tab"; import type { ConsentAction } from "./enablement-notes"; /** @@ -86,17 +91,24 @@ export function authorizeActionMutationOptions( shared = false, ) { return mutationOptions({ - mutationFn: async (variables: { - serverId: string; - action: string; - }): Promise => { + mutationFn: async ( + variables: { + serverId: string; + action: string; + }, + context: MutationFunctionContext, + ): Promise => { + // Embedded, the consent opens in a window of its own and comes back to a page that closes it. + const inWindow = await connectsInWindow(context.client); const body = { action: variables.action, returnTo: desktopShell() ? ("desktop" as const) - : returnTo === "admin" - ? ("apps" as const) - : ("connections" as const), + : inWindow + ? ("window" as const) + : returnTo === "admin" + ? ("apps" as const) + : ("connections" as const), }; const headers = { "Idempotency-Key": idempotencyKey() }; const options = { fallback: "Couldn't authorize that action." }; diff --git a/app/src/lib/plugins/mutations.ts b/app/src/lib/plugins/mutations.ts index 3b4f93ecb4..86a17d1e9c 100644 --- a/app/src/lib/plugins/mutations.ts +++ b/app/src/lib/plugins/mutations.ts @@ -29,6 +29,7 @@ import { ClientError } from "@/lib/client"; import { desktopShell } from "@/lib/desktop/shell"; import { enterpriseKeys } from "@/lib/enterprise/queries"; import { teamGrantKeys } from "@/lib/team-grants/queries"; +import { connectsInWindow } from "./consent-tab"; import { confirmOnReturn } from "./confirm-on-return"; import { pluginKeys } from "./queries"; import { type SharedUseApproval, sharedUseKeys } from "./shared-use"; @@ -266,6 +267,7 @@ export function connectAccountMutationOptions( await startConnect(serverId, { returnTo, shared, + inWindow: await connectsInWindow(context.client), fallback: "Couldn't connect that account.", }), ), @@ -294,6 +296,7 @@ export function connectAnotherAccountMutationOptions( await startConnect(serverId, { returnTo, another: true, + inWindow: await connectsInWindow(context.client), fallback: "Couldn't connect that account.", }), ), @@ -323,7 +326,8 @@ function confirmedOnReturn( /** * One press of Connect, at the person's own connection or, for a Shared app, the app's shared one. * Where the person comes back to is one of OpenBot's own pages: the app's page for admins, the - * person's connection page, or OpenBot Desktop when the press came from its window. + * person's connection page, OpenBot Desktop when the press came from its window, or, embedded in + * another app's page, a page that closes the sign-in's own window (`inWindow`, lib/plugins/consent-tab.ts). */ function startConnect( serverId: string, @@ -332,6 +336,7 @@ function startConnect( fallback: string; shared?: boolean; another?: boolean; + inWindow?: boolean; values?: Record; }, ): Promise { @@ -342,7 +347,11 @@ function startConnect( organizationId(), serverId, { - returnTo: desktopShell() ? "desktop" : "apps", + returnTo: desktopShell() + ? "desktop" + : press.inWindow + ? "window" + : "apps", ...(press.values ? { values: press.values } : {}), }, headers, @@ -351,9 +360,11 @@ function startConnect( const body: ConnectAppRequest = { returnTo: desktopShell() ? "desktop" - : press.returnTo === "admin" - ? "apps" - : "connections", + : press.inWindow + ? "window" + : press.returnTo === "admin" + ? "apps" + : "connections", ...(press.another ? { anotherAccount: true } : {}), ...(press.values ? { values: press.values } : {}), }; diff --git a/app/src/routes/_authed/_app/connections.$key.tsx b/app/src/routes/_authed/_app/connections.$key.tsx index 572d91d1c1..e398d64f0c 100644 --- a/app/src/routes/_authed/_app/connections.$key.tsx +++ b/app/src/routes/_authed/_app/connections.$key.tsx @@ -77,6 +77,7 @@ import { type PluginServer, personalConnections, } from "@/lib/plugins/queries"; +import { useConsentTab } from "@/lib/plugins/consent-tab"; import { searchTextEntry } from "@/lib/search-text"; /** @@ -283,9 +284,14 @@ function AppConnectionPage({ // A refusal is kept whole, not as its words, so a hold is drawn calmly (`failureSaid`). const [notice, setNotice] = useState(null); + // Embedded in another app's page, the sign-in opens in a tab of its own (lib/plugins/consent-tab.ts). + const consent = useConsentTab(); const connect = useMutation({ ...connectAccountMutationOptions(), - onError: (thrown: Error) => setNotice(thrown), + onError: (thrown: Error) => { + consent.drop(); + setNotice(thrown); + }, /* * A full page navigation, not a fetch. The consent screen is the vendor's own and has to be shown * to you in your own browser; there is deliberately nothing here that could complete it for you. @@ -306,13 +312,14 @@ function AppConnectionPage({ ? start.authorizationUrl : null; if (authorizationUrl === null) { + consent.drop(); setNotice({ message: "Couldn't start connecting, so nothing was connected. Try again, or ask an admin if it keeps happening.", }); return; } - window.location.href = authorizationUrl; + consent.go(authorizationUrl); }, }); @@ -912,6 +919,7 @@ function AppConnectionPage({ disabled={connect.isPending} onClick={() => { setNotice(null); + consent.claim(); connect.mutate(key); }} size="sm" @@ -981,8 +989,10 @@ function AppConnectionPage({ } onClick={() => { setNotice(null); - if (enabled) connect.mutate(key); - else void connectApp.run(key, "connect"); + if (enabled) { + consent.claim(); + connect.mutate(key); + } else void connectApp.run(key, "connect"); }} size="sm" type="button" diff --git a/app/tests/embedded-consent-window.test.ts b/app/tests/embedded-consent-window.test.ts new file mode 100644 index 0000000000..2568a76045 --- /dev/null +++ b/app/tests/embedded-consent-window.test.ts @@ -0,0 +1,219 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClient } from "@tanstack/react-query"; +import { configureEmbed, resetEmbedForTests } from "@/lib/embed/config"; +import { setCurrentOrganization } from "@/lib/organizations/current"; +import { createConsentTab } from "@/lib/plugins/consent-tab"; +import { authorizeActionMutationOptions } from "@/lib/plugins/grants"; +import { connectAccountMutationOptions } from "@/lib/plugins/mutations"; + +/** + * Embedded in another app's page, OpenBot opens an app's sign-in in a window of its own and asks + * the vendor to send the person back to a page that closes it (`returnTo: window`), so the host page + * stays where it is. Before this, the sign-in took over the host page, and the vendor sent the + * person to OpenBot's public address, where somebody signed in through the host has no session: a + * sign-in screen, out of the app they were using. + */ + +beforeAll(() => GlobalRegistrator.register()); +afterAll(() => GlobalRegistrator.unregister()); + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; + resetEmbedForTests(); +}); + +const getAssertion = async () => "assertion"; +const START = "https://vendor.example.com/authorize?state=s"; + +/** A server that offers (or not) `windowConnections`, recording each connect and authorize body. */ +function server(offersWindow: boolean) { + const bodies: { path: string; body: Record }[] = []; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL( + typeof input === "string" || input instanceof URL ? input : input.url, + "https://openbot.example.com", + ); + const json = (body: unknown) => + new Response(JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json" }, + }); + if (url.pathname.endsWith("/deployment")) + return json({ + generativeUi: false, + selfHostBanner: false, + localEvaluation: false, + edition: "team", + ...(offersWindow ? { windowConnections: true } : {}), + }); + if (init?.method === "POST") { + bodies.push({ + path: url.pathname, + body: JSON.parse(String(init.body ?? "{}")), + }); + if (url.pathname.includes("/authorize")) + return json({ authorizationUrl: START }); + return json({ next: "consent", authorizationUrl: START }); + } + return new Response("not found", { status: 404 }); + }) as typeof fetch; + return bodies; +} + +function embed() { + configureEmbed({ apiBaseUrl: "https://openbot.example.com", getAssertion }); +} + +async function connect(returnTo: "settings" | "admin", shared = false) { + setCurrentOrganization("default"); + const options = connectAccountMutationOptions(returnTo, shared); + const client = new QueryClient(); + return options.mutationFn?.("gmail", { client, meta: undefined }); +} + +test("embedded, and offered, a connect asks to come back to a page that closes its window", async () => { + const bodies = server(true); + embed(); + await connect("settings"); + expect(bodies.at(-1)?.body.returnTo).toBe("window"); +}); + +test("embedded, an administrator's connect of an app's shared account comes back the same way", async () => { + const bodies = server(true); + embed(); + await connect("admin", true); + expect(bodies.at(-1)?.body.returnTo).toBe("window"); +}); + +test("embedded, an action's consent comes back the same way", async () => { + const bodies = server(true); + embed(); + setCurrentOrganization("default"); + const options = authorizeActionMutationOptions("settings"); + await options.mutationFn?.( + { serverId: "gmail", action: "send" }, + { client: new QueryClient(), meta: undefined }, + ); + expect(bodies.at(-1)?.body.returnTo).toBe("window"); +}); + +test("not embedded, a connect comes back to OpenBot's own pages as before", async () => { + const bodies = server(true); + await connect("settings"); + expect(bodies.at(-1)?.body.returnTo).toBe("connections"); + await connect("admin"); + expect(bodies.at(-1)?.body.returnTo).toBe("apps"); +}); + +test("embedded, against a server that doesn't offer it, a connect never sends window", async () => { + const bodies = server(false); + embed(); + await connect("settings"); + expect(bodies.at(-1)?.body.returnTo).toBe("connections"); +}); + +/** A stand-in window: what it was told to open, and the tabs it handed out. */ +function fakeWindow(blocked = false) { + const opened: { url: string; tab: FakeTab }[] = []; + const page = { href: "https://host.example.com/apps" }; + return { + opened, + page, + open: (url: string) => { + if (blocked) return null; + const tab = new FakeTab(url); + opened.push({ url, tab }); + return tab as unknown as Window; + }, + navigate: (url: string) => { + page.href = url; + }, + }; +} + +class FakeTab { + closed = false; + opener: unknown = "host"; + replacedWith: string | null = null; + constructor(public url: string) {} + location = { replace: (url: string) => (this.replacedWith = url) }; + close() { + this.closed = true; + } +} + +test("embedded, the consent tab is claimed on the click and sent to the sign-in, and the host page stays", () => { + const win = fakeWindow(); + const consent = createConsentTab({ embedded: () => true, ...win }); + consent.claim(); + expect(win.opened).toHaveLength(1); + expect(win.opened[0]?.url).toBe(""); + // The sign-in's window can't reach back into the host page. + expect(win.opened[0]?.tab.opener).toBeNull(); + consent.go(START); + expect(win.opened[0]?.tab.replacedWith).toBe(START); + expect(win.page.href).toBe("https://host.example.com/apps"); +}); + +test("embedded, a sign-in with no tab claimed opens one of its own, and the host page stays", () => { + const win = fakeWindow(); + const consent = createConsentTab({ embedded: () => true, ...win }); + consent.go(START); + expect(win.opened.map((o) => o.url)).toEqual([START]); + expect(win.page.href).toBe("https://host.example.com/apps"); +}); + +test("embedded, a claimed tab is closed when the press is refused or needs no sign-in", () => { + const win = fakeWindow(); + const consent = createConsentTab({ embedded: () => true, ...win }); + consent.claim(); + consent.drop(); + expect(win.opened[0]?.tab.closed).toBe(true); +}); + +test("embedded and blocked, the sign-in still opens, in the host page, as before", () => { + const win = fakeWindow(true); + const consent = createConsentTab({ embedded: () => true, ...win }); + consent.claim(); + consent.go(START); + expect(win.page.href).toBe(START); +}); + +test("not embedded, nothing is claimed and the page goes to the sign-in as before", () => { + const win = fakeWindow(); + const consent = createConsentTab({ embedded: () => false, ...win }); + consent.claim(); + expect(win.opened).toHaveLength(0); + consent.go(START); + expect(win.page.href).toBe(START); +}); + +/* + * Every screen that sends a person to an app's sign-in goes through the consent tab, so a new one + * can't take over the host page again. A scan, as relative-api-paths.test.ts scans for addresses. + */ +const SRC = join(import.meta.dir, "..", "src"); +const CONSENT_SCREENS = [ + "components/connections/add-server-page.tsx", + "components/manage/plugin-page.tsx", + "components/plugins/brokered-account-row.tsx", + "components/plugins/grant-list.tsx", + "lib/connections/connect-app.ts", + "routes/_authed/_app/connections.$key.tsx", +]; +const LEAVES_FOR_CONSENT = + /window\.location\.href\s*=\s*(?:start\.authorizationUrl|authorizationUrl|handoff\.url)\b/; + +test("no screen sends its own page to an app's sign-in", () => { + for (const file of CONSENT_SCREENS) { + const source = readFileSync(join(SRC, file), "utf8"); + expect({ file, leaves: LEAVES_FOR_CONSENT.test(source) }).toEqual({ + file, + leaves: false, + }); + } +}); diff --git a/docs/configuration.md b/docs/configuration.md index 77dd74ab3a..5b0e067e67 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -830,6 +830,14 @@ sign-in routes, not only the embedded one, so list only host pages you control. **Switching people.** When the host signs a different person into the same browser, the previous person's session and their Recorders end. +**Connecting apps.** Embedded, an app's sign-in opens in a tab of its own, and the host page stays +where it is. When the person is done, the app sends them back to a page on OpenBot's public address +that needs no sign-in and closes the tab (`returnTo: window`), and the embedded app reads the +connection again once the person is back. The host page must let the browser open that tab: a +`sandbox` on a frame around it needs `allow-popups`. Through Composio, the step OpenBot shows before +the sign-in is left out when embedded, because no page of OpenBot's runs on the host's origin to show +it. + **Check a token.** Before wiring up a host, check one against the same rules: ```sh diff --git a/mobile/src/api/generated/model/connectionReturnTo.ts b/mobile/src/api/generated/model/connectionReturnTo.ts index b257bcc570..c14cc49c84 100644 --- a/mobile/src/api/generated/model/connectionReturnTo.ts +++ b/mobile/src/api/generated/model/connectionReturnTo.ts @@ -3,7 +3,7 @@ */ /** - * Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection. Never an address. A client sends mobile only where getDeployment says mobileConnections. + * Which of OpenBot's own pages the app sends the person back to: connections, the person's own page for the app; apps, the app's page for administrators; desktop, back to OpenBot Desktop; mobile, back to OpenBot Mobile, which then calls confirmConnection; window, a page that needs no sign-in and closes the window the sign-in ran in, for OpenBot embedded in another app's page, which opened that window and reads the connection again once the person is back. Never an address. A client sends mobile only where getDeployment says mobileConnections, and window only where it says windowConnections. */ export type ConnectionReturnTo = (typeof ConnectionReturnTo)[keyof typeof ConnectionReturnTo]; @@ -13,4 +13,5 @@ export const ConnectionReturnTo = { apps: "apps", desktop: "desktop", mobile: "mobile", + window: "window", } as const; diff --git a/mobile/src/api/generated/model/deployment.ts b/mobile/src/api/generated/model/deployment.ts index ce29ccc182..608a2e49a8 100644 --- a/mobile/src/api/generated/model/deployment.ts +++ b/mobile/src/api/generated/model/deployment.ts @@ -26,6 +26,8 @@ export interface Deployment { runStop?: boolean; /** Whether an app's sign-in page can send the person back to OpenBot Mobile (returnTo mobile on connectApp), so the phone can connect their apps. Absent from a server older than it. */ mobileConnections?: boolean; + /** Whether an app's sign-in page can send the person back to a page that closes the window it ran in (returnTo window on connectApp, connectSharedApp and authorizeAction), so OpenBot embedded in another app's page can open the sign-in in a window of its own and stay where it is. Absent from a server older than it. */ + windowConnections?: boolean; /** Whether conversations are kept between restarts. */ durableHistory: boolean; /** The social sign-ins offered, by id. */ diff --git a/mobile/src/api/generated/model/sharedConnectionReturnTo.ts b/mobile/src/api/generated/model/sharedConnectionReturnTo.ts index 28e8283533..e1de29d9bd 100644 --- a/mobile/src/api/generated/model/sharedConnectionReturnTo.ts +++ b/mobile/src/api/generated/model/sharedConnectionReturnTo.ts @@ -3,7 +3,7 @@ */ /** - * Which of OpenBot's own pages the app sends the administrator back to: apps, the app's page for administrators; desktop, back to OpenBot Desktop. Never an address. + * Which of OpenBot's own pages the app sends the administrator back to: apps, the app's page for administrators; desktop, back to OpenBot Desktop; window, a page that needs no sign-in and closes the window the sign-in ran in (see ConnectionReturnTo). Never an address. A client sends window only where getDeployment says windowConnections. */ export type SharedConnectionReturnTo = (typeof SharedConnectionReturnTo)[keyof typeof SharedConnectionReturnTo]; @@ -11,4 +11,5 @@ export type SharedConnectionReturnTo = export const SharedConnectionReturnTo = { apps: "apps", desktop: "desktop", + window: "window", } as const; From 90f1f28b9ad1e876c0987bdc0ff631cd94920f0d Mon Sep 17 00:00:00 2001 From: Maxim Date: Thu, 3 Dec 2026 21:39:35 +0100 Subject: [PATCH 2/3] Embedded: ask for the closing page only with a tab held, and confirm until connected From review: - returnTo window only while a tab claimed on the press is there for the sign-in. With none (the browser blocked it, or the page started the press itself) the sign-in opens in the host page, which a page that closes its tab could not close, so it comes back to OpenBot's own pages as before. A tab the person closed before the sign-in was ready opens a new one, never the host page. - Never for apps authorized action by action: that consent ends at OpenBot's verifier, which needs the person's session. - Embedded, a confirm answered "not connected" is asked again at the next return, for up to fifteen minutes, so coming back to the host page before finishing no longer loses the account. - Admin's app page claims only for an app reached as you, and lets go of the tab where reading the catalogue fails. Co-Authored-By: Claude Opus 5.5 --- app/src/components/manage/plugin-page.tsx | 28 +++++--- app/src/lib/plugins/confirm-on-return.ts | 67 +++++++++++++---- app/src/lib/plugins/consent-tab.ts | 79 +++++++++++++++----- app/tests/embedded-consent-window.test.ts | 88 ++++++++++++++++++++++- app/tests/plugin-mutation-refresh.test.ts | 3 +- 5 files changed, 224 insertions(+), 41 deletions(-) diff --git a/app/src/components/manage/plugin-page.tsx b/app/src/components/manage/plugin-page.tsx index 753eb2037a..4a7ae3801a 100644 --- a/app/src/components/manage/plugin-page.tsx +++ b/app/src/components/manage/plugin-page.tsx @@ -680,10 +680,18 @@ export function PluginPage({ setDialog("instance"); return; } - // Claimed on the click: adding it and reading the catalogue come before the sign-in. - consent.claim(); - if (await add()) await signInOnceAdded(); - else consent.drop(); + /* + * Claimed on the click, for an app reached as you: adding it and reading the catalogue come + * before the sign-in. Let go of where nothing opens one, a refusal or a failed read among them. + */ + if (auth === "user-oauth") consent.claim(); + try { + if (await add()) await signInOnceAdded(); + else consent.drop(); + } catch (thrown) { + consent.drop(); + throw thrown; + } }; /** What is left once Connect has added it, for an app reached as you: the sign-in. */ @@ -1921,11 +1929,13 @@ export function PluginPage({ onClick={() => { if (!server) { // Opened by Connect: Save adds it, and an app reached as you goes on to its sign-in. - consent.claim(); - void add().then((added) => { - if (added) return signInOnceAdded(); - consent.drop(); - }); + if (auth === "user-oauth") consent.claim(); + void add() + .then((added) => { + if (added) return signInOnceAdded(); + consent.drop(); + }) + .catch(() => consent.drop()); return; } if (dialog === "client") { diff --git a/app/src/lib/plugins/confirm-on-return.ts b/app/src/lib/plugins/confirm-on-return.ts index c8cd4aa2f5..aff6298810 100644 --- a/app/src/lib/plugins/confirm-on-return.ts +++ b/app/src/lib/plugins/confirm-on-return.ts @@ -5,8 +5,20 @@ import { embedConfig } from "@/lib/embed/config"; import { fromDirectory } from "./provider-vocabulary"; import { pluginKeys } from "./queries"; -/** The consents waiting for the window to be back in front, by app key, with how each is confirmed. */ -const pending = new Map Promise>(); +/** + * The consents waiting for the window to be back in front, by app key: how each is confirmed, and, + * embedded, until when it is asked again. + */ +const pending = new Map< + string, + { confirm: () => Promise; until: number } +>(); + +/** + * How long an embedded consent is asked about again at each return, while the vendor's answer is + * still "not connected": as long as a person takes over a sign-in, and no longer. + */ +const EMBEDDED_WAIT_MS = 15 * 60_000; /** The client the last consent was started through, which refreshes the lists afterwards. */ let client: QueryClient | null = null; @@ -35,13 +47,25 @@ export function confirmOnReturn( confirm: () => Promise, ): void { if (!desktopShell() && embedConfig() === undefined) return; - pending.set(serverId, confirm); + pending.set(serverId, { confirm, until: Date.now() + EMBEDDED_WAIT_MS }); client = queryClient; - // One listener for every consent waiting, on whichever window this is. + listen(); +} + +/** One listener for every consent waiting, on whichever window this is. */ +function listen(): void { window.removeEventListener("focus", confirmPending); window.addEventListener("focus", confirmPending, { once: true }); } +/** Whether a confirm's answer says the account is there. */ +function connected(answer: PromiseSettledResult): boolean { + return ( + answer.status === "fulfilled" && + (answer.value as { connected?: unknown } | null)?.connected === true + ); +} + async function confirmPending(): Promise { const queryClient = client; const waiting = [...pending.entries()]; @@ -63,14 +87,33 @@ async function confirmPending(): Promise { const apps = await queryClient .fetchQuery(appsQueryOptions()) .catch(() => null); - const confirms = waiting - .filter( - ([serverId]) => - apps === null || - apps.some((app) => app.id === serverId && fromDirectory(app)), - ) - .map(([, ask]) => ask); + const confirms = waiting.filter( + ([serverId]) => + apps === null || + apps.some((app) => app.id === serverId && fromDirectory(app)), + ); // A refusal is not the window's to report: the lists read again say whether it is connected. - await Promise.allSettled(confirms.map((ask) => ask())); + const answers = await Promise.allSettled( + confirms.map(([, entry]) => entry.confirm()), + ); + /* + * EMBEDDED, ASKED AGAIN UNTIL IT IS THERE. The sign-in ran in a tab of the same browser, and the + * person may come back to the host page before they finish there: asked then, the vendor says not + * yet, and nothing asked again once they did finish. So a consent not answered connected waits for + * the next return, until its time is up. OpenBot Desktop's window is left as it was: its consent ran + * in another app, and coming back to the window is the end of it. + */ + if (embedConfig() !== undefined) { + const now = Date.now(); + confirms.forEach(([serverId, entry], index) => { + const answer = answers[index]; + if (answer && !connected(answer) && entry.until > now) + pending.set(serverId, entry); + }); + if (pending.size > 0) { + client = queryClient; + listen(); + } + } await queryClient.invalidateQueries({ queryKey: pluginKeys.all }); } diff --git a/app/src/lib/plugins/consent-tab.ts b/app/src/lib/plugins/consent-tab.ts index 0e2bd59c9a..0e3c74268f 100644 --- a/app/src/lib/plugins/consent-tab.ts +++ b/app/src/lib/plugins/consent-tab.ts @@ -1,5 +1,6 @@ import type { QueryClient } from "@tanstack/react-query"; import { useMemo } from "react"; +import { appSetupQueryOptions } from "@/lib/apps/queries"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { embedConfig } from "@/lib/embed/config"; import { pluginKeys } from "@/lib/plugins/queries"; @@ -47,10 +48,34 @@ const browserWindow: ConsentTabWindow = { }, }; +/** + * The tabs claimed for presses and not yet sent anywhere, across every screen: what + * {@link connectsInWindow} asks, as the press's request goes out, whether a tab is there for the + * sign-in. One press is on its way at a time, so this is that press's. + */ +const held = new Set(); + +/** Whether a tab claimed on a press is open and waiting for the sign-in. */ +function holdsConsentTab(): boolean { + for (const tab of held) if (!tab.closed) return true; + return false; +} + +/** Forget every claimed tab, between tests. */ +export function resetConsentTabsForTests(): void { + held.clear(); +} + export function createConsentTab( win: ConsentTabWindow = browserWindow, ): ConsentTab { let claimed: Window | null = null; + const release = () => { + if (claimed) held.delete(claimed); + const tab = claimed; + claimed = null; + return tab; + }; /* * `noopener` can't be passed to `open`: it makes it answer null, which can't be told from a * blocked tab and can't be navigated later. The opener is severed on the handle instead, so the @@ -64,30 +89,38 @@ export function createConsentTab( return { claim() { if (!win.embedded()) return; - claimed?.close(); + release()?.close(); claimed = openTab(""); + if (claimed) held.add(claimed); }, go(url) { if (!win.embedded()) { win.navigate(url); return; } - const tab = claimed; - claimed = null; + const tab = release(); if (tab && !tab.closed) { tab.location.replace(url); return; } /* - * BLOCKED, THE SIGN-IN STILL OPENS. A browser that refused the tab on the click may let one - * open now; one that refuses again leaves only this page, which is how the sign-in always - * opened, and better than a press that does nothing. + * THE PERSON CLOSED THE TAB BEFORE THE SIGN-IN WAS READY. The request asked for the page that + * closes a tab, so the sign-in opens in a new one if the browser lets it, and never in the + * host page, which that page could not close. + */ + if (tab) { + openTab(url); + return; + } + /* + * NO TAB WAS HELD (the browser blocked it on the click, or the page started the press itself), + * so the request asked for OpenBot's own pages ({@link connectsInWindow}). The sign-in opens in + * a tab if the browser lets it now; otherwise in this page, which is how it always opened. */ if (!openTab(url)) win.navigate(url); }, drop() { - claimed?.close(); - claimed = null; + release()?.close(); }, }; } @@ -99,19 +132,33 @@ export function useConsentTab(): ConsentTab { /** * Whether this press asks the vendor to send the person back to a page that closes the sign-in's - * window (`returnTo: window`): embedded, and only where the server says it has that page - * (`windowConnections`). A server older than it has none, and the sign-in comes back to OpenBot's - * own pages as before, in the tab of its own. + * tab (`returnTo: window`). Only when all of these hold, and otherwise the sign-in comes back to + * OpenBot's own pages, as before: + * + * - Embedded in another app's page. + * - A tab claimed on the press is there for the sign-in. With none (the browser blocked it, or the + * page started the press itself) the sign-in opens in the host page, and a page that closes its + * tab could not close that one. + * - The server has that page (`windowConnections`). A server older than it does not. + * - The apps here are not authorized action by action (Arcade): that consent ends at OpenBot's + * verifier, which needs the person's session, and a tab of its own has none. */ export async function connectsInWindow( queryClient: QueryClient, ): Promise { - if (embedConfig() === undefined) return false; - const capabilities = await queryClient + if (embedConfig() === undefined || !holdsConsentTab()) return false; + const [capabilities, setup] = await Promise.all([ // Cached for good once read (configuration, not data), so this asks the server once. - .fetchQuery(deploymentCapabilitiesQueryOptions()) - .catch(() => null); - return capabilities?.windowConnections === true; + queryClient + .fetchQuery(deploymentCapabilitiesQueryOptions()) + .catch(() => null), + queryClient.fetchQuery(appSetupQueryOptions()).catch(() => null), + ]); + return ( + capabilities?.windowConnections === true && + setup !== null && + setup.authorizesPerAction !== true + ); } /** Read every plugin list again, as a screen does once the person is back from a sign-in. */ diff --git a/app/tests/embedded-consent-window.test.ts b/app/tests/embedded-consent-window.test.ts index 2568a76045..81b0ce21cb 100644 --- a/app/tests/embedded-consent-window.test.ts +++ b/app/tests/embedded-consent-window.test.ts @@ -5,7 +5,11 @@ import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClient } from "@tanstack/react-query"; import { configureEmbed, resetEmbedForTests } from "@/lib/embed/config"; import { setCurrentOrganization } from "@/lib/organizations/current"; -import { createConsentTab } from "@/lib/plugins/consent-tab"; +import { confirmOnReturn } from "@/lib/plugins/confirm-on-return"; +import { + createConsentTab, + resetConsentTabsForTests, +} from "@/lib/plugins/consent-tab"; import { authorizeActionMutationOptions } from "@/lib/plugins/grants"; import { connectAccountMutationOptions } from "@/lib/plugins/mutations"; @@ -24,13 +28,17 @@ const originalFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = originalFetch; resetEmbedForTests(); + resetConsentTabsForTests(); }); const getAssertion = async () => "assertion"; const START = "https://vendor.example.com/authorize?state=s"; -/** A server that offers (or not) `windowConnections`, recording each connect and authorize body. */ -function server(offersWindow: boolean) { +/** + * A server that offers (or not) `windowConnections`, recording each connect and authorize body. + * `perAction`: its apps are authorized action by action (Arcade), whose verifier needs a session. + */ +function server(offersWindow: boolean, perAction = false) { const bodies: { path: string; body: Record }[] = []; globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = new URL( @@ -50,6 +58,8 @@ function server(offersWindow: boolean) { edition: "team", ...(offersWindow ? { windowConnections: true } : {}), }); + if (url.pathname.endsWith("/app-setup")) + return json({ authorizesPerAction: perAction }); if (init?.method === "POST") { bodies.push({ path: url.pathname, @@ -68,6 +78,11 @@ function embed() { configureEmbed({ apiBaseUrl: "https://openbot.example.com", getAssertion }); } +/** A press made on the host page: the consent tab claimed on the click, as a screen claims it. */ +function pressed() { + createConsentTab({ embedded: () => true, ...fakeWindow() }).claim(); +} + async function connect(returnTo: "settings" | "admin", shared = false) { setCurrentOrganization("default"); const options = connectAccountMutationOptions(returnTo, shared); @@ -78,6 +93,7 @@ async function connect(returnTo: "settings" | "admin", shared = false) { test("embedded, and offered, a connect asks to come back to a page that closes its window", async () => { const bodies = server(true); embed(); + pressed(); await connect("settings"); expect(bodies.at(-1)?.body.returnTo).toBe("window"); }); @@ -85,6 +101,7 @@ test("embedded, and offered, a connect asks to come back to a page that closes i test("embedded, an administrator's connect of an app's shared account comes back the same way", async () => { const bodies = server(true); embed(); + pressed(); await connect("admin", true); expect(bodies.at(-1)?.body.returnTo).toBe("window"); }); @@ -92,6 +109,7 @@ test("embedded, an administrator's connect of an app's shared account comes back test("embedded, an action's consent comes back the same way", async () => { const bodies = server(true); embed(); + pressed(); setCurrentOrganization("default"); const options = authorizeActionMutationOptions("settings"); await options.mutationFn?.( @@ -112,6 +130,31 @@ test("not embedded, a connect comes back to OpenBot's own pages as before", asyn test("embedded, against a server that doesn't offer it, a connect never sends window", async () => { const bodies = server(false); embed(); + pressed(); + await connect("settings"); + expect(bodies.at(-1)?.body.returnTo).toBe("connections"); +}); + +/* + * WITH NO TAB HELD, THE PAGE THE SIGN-IN COMES BACK TO MUST BE ONE IT CAN USE. A press whose tab the + * browser blocked, or a connect a page started by itself, opens the sign-in in the host page; a page + * that closes its tab can't close that one, so it would strand the person there. + */ +test("embedded, with no tab held, a connect comes back to OpenBot's own pages as before", async () => { + const bodies = server(true); + embed(); + await connect("settings"); + expect(bodies.at(-1)?.body.returnTo).toBe("connections"); + createConsentTab({ embedded: () => true, ...fakeWindow(true) }).claim(); + await connect("settings"); + expect(bodies.at(-1)?.body.returnTo).toBe("connections"); +}); + +// Their consent ends at OpenBot's verifier, which needs the person's session: not in a tab of its own. +test("embedded, where apps are authorized action by action, a connect never sends window", async () => { + const bodies = server(true, true); + embed(); + pressed(); await connect("settings"); expect(bodies.at(-1)?.body.returnTo).toBe("connections"); }); @@ -175,6 +218,17 @@ test("embedded, a claimed tab is closed when the press is refused or needs no si expect(win.opened[0]?.tab.closed).toBe(true); }); +test("embedded, a claimed tab the person closed before the sign-in opens a new one, and never the host page", () => { + const win = fakeWindow(); + const consent = createConsentTab({ embedded: () => true, ...win }); + consent.claim(); + const first = win.opened[0]?.tab; + if (first) first.closed = true; + consent.go(START); + expect(win.opened.map((o) => o.url)).toEqual(["", START]); + expect(win.page.href).toBe("https://host.example.com/apps"); +}); + test("embedded and blocked, the sign-in still opens, in the host page, as before", () => { const win = fakeWindow(true); const consent = createConsentTab({ embedded: () => true, ...win }); @@ -217,3 +271,31 @@ test("no screen sends its own page to an app's sign-in", () => { }); } }); + +/* + * THE CONFIRM WAITS FOR THE ANSWER IT IS WAITING FOR. Embedded, the person may come back to the host + * page before they finish in the sign-in's tab; that return asked too early, and the account the + * vendor holds was never recorded once they did finish. So a confirm that hears "not yet" asks again + * the next time the page has the focus, and stops once it hears "connected". + */ +test("embedded, a confirm that is too early asks again at the next return, and stops once connected", async () => { + server(true); + embed(); + setCurrentOrganization("default"); + const answers = [{ connected: false }, { connected: true }]; + let asked = 0; + confirmOnReturn(new QueryClient(), "gmail", async () => { + asked++; + return answers.shift() ?? { connected: true }; + }); + const comeBack = async () => { + window.dispatchEvent(new Event("focus")); + await new Promise((resolve) => setTimeout(resolve, 20)); + }; + await comeBack(); + expect(asked).toBe(1); + await comeBack(); + expect(asked).toBe(2); + await comeBack(); + expect(asked).toBe(2); +}); diff --git a/app/tests/plugin-mutation-refresh.test.ts b/app/tests/plugin-mutation-refresh.test.ts index 165b4a6ee8..dc3f936ce2 100644 --- a/app/tests/plugin-mutation-refresh.test.ts +++ b/app/tests/plugin-mutation-refresh.test.ts @@ -126,7 +126,8 @@ const EVERY_PLUGIN_QUERY = [ * * Spelled out rather than cast away, because `app/tests` sits outside `app/tsconfig.json` and * `bun test` does not typecheck — so a call written to the wrong arity here is a green test against - * a signature that does not exist. None of these mutation functions reads it. + * a signature that does not exist. The connect and authorize ones read its client, to ask whether + * an embedded sign-in comes back to a page that closes its tab (lib/plugins/consent-tab.ts). */ function mutationContext(): MutationFunctionContext { return { client: new QueryClient(), meta: undefined }; From 30c729a9d27ce3679d5e853b6cbd563432188ba9 Mon Sep 17 00:00:00 2001 From: Maxim Date: Thu, 3 Dec 2026 22:02:10 +0100 Subject: [PATCH 3/3] Embedded: a chat card's, Browse apps' and app access's tab asks for the closing page too From Dave's review of this PR: - useConnectInNewTab claims its own tab and never registered it as held, so a chat card's connect, Browse apps and an app's access row still asked for OpenBot's own pages and landed on a sign-in screen when embedded. Its tab is now held (holdConsentTab) until it is sent to the sign-in or closed. Test: an embedded chat card's connect sends returnTo window. - A screen that goes lets go of the tab it claimed. - A confirm put back for the next return never replaces a newer press for the same app. - Docs: a sandboxed frame needs allow-popups-to-escape-sandbox as well as allow-popups. Co-Authored-By: Claude Opus 5.5 --- .../components/plugins/connect-in-new-tab.ts | 9 ++++ app/src/lib/plugins/confirm-on-return.ts | 8 +++- app/src/lib/plugins/consent-tab.ts | 22 ++++++++-- app/tests/connect-app-card.test.tsx | 43 +++++++++++++++++++ docs/configuration.md | 3 +- 5 files changed, 80 insertions(+), 5 deletions(-) diff --git a/app/src/components/plugins/connect-in-new-tab.ts b/app/src/components/plugins/connect-in-new-tab.ts index d63374fdd2..3e825f3a0d 100644 --- a/app/src/components/plugins/connect-in-new-tab.ts +++ b/app/src/components/plugins/connect-in-new-tab.ts @@ -4,6 +4,7 @@ import { ConsentHandoffDialog } from "@/components/plugins/consent-handoff"; import { desktopShell } from "@/lib/desktop/shell"; import { embedConfig } from "@/lib/embed/config"; import { failureOf } from "@/lib/load-failure"; +import { holdConsentTab, releaseConsentTab } from "@/lib/plugins/consent-tab"; import { markConnectReturn } from "@/lib/plugins/connect-return"; import { brokeredConsentFor, @@ -156,6 +157,8 @@ export function useConnectInNewTab( const claimTab = (): Window | null => { const tab = window.open("", "_blank"); if (tab) tab.opener = null; + // Embedded, the press then asks for the page that closes this tab (lib/plugins/consent-tab.ts). + holdConsentTab(tab); return tab; }; @@ -199,6 +202,7 @@ export function useConnectInNewTab( const from = here(); const unused = () => { tab?.close(); + releaseConsentTab(tab); handle.current = null; }; return during( @@ -225,6 +229,7 @@ export function useConnectInNewTab( start = await connect.mutateAsync(serverId); } catch { tab?.close(); + releaseConsentTab(tab); handle.current = null; return; } @@ -237,6 +242,7 @@ export function useConnectInNewTab( */ if (start !== null && "connected" in start) { tab?.close(); + releaseConsentTab(tab); handle.current = null; void invalidateAppConnection(queryClient); return; @@ -248,6 +254,7 @@ export function useConnectInNewTab( */ if (start === null) { tab?.close(); + releaseConsentTab(tab); handle.current = null; setNeedsKey(true); return; @@ -288,6 +295,7 @@ export function useConnectInNewTab( /** Send the claimed tab to `destination`, and watch for the person to come back from it. */ const leaveFor = (tab: Window | null, destination: string) => { + releaseConsentTab(tab); setWaiting(true); if (tab) tab.location.replace(destination); // The tab was blocked. The url is still good, so offer it as something to click. @@ -304,6 +312,7 @@ export function useConnectInNewTab( const cancelHandoff = () => { setHandoff(null); held.current?.close(); + releaseConsentTab(held.current); held.current = null; handle.current = null; }; diff --git a/app/src/lib/plugins/confirm-on-return.ts b/app/src/lib/plugins/confirm-on-return.ts index aff6298810..35710a8a10 100644 --- a/app/src/lib/plugins/confirm-on-return.ts +++ b/app/src/lib/plugins/confirm-on-return.ts @@ -107,7 +107,13 @@ async function confirmPending(): Promise { const now = Date.now(); confirms.forEach(([serverId, entry], index) => { const answer = answers[index]; - if (answer && !connected(answer) && entry.until > now) + // A press for the same app made meanwhile is the newer one, and stays. + if ( + answer && + !connected(answer) && + entry.until > now && + !pending.has(serverId) + ) pending.set(serverId, entry); }); if (pending.size > 0) { diff --git a/app/src/lib/plugins/consent-tab.ts b/app/src/lib/plugins/consent-tab.ts index 0e3c74268f..9bdd02b6b9 100644 --- a/app/src/lib/plugins/consent-tab.ts +++ b/app/src/lib/plugins/consent-tab.ts @@ -1,5 +1,5 @@ import type { QueryClient } from "@tanstack/react-query"; -import { useMemo } from "react"; +import { useEffect, useMemo } from "react"; import { appSetupQueryOptions } from "@/lib/apps/queries"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { embedConfig } from "@/lib/embed/config"; @@ -55,6 +55,20 @@ const browserWindow: ConsentTabWindow = { */ const held = new Set(); +/** + * Hold a tab another opener claimed on a press for a sign-in (`useConnectInNewTab`, which a chat + * card, Browse apps and an app's access row use), so the press asks for the page that closes it. + * Released once the tab is sent to the sign-in, or closed. + */ +export function holdConsentTab(tab: Window | null): void { + if (tab && embedConfig() !== undefined) held.add(tab); +} + +/** Let go of a tab {@link holdConsentTab} held. */ +export function releaseConsentTab(tab: Window | null): void { + if (tab) held.delete(tab); +} + /** Whether a tab claimed on a press is open and waiting for the sign-in. */ function holdsConsentTab(): boolean { for (const tab of held) if (!tab.closed) return true; @@ -125,9 +139,11 @@ export function createConsentTab( }; } -/** One consent tab per screen, for the screen's presses. */ +/** One consent tab per screen, for the screen's presses; a screen that goes lets go of its tab. */ export function useConsentTab(): ConsentTab { - return useMemo(() => createConsentTab(), []); + const consent = useMemo(() => createConsentTab(), []); + useEffect(() => () => consent.drop(), [consent]); + return consent; } /** diff --git a/app/tests/connect-app-card.test.tsx b/app/tests/connect-app-card.test.tsx index 02b47b6a9f..7c9380f754 100644 --- a/app/tests/connect-app-card.test.tsx +++ b/app/tests/connect-app-card.test.tsx @@ -13,6 +13,8 @@ import { } from "@tanstack/react-router"; import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"; import { ConnectAppCard } from "@/components/channels/connect-app-card"; +import { configureEmbed, resetEmbedForTests } from "@/lib/embed/config"; +import { resetConsentTabsForTests } from "@/lib/plugins/consent-tab"; import { CAPABILITIES, CLIENT_NAME } from "@/lib/client"; import { carryOnMessage } from "@/lib/copilot/carry-on"; import { ConversationProvider } from "@/lib/copilot/conversation"; @@ -75,9 +77,13 @@ function mounted( popupsAllowed?: boolean; /** Drawn inside a conversation, as the latest thing in it: what the card sends is kept here. */ asked?: string[]; + /** The server offers the page that closes a sign-in's tab (`windowConnections`). */ + windowOffered?: boolean; } = {}, ) { const { connections = [], answers = "url", popupsAllowed = true } = options; + /** The body of each connect request, as sent. */ + const connectBodies: Record[] = []; /** Where a claimed tab was pointed, which is the only evidence the vendor was reached. */ const sentTo: string[] = []; @@ -122,6 +128,12 @@ function mounted( // The verifier always answers with somewhere to go, which a manual redirect does not follow. return new Response(null, { status: 303, headers: { location: "/" } }); } + if (url.endsWith("/deployment")) + return json({ + edition: "team", + ...(options.windowOffered ? { windowConnections: true } : {}), + }); + if (url.endsWith("/app-setup")) return json({ authorizesPerAction: false }); const call = connectionsCall(url, init); // A person's own connections. A Shared app's one account is never among them. if (call?.operation === "list") @@ -132,6 +144,11 @@ function mounted( ).filter((row) => row.holder !== "deployment"), ); if (call?.operation === "connect") { + connectBodies.push( + typeof init?.body === "string" + ? (JSON.parse(init.body) as Record) + : {}, + ); if (answers === "failure") return connectionsProblem(502, "That account could not be connected."); // What a key-entry app answers: a form to fill in, and no page to visit. @@ -210,6 +227,7 @@ function mounted( tabGone = true; }, verifierCalls, + connectBodies, }; } @@ -241,6 +259,31 @@ test("sends the person to the vendor in another tab, never in this one", async ( expect(card.view.getByText(/Finish in the tab that opened/)).toBeTruthy(); }); +/* + * EMBEDDED IN ANOTHER APP'S PAGE, the card's tab is the one the sign-in runs in, so it asks to come + * back to the page that closes it: OpenBot's own pages there need a session the person doesn't have. + */ +test("embedded, the card's connect asks to come back to a page that closes its tab", async () => { + configureEmbed({ + apiBaseUrl: "https://openbot.example.com", + getAssertion: async () => "assertion", + }); + try { + const card = mounted({ windowOffered: true }); + await waitFor(() => card.view.getByRole("button", { name: /^Connect$/ })); + + press(card); + + await waitFor(() => + expect(card.sentTo).toContain("https://notion.test/consent"), + ); + expect(card.connectBodies.at(-1)?.returnTo).toBe("window"); + } finally { + resetEmbedForTests(); + resetConsentTabsForTests(); + } +}); + test("claims the tab on the click itself, before the request that mints the url", async () => { /* * A browser only lets a page open a tab while a click is still recent — about five seconds in diff --git a/docs/configuration.md b/docs/configuration.md index 5b0e067e67..9250345bc6 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -834,7 +834,8 @@ person's session and their Recorders end. where it is. When the person is done, the app sends them back to a page on OpenBot's public address that needs no sign-in and closes the tab (`returnTo: window`), and the embedded app reads the connection again once the person is back. The host page must let the browser open that tab: a -`sandbox` on a frame around it needs `allow-popups`. Through Composio, the step OpenBot shows before +`sandbox` on a frame around it needs `allow-popups` and `allow-popups-to-escape-sandbox`, or the +vendor's sign-in page opens sandboxed too and breaks. Through Composio, the step OpenBot shows before the sign-in is left out when embedded, because no page of OpenBot's runs on the host's origin to show it.