Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(desktop): return connector authorization to Linger
yunhef70f03f571a8
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 1fc58429..3ee86783 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -39,6 +39,11 @@ Gateway and runs Agents. The daemon exits with the app.## Structure+- Connector OAuth opens in the system browser. The desktop prepares an+ expiring, one-time IPv4 loopback callback before TeamHub creates the link.+ The callback restores the originating window and forwards the return to its+ signed-in SPA, which requests TeamHub verification.+- `src/main/modules.ts`: `Module` interface, typed bus and the host that startsmodules in dependency layers and stops them in reverse.- `src/main/*.ts`: one file per module (Enrollment, WorkspaceGrants,diff --git a/apps/desktop/src/main/connector-oauth.test.ts b/apps/desktop/src/main/connector-oauth.test.tsnew file mode 100644index 00000000..90b3e53b--- /dev/null+++ b/apps/desktop/src/main/connector-oauth.test.ts@@ -0,0 +1,25 @@+import { expect, it, vi } from "vitest";++import { ConnectorOAuth } from "./connector-oauth.js";++it("accepts only the assigned browser callback and consumes it once", async () => {+ const oauth = new ConnectorOAuth();+ const returned = vi.fn();+ try {+ const callback = new URL(await oauth.prepare(returned));+ expect(callback.hostname).toBe("127.0.0.1");+ const wrong = new URL("wrong", callback);+ expect((await fetch(wrong)).status).toBe(404);+ expect((await fetch(callback, { method: "POST" })).status).toBe(404);+ expect(returned).not.toHaveBeenCalled();++ callback.searchParams.set("connected_account_id", "ca_returned");+ const response = await fetch(callback);+ expect(response.status).toBe(200);+ expect(await response.text()).toContain("back to Linger");+ expect(returned).toHaveBeenCalledExactlyOnceWith("ca_returned");+ expect((await fetch(callback)).status).toBe(404);+ } finally {+ oauth.stop();+ }+});diff --git a/apps/desktop/src/main/connector-oauth.ts b/apps/desktop/src/main/connector-oauth.tsnew file mode 100644index 00000000..e641b349--- /dev/null+++ b/apps/desktop/src/main/connector-oauth.ts@@ -0,0 +1,91 @@+import { randomBytes } from "node:crypto";+import { createServer, type Server } from "node:http";++const CALLBACK_PREFIX = "/oauth/connector/";+const CALLBACK_TTL = 15 * 60_000;+const MAX_CALLBACKS = 32;+type ReturnHandler = (connectedAccountId?: string) => void;++export class ConnectorOAuth {+ #server?: Server;+ #origin?: Promise<string>;+ readonly #pending = new Map<+ string,+ { expires: number; onReturn: ReturnHandler }+ >();++ async prepare(onReturn: ReturnHandler): Promise<string> {+ const origin = await (this.#origin ??= this.#listen());+ const now = Date.now();+ for (const [key, attempt] of this.#pending) {+ if (attempt.expires <= now) this.#pending.delete(key);+ }+ if (this.#pending.size >= MAX_CALLBACKS) {+ throw new Error("Too many connector authorizations in progress");+ }+ const pathname = CALLBACK_PREFIX + randomBytes(24).toString("hex");+ this.#pending.set(pathname, { expires: now + CALLBACK_TTL, onReturn });+ return origin + pathname;+ }++ #listen(): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ const server = createServer({ requestTimeout: 10_000 }, (req, res) => {+ const address = server.address();+ const host =+ address && typeof address !== "string"+ ? `127.0.0.1:${address.port}`+ : "";+ res.setHeader("Cache-Control", "no-store");+ if (+ !host ||+ req.method !== "GET" ||+ req.headers.host !== host ||+ !req.url?.startsWith(CALLBACK_PREFIX)+ ) {+ res.writeHead(404).end("Authorization callback not found.");+ return;+ }+ const url = new URL(req.url, `http://${host}`);+ const attempt = this.#pending.get(url.pathname);+ if (!attempt || attempt.expires <= Date.now()) {+ res.writeHead(404).end("Authorization callback not found.");+ return;+ }+ this.#pending.delete(url.pathname);+ const account = url.searchParams.get("connected_account_id");+ res+ .writeHead(200, {+ "Content-Type": "text/html; charset=utf-8",+ "Content-Security-Policy": "default-src 'none'",+ "Referrer-Policy": "no-referrer",+ })+ .end(+ "<!doctype html><html lang=en><meta charset=utf-8><title>Linger authorization</title><h1>Go back to Linger</h1><p>Linger received the authorization response. Check the connector status in the app. You can close this tab.</p>",+ );+ attempt.onReturn(+ account && /^[a-zA-Z0-9_-]{1,256}$/.test(account)+ ? account+ : undefined,+ );+ });+ this.#server = server;+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ server.unref();+ const address = server.address();+ if (address && typeof address !== "string")+ resolve(`http://127.0.0.1:${address.port}`);+ });+ }).catch((error: unknown) => {+ this.#origin = undefined;+ throw error;+ });+ }++ stop(): void {+ this.#pending.clear();+ this.#server?.close();+ this.#server?.closeAllConnections();+ }+}diff --git a/apps/desktop/src/main/desktop-ipc.ts b/apps/desktop/src/main/desktop-ipc.tsindex 85530677..c7b8d917 100644--- a/apps/desktop/src/main/desktop-ipc.ts+++ b/apps/desktop/src/main/desktop-ipc.ts@@ -1,4 +1,4 @@-import { ipcMain, type IpcMainInvokeEvent } from "electron";+import { app, ipcMain, type IpcMainInvokeEvent } from "electron";import { z } from "zod";import {@@ -11,6 +11,7 @@ import {} from "../shared/api.js";import type { ComputerDaemonModule } from "./computer-daemon.js";import type { WorkspaceGrant } from "./config.js";+import { ConnectorOAuth } from "./connector-oauth.js";import type { EnrollmentModule } from "./enrollment.js";import type { LocalServerModule } from "./local-server.js";import type { Module, ModuleContext } from "./modules.js";@@ -96,6 +97,36 @@ export class DesktopIpcModule implements Module {const localServer = ctx.get<LocalServerModule>("LocalServer");const updater = ctx.get<UpdaterModule>("Updater");+ const oauth = new ConnectorOAuth();+ ipcMain.handle(IPC.connectorOAuthPrepare, (event: IpcMainInvokeEvent) => {+ const contents = windows.webContents();+ const origin = ctx.config.get().serverUrl;+ if (+ !contents ||+ !origin ||+ event.sender !== contents ||+ event.senderFrame !== contents.mainFrame ||+ !sameOrigin(contents.getURL(), origin)+ ) {+ throw new Error("Not allowed");+ }+ return oauth.prepare((account) => {+ if (+ contents.isDestroyed() ||+ !sameOrigin(contents.getURL(), origin) ||+ contents !== windows.webContents()+ )+ return;+ windows.show();+ if (process.platform === "darwin") app.focus({ steal: true });+ contents.send(IPC.connectorOAuthReturn, account);+ });+ });+ this.#unsubscribe.push(() => {+ ipcMain.removeHandler(IPC.connectorOAuthPrepare);+ oauth.stop();+ });+const status = (): ComputerStatus => {const computerId = ctx.config.get().computerId;return {diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex dab39572..da600f3c 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -52,6 +52,15 @@ const api: LingerDesktopApi = {install: () => ipcRenderer.invoke(IPC.updateInstall),check: () => ipcRenderer.invoke(IPC.updateCheck),},+ connectorOAuth: {+ prepare: () => ipcRenderer.invoke(IPC.connectorOAuthPrepare),+ onReturn: (callback) => {+ const listener = (_event: unknown, account?: string): void =>+ callback(account);+ ipcRenderer.on(IPC.connectorOAuthReturn, listener);+ return () => ipcRenderer.off(IPC.connectorOAuthReturn, listener);+ },+ },...(process.platform === "darwin"? {permissions: {diff --git a/apps/desktop/src/shared/api.ts b/apps/desktop/src/shared/api.tsindex 10b10ab1..f319d28e 100644--- a/apps/desktop/src/shared/api.ts+++ b/apps/desktop/src/shared/api.ts@@ -102,6 +102,10 @@ export interface LingerDesktopApi {// Try Again after a failure.check(): Promise<void>;};+ readonly connectorOAuth: {+ prepare(): Promise<string>;+ onReturn(callback: (connectedAccountId?: string) => void): () => void;+ };// macOS only.readonly permissions?: {act(step: DesktopPermissionStep): Promise<void>;@@ -125,4 +129,6 @@ export const IPC = {updateStateEvent: "update.state.event",updateInstall: "update.install",updateCheck: "update.check",+ connectorOAuthPrepare: "connector-oauth.prepare",+ connectorOAuthReturn: "connector-oauth.return",} as const;diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.mdindex 2f2764a5..0f79a6a1 100644--- a/apps/teamhub/AGENTS.md+++ b/apps/teamhub/AGENTS.md@@ -21,6 +21,9 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.- `internal/app`: routing, authentication, request decoding, response encoding,and error mapping. `app.go` and `feature*.go` build the domain services.+- Connector authorization defaults to the public Web callback. For a desktop+ request, pass only a validated one-time loopback address to Composio.+ TeamHub verifies connection status independently under the signed-in Account.- `internal/<feature>`: business behavior, transactions and data access withpackage tests: `collaboration` (Human Rooms and Messages),`agentregistry` (Agents, templates, Skill bindings, Another Me),diff --git a/apps/teamhub/internal/app/handlers_external_source_v1.go b/apps/teamhub/internal/app/handlers_external_source_v1.goindex 98d7d0cf..623e6129 100644--- a/apps/teamhub/internal/app/handlers_external_source_v1.go+++ b/apps/teamhub/internal/app/handlers_external_source_v1.go@@ -5,6 +5,7 @@ import ("net/http""github.com/gin-gonic/gin"+ "github.com/simplexai-labs/linger/apps/teamhub/internal/composio""github.com/simplexai-labs/linger/apps/teamhub/internal/externalsource"httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic")@@ -77,7 +78,12 @@ func (a *App) createExternalConnection(c *gin.Context) {a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "External application connection request is invalid")return}- connection, err := a.externalSources.CreateConnection(c.Request.Context(), currentPrincipal(c).Session.AccountID, request.AppKey)+ ctx, err := composio.WithDesktopOAuthCallback(c.Request.Context(), request.DesktopCallbackUrl)+ if err != nil {+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Desktop authorization callback is invalid")+ return+ }+ connection, err := a.externalSources.CreateConnection(ctx, currentPrincipal(c).Session.AccountID, request.AppKey)if errors.Is(err, externalsource.ErrManagedKeyForbidden) {a.writeError(c, http.StatusForbidden, "COMPOSIO_CONNECTION_FORBIDDEN", "Composio denied this connection. Check the API key's permissions and confirm this app is available in your Composio project. If the key lacks Write All access, create a new key with Read All and Write All, then update it in Security.")return@@ -208,7 +214,12 @@ func (a *App) createExternalConnectionReauthorization(c *gin.Context) {a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Reauthorization request is invalid")return}- connection, err := a.externalSources.CreateReauthorization(c.Request.Context(), currentPrincipal(c).Session.AccountID, c.Param("externalConnectionId"), request.ExpectedRevision)+ ctx, err := composio.WithDesktopOAuthCallback(c.Request.Context(), request.DesktopCallbackUrl)+ if err != nil {+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Desktop authorization callback is invalid")+ return+ }+ connection, err := a.externalSources.CreateReauthorization(ctx, currentPrincipal(c).Session.AccountID, c.Param("externalConnectionId"), request.ExpectedRevision)if a.writeExternalSourceError(c, "create external connection reauthorization", err) {return}diff --git a/apps/teamhub/internal/composio/client.go b/apps/teamhub/internal/composio/client.goindex 54abd03d..f80ea753 100644--- a/apps/teamhub/internal/composio/client.go+++ b/apps/teamhub/internal/composio/client.go@@ -303,8 +303,12 @@ func (c *Client) CreateConnectionLink(ctx context.Context, authConfigID, accountreturn Link{}, errors.New("Composio auth config ID is required")}body := map[string]string{"auth_config_id": authConfigID, "user_id": c.UserIDForAccount(accountID)}- if c.callbackURL != "" {- body["callback_url"] = c.callbackURL+ callback := c.callbackURL+ if desktop, ok := ctx.Value(desktopCallbackKey{}).(string); ok {+ callback = desktop+ }+ if callback != "" {+ body["callback_url"] = callback}var response struct {ConnectedAccountID string `json:"connected_account_id"`diff --git a/apps/teamhub/internal/composio/client_test.go b/apps/teamhub/internal/composio/client_test.goindex 4560075d..8d79dcc9 100644--- a/apps/teamhub/internal/composio/client_test.go+++ b/apps/teamhub/internal/composio/client_test.go@@ -19,15 +19,16 @@ import ()func TestClientCreateLinkSendsFixedCallbackURL(t *testing.T) {+ const web = "https://workspace.example.com/oauth/composio-complete"+ desktop := "http://127.0.0.1:43210/oauth/connector/" + strings.Repeat("a", 48)+ got := make(chan any, 2)mux := http.NewServeMux()mux.HandleFunc("/api/v3.1/connected_accounts/link", func(w http.ResponseWriter, r *http.Request) {var body map[string]anyif err := json.NewDecoder(r.Body).Decode(&body); err != nil {t.Fatal(err)}- if body["callback_url"] != "https://workspace.example.com/oauth/composio-complete" {- t.Fatalf("unexpected link body: %#v", body)- }+ got <- body["callback_url"]w.WriteHeader(http.StatusCreated)_, _ = w.Write([]byte(`{"connected_account_id":"ca_1","redirect_url":"https://connect.example/link","expires_at":"2026-08-05T12:00:00Z"}`))})@@ -36,14 +37,26 @@ func TestClientCreateLinkSendsFixedCallbackURL(t *testing.T) {client, err := newTestClient(Config{BaseURL: server.URL, APIKey: "restricted-key",- CallbackURL: "https://workspace.example.com/oauth/composio-complete", HTTPClient: server.Client(),+ CallbackURL: web, HTTPClient: server.Client(),})if err != nil {t.Fatal(err)}- if _, err := client.CreateConnectionLink(context.Background(), "gmail-auth", "account_1"); err != nil {+ ctx, err := WithDesktopOAuthCallback(context.Background(), &desktop)+ if err != nil {t.Fatal(err)}+ for _, request := range []struct {+ ctx context.Context+ want string+ }{{ctx, desktop}, {context.Background(), web}} {+ if _, err := client.CreateConnectionLink(request.ctx, "gmail-auth", "account_1"); err != nil {+ t.Fatal(err)+ }+ if callback := <-got; callback != request.want {+ t.Errorf("callback = %q, want %q", callback, request.want)+ }+ }}func TestOAuthCallbackURLUsesPublicWebBase(t *testing.T) {diff --git a/apps/teamhub/internal/composio/desktop_callback.go b/apps/teamhub/internal/composio/desktop_callback.gonew file mode 100644index 00000000..e5827b37--- /dev/null+++ b/apps/teamhub/internal/composio/desktop_callback.go@@ -0,0 +1,27 @@+package composio++import (+ "context"+ "errors"+ "regexp"+ "strconv"+)++type desktopCallbackKey struct{}++var desktopCallbackPattern = regexp.MustCompile(`^http://127\.0\.0\.1:([1-9][0-9]{0,4})/oauth/connector/[a-f0-9]{48}$`)++// WithDesktopOAuthCallback accepts only the desktop's one-time loopback URL.+// The hosted browser follows the URL; TeamHub never connects to it.+func WithDesktopOAuthCallback(ctx context.Context, callback *string) (context.Context, error) {+ if callback == nil {+ return ctx, nil+ }+ match := desktopCallbackPattern.FindStringSubmatch(*callback)+ if len(match) == 2 {+ if _, err := strconv.ParseUint(match[1], 10, 16); err == nil {+ return context.WithValue(ctx, desktopCallbackKey{}, *callback), nil+ }+ }+ return nil, errors.New("invalid desktop OAuth callback")+}diff --git a/apps/teamhub/internal/composio/desktop_callback_test.go b/apps/teamhub/internal/composio/desktop_callback_test.gonew file mode 100644index 00000000..19cdf23c--- /dev/null+++ b/apps/teamhub/internal/composio/desktop_callback_test.go@@ -0,0 +1,26 @@+package composio++import (+ "context"+ "strings"+ "testing"+)++func TestDesktopOAuthCallbackAllowsOnlyOneTimeLoopbackAddresses(t *testing.T) {+ valid := "http://127.0.0.1:43210/oauth/connector/" + strings.Repeat("a", 48)+ ctx, err := WithDesktopOAuthCallback(context.Background(), &valid)+ if err != nil || ctx.Value(desktopCallbackKey{}) != valid {+ t.Fatalf("valid callback rejected: %v", err)+ }+ for _, url := range []string{+ strings.Replace(valid, "127.0.0.1", "localhost", 1),+ strings.Replace(valid, "127.0.0.1", "example.test", 1),+ strings.Replace(valid, "43210", "65536", 1),+ valid + "?extra=1",+ strings.TrimSuffix(valid, "a"),+ } {+ if _, err := WithDesktopOAuthCallback(context.Background(), &url); err == nil {+ t.Errorf("accepted unexpected callback %q", url)+ }+ }+}diff --git a/apps/teamhub/tests/integration/composio_fake_test.go b/apps/teamhub/tests/integration/composio_fake_test.goindex b8d40f7e..ac593b93 100644--- a/apps/teamhub/tests/integration/composio_fake_test.go+++ b/apps/teamhub/tests/integration/composio_fake_test.go@@ -40,6 +40,7 @@ type fakeComposio struct {mu sync.Mutexaccounts map[string]*fakeComposioAccountlinks int+ lastCallback stringrevoked []stringstatusRequests map[string]int// intercept may answer a request before the default handling.@@ -81,12 +82,14 @@ func (f *fakeComposio) serveHTTP(w http.ResponseWriter, r *http.Request) {var input struct {AuthConfigID string `json:"auth_config_id"`UserID string `json:"user_id"`+ CallbackURL string `json:"callback_url"`}if err := json.NewDecoder(r.Body).Decode(&input); err != nil {w.WriteHeader(http.StatusBadRequest)return}f.links+++ f.lastCallback = input.CallbackURLid := fmt.Sprintf("ca_link_%d", f.links)// The account is authorized as soon as the link exists.f.accounts[id] = &fakeComposioAccount{userID: input.UserID, toolkit: fakeComposioToolkit(input.AuthConfigID), authConfigID: input.AuthConfigID, status: composio.ConnectionActive}@@ -196,6 +199,12 @@ func (f *fakeComposio) statusRequestCount(upstreamID string) int {return f.statusRequests[upstreamID]}+func (f *fakeComposio) callbackURL() string {+ f.mu.Lock()+ defer f.mu.Unlock()+ return f.lastCallback+}+// completeAuthorizations stands in for the OAuth popup returning to TeamHub:// it makes the session account's pending authorizations due at once.func completeAuthorizations(t *testing.T, env *testEnv, session *http.Client) {diff --git a/apps/teamhub/tests/integration/connected_apps_test.go b/apps/teamhub/tests/integration/connected_apps_test.goindex 1f2df853..d84d36f2 100644--- a/apps/teamhub/tests/integration/connected_apps_test.go+++ b/apps/teamhub/tests/integration/connected_apps_test.go@@ -152,10 +152,18 @@ func TestConnectedAppsCatalogAndGenericConnection(t *testing.T) {}}- statusCode, _, body = env.request(alice, http.MethodPost, "/v0/external-connections", map[string]any{"app_key": "gmail"}, "connected-app-create")+ desktopCallback := "http://127.0.0.1:43210/oauth/connector/" + strings.Repeat("a", 48)+ statusCode, _, body = env.request(alice, http.MethodPost, "/v0/external-connections", map[string]any{"app_key": "gmail", "desktop_callback_url": "https://example.test/oauth"}, "invalid-desktop-callback")+ if statusCode != http.StatusBadRequest || composioFake.callbackURL() != "" {+ t.Fatalf("invalid desktop callback reached Composio: status=%d body=%s", statusCode, body)+ }+ statusCode, _, body = env.request(alice, http.MethodPost, "/v0/external-connections", map[string]any{"app_key": "gmail", "desktop_callback_url": desktopCallback}, "connected-app-create")if statusCode != http.StatusCreated {t.Fatalf("generic create status=%d body=%s", statusCode, body)}+ if got := composioFake.callbackURL(); got != desktopCallback {+ t.Fatalf("desktop callback sent to Composio = %q, want %q", got, desktopCallback)+ }var connection struct {ID string `json:"id"`Provider string `json:"provider"`@@ -184,7 +192,10 @@ func TestConnectedAppsCatalogAndGenericConnection(t *testing.T) {t.Fatalf("unavailable app create status=%d body=%s", statusCode, body)}- completeAuthorizations(t, env, alice)+ statusCode, _, body = env.request(alice, http.MethodPost, "/v0/external-connection-completions", map[string]any{"connected_account_id": "ca_link_1"}, "")+ if statusCode != http.StatusNoContent {+ t.Fatalf("desktop completion status=%d body=%s", statusCode, body)+ }if !waitForExternalSource(func() bool {statusCode, _, body = env.request(alice, http.MethodGet, "/v0/external-connections/"+connection.ID, nil, "")if statusCode != http.StatusOK {diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex f409164a..03e52a2e 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -16,6 +16,10 @@ build:assets` to check the initial JS budget.## Structure+- Connector authorization uses the Web completion route or, when the desktop+ bridge is available, its one-time browser callback. The signed-in desktop+ page asks TeamHub to verify the return and refreshes its connector queries.+- `src/app`: routes, providers, route error boundaries, and global CSS.- `src/features/teamhub`: Human API, Session, error, and realtime adapters.- `src/features/rooms`: Room routes, Chat, Timeline, the right sidebar (Agent Info, Activity, Thread, Document) and membership UI.diff --git a/apps/web/src/features/apps/connected-apps-queries.ts b/apps/web/src/features/apps/connected-apps-queries.tsindex a5ddec57..0b99f9bb 100644--- a/apps/web/src/features/apps/connected-apps-queries.ts+++ b/apps/web/src/features/apps/connected-apps-queries.ts@@ -79,7 +79,8 @@ export function externalConnectionAgentAccessQueryOptions(export function isExternalSourceAccountQuery(queryKey: readonly unknown[]) {return (queryKey[0] === "teamhub" &&- typeof queryKey[1] === "string" &&- queryKey[1] === "external-connections"+ (queryKey[1] === "external-connections" ||+ (typeof queryKey[1] === "string" &&+ queryKey[2] === "external-connections")));}diff --git a/apps/web/src/features/apps/desktop-connector-oauth.ts b/apps/web/src/features/apps/desktop-connector-oauth.tsnew file mode 100644index 00000000..0f4b5881--- /dev/null+++ b/apps/web/src/features/apps/desktop-connector-oauth.ts@@ -0,0 +1,11 @@+interface DesktopConnectorOAuth {+ prepare(): Promise<string>;+ onReturn(callback: (connectedAccountId?: string) => void): () => void;+}++export function desktopConnectorOAuth() {+ return typeof window === "undefined"+ ? undefined+ : (window as { lingerDesktop?: { connectorOAuth?: DesktopConnectorOAuth } })+ .lingerDesktop?.connectorOAuth;+}diff --git a/apps/web/src/features/apps/desktop-connector-return.test.tsx b/apps/web/src/features/apps/desktop-connector-return.test.tsxnew file mode 100644index 00000000..e8b86ba8--- /dev/null+++ b/apps/web/src/features/apps/desktop-connector-return.test.tsx@@ -0,0 +1,54 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, waitFor } from "@testing-library/react";+import { afterEach, expect, it, vi } from "vitest";++import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";+import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";++import {+ externalConnectionsQueryKey,+ tenantExternalConnectionsQueryKey,+} from "./connected-apps-queries";+import { DesktopConnectorReturn } from "./desktop-connector-return";++afterEach(() => vi.unstubAllGlobals());++it("asks the signed-in client to verify the return and refreshes connector queries", async () => {+ let returned: ((account?: string) => void) | undefined;+ const unsubscribe = vi.fn();+ vi.stubGlobal("lingerDesktop", {+ connectorOAuth: {+ onReturn(listener: (account?: string) => void) {+ returned = listener;+ return unsubscribe;+ },+ },+ });+ const runtime = createTestTeamHubRuntime();+ const complete = vi+ .spyOn(runtime.client, "completeExternalConnectionAuthorization")+ .mockResolvedValue(undefined);+ const cache = new QueryClient();+ const own = externalConnectionsQueryKey();+ const tenant = tenantExternalConnectionsQueryKey("tenant-test");+ const unrelated = ["teamhub", "unrelated"];+ for (const key of [own, tenant, unrelated]) cache.setQueryData(key, []);+ const view = render(+ <QueryClientProvider client={cache}>+ <TeamHubRuntimeProvider runtime={runtime}>+ <DesktopConnectorReturn />+ </TeamHubRuntimeProvider>+ </QueryClientProvider>,+ );++ expect(returned).toBeTypeOf("function");+ returned?.("ca_returned");+ await waitFor(() =>+ expect(cache.getQueryState(own)?.isInvalidated).toBe(true),+ );+ expect(cache.getQueryState(tenant)?.isInvalidated).toBe(true);+ expect(cache.getQueryState(unrelated)?.isInvalidated).toBe(false);+ expect(complete).toHaveBeenCalledExactlyOnceWith("ca_returned");+ view.unmount();+ expect(unsubscribe).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/apps/desktop-connector-return.tsx b/apps/web/src/features/apps/desktop-connector-return.tsxnew file mode 100644index 00000000..6f60329b--- /dev/null+++ b/apps/web/src/features/apps/desktop-connector-return.tsx@@ -0,0 +1,28 @@+import { useQueryClient } from "@tanstack/react-query";+import { useEffect } from "react";++import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";++import { isExternalSourceAccountQuery } from "./connected-apps-queries";+import { desktopConnectorOAuth } from "./desktop-connector-oauth";++export function DesktopConnectorReturn() {+ const { client } = useTeamHubRuntime();+ const queryClient = useQueryClient();+ useEffect(+ () =>+ desktopConnectorOAuth()?.onReturn((connectedAccountId) => {+ void client+ .completeExternalConnectionAuthorization(connectedAccountId)+ .catch(() => undefined)+ .then(() =>+ queryClient.invalidateQueries({+ predicate: ({ queryKey }) =>+ isExternalSourceAccountQuery(queryKey),+ }),+ );+ }),+ [client, queryClient],+ );+ return null;+}diff --git a/apps/web/src/features/apps/oauth-popup.test.ts b/apps/web/src/features/apps/oauth-popup.test.tsindex 465c7b1c..d8b70202 100644--- a/apps/web/src/features/apps/oauth-popup.test.ts+++ b/apps/web/src/features/apps/oauth-popup.test.ts@@ -4,7 +4,10 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { openOAuthPopup, openOAuthUrl } from "./oauth-popup";describe("OAuth popup", () => {- afterEach(() => vi.restoreAllMocks());+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });it("opens the Connect Link directly in a named 560x720 popup", () => {const popup = { closed: false, focus: vi.fn() } as unknown as Window;@@ -25,4 +28,10 @@ describe("OAuth popup", () => {expect(openOAuthUrl("https://connect.example.test/oauth")).toBe(false);});++ it("accepts Electron's handoff to the system browser", () => {+ vi.stubGlobal("lingerDesktop", { connectorOAuth: {} });+ vi.spyOn(window, "open").mockReturnValue(null);+ expect(openOAuthUrl("https://connect.example.test/oauth")).toBe(true);+ });});diff --git a/apps/web/src/features/apps/oauth-popup.ts b/apps/web/src/features/apps/oauth-popup.tsindex 35849657..f5194b31 100644--- a/apps/web/src/features/apps/oauth-popup.ts+++ b/apps/web/src/features/apps/oauth-popup.ts@@ -1,3 +1,5 @@+import { desktopConnectorOAuth } from "./desktop-connector-oauth";+const OAUTH_POPUP_NAME = "linger_composio_oauth";const OAUTH_POPUP_WIDTH = 560;const OAUTH_POPUP_HEIGHT = 720;@@ -27,5 +29,18 @@ export function openOAuthPopup(connectUrl: string): Window | null {}export function openOAuthUrl(connectUrl: string): boolean {- return Boolean(openOAuthPopup(connectUrl));+ const popup = openOAuthPopup(connectUrl);+ // Electron sends the URL to the browser and denies the in-app popup.+ if (popup) return true;+ if (!desktopConnectorOAuth()) return false;+ try {+ const target = new URL(connectUrl);+ return (+ (target.protocol === "http:" || target.protocol === "https:") &&+ !target.username &&+ !target.password+ );+ } catch {+ return false;+ }}diff --git a/apps/web/src/features/teamhub/teamhub-external-source-client.test.ts b/apps/web/src/features/teamhub/teamhub-external-source-client.test.tsindex 25df5010..86035a4e 100644--- a/apps/web/src/features/teamhub/teamhub-external-source-client.test.ts+++ b/apps/web/src/features/teamhub/teamhub-external-source-client.test.ts@@ -23,6 +23,34 @@ describe("TeamHub External Source client", () => {},);+ it("uses a fresh desktop return URL for each request that creates an auth link", async () => {+ const url = "http://127.0.0.1:43210/oauth/connector/" + "a".repeat(48);+ const prepare = vi.fn().mockResolvedValue(url);+ vi.stubGlobal("window", { lingerDesktop: { connectorOAuth: { prepare } } });+ try {+ const fetchRequest = vi+ .fn<typeof fetch>()+ .mockImplementation(async () => jsonResponse(connectionFixture(), 201));+ const client = createHttpTeamHubClient({+ baseUrl: "https://teamhub.example.test",+ fetchRequest,+ });+ await client.createExternalConnection("notion");+ await client.createExternalConnectionReauthorization("connection/a", 3);+ expect(prepare).toHaveBeenCalledTimes(2);+ expect(+ (await sentRequests(fetchRequest)).map(([, init]) =>+ JSON.parse(requestBodyText(init?.body)),+ ),+ ).toEqual([+ { app_key: "notion", desktop_callback_url: url },+ { expected_revision: 3, desktop_callback_url: url },+ ]);+ } finally {+ vi.unstubAllGlobals();+ }+ });+it("maps connection and selection pagination to V1 routes", async () => {const connection = connectionFixture();const fetchRequest = vidiff --git a/apps/web/src/features/teamhub/teamhub-external-source-client.ts b/apps/web/src/features/teamhub/teamhub-external-source-client.tsindex a893b7d1..854a69ad 100644--- a/apps/web/src/features/teamhub/teamhub-external-source-client.ts+++ b/apps/web/src/features/teamhub/teamhub-external-source-client.ts@@ -1,3 +1,5 @@+import { desktopConnectorOAuth } from "@/features/apps/desktop-connector-oauth";+import type {TeamHubDisconnectExternalConnectionInput,TeamHubExternalAppKey,@@ -86,6 +88,10 @@ export function createHttpTeamHubExternalSourceClient(const connection = (externalConnectionId: string) => ({path: { externalConnectionId },});+ const desktopCallback = async () => {+ const url = await desktopConnectorOAuth()?.prepare();+ return url ? { desktop_callback_url: url } : {};+ };return {completeExternalConnectionAuthorization: (connectedAccountId) =>done(@@ -95,13 +101,13 @@ export function createHttpTeamHubExternalSourceClient(: {},}),),- createExternalConnection: (appKey) =>+ createExternalConnection: async (appKey) =>data(api.POST("/v0/external-connections", {- body: { app_key: appKey },+ body: { app_key: appKey, ...(await desktopCallback()) },}),),- createExternalConnectionReauthorization: (+ createExternalConnectionReauthorization: async (externalConnectionId,expectedRevision,) =>@@ -110,7 +116,10 @@ export function createHttpTeamHubExternalSourceClient("/v0/external-connections/{externalConnectionId}/reauthorizations",{params: connection(externalConnectionId),- body: { expected_revision: expectedRevision },+ body: {+ expected_revision: expectedRevision,+ ...(await desktopCallback()),+ },},),),diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsxindex 3e0da32a..fec4737a 100644--- a/apps/web/src/main.tsx+++ b/apps/web/src/main.tsx@@ -16,6 +16,7 @@ import "@fontsource-variable/roboto-slab";import "@/app/globals.css";import { loadHanFont } from "@/app/han-font";import { installVitePreloadRecovery } from "@/app/vite-preload-recovery";+import { DesktopConnectorReturn } from "@/features/apps/desktop-connector-return";import { createBrowserTeamHubRuntime } from "@/features/teamhub/browser-teamhub-runtime";import { teamHubData } from "@/features/teamhub/teamhub-api";import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";@@ -85,6 +86,7 @@ async function startBrowserApp() {<StrictMode><QueryClientProvider client={queryClient}><TeamHubRuntimeProvider runtime={runtime}>+ <DesktopConnectorReturn /><RouterProvider router={router} /></TeamHubRuntimeProvider></QueryClientProvider>diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.goindex a1939568..9433ed27 100644--- a/contracts/generated/go/teamhubpublic/openapi.gen.go+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go@@ -4812,13 +4812,18 @@ type CreatableAgentType string// CreateExternalConnectionReauthorizationRequest defines model for CreateExternalConnectionReauthorizationRequest.type CreateExternalConnectionReauthorizationRequest struct {- ExpectedRevision int64 `json:"expected_revision"`+ // DesktopCallbackUrl One-time OAuth return address on the desktop client's IPv4 loopback listener.+ DesktopCallbackUrl *ExternalConnectionDesktopCallbackURL `json:"desktop_callback_url,omitempty"`+ ExpectedRevision int64 `json:"expected_revision"`}// CreateExternalConnectionRequest defines model for CreateExternalConnectionRequest.type CreateExternalConnectionRequest struct {// AppKey Stable catalog key. TeamHub validates app availability and capabilities.AppKey ExternalAppKey `json:"app_key"`++ // DesktopCallbackUrl One-time OAuth return address on the desktop client's IPv4 loopback listener.+ DesktopCallbackUrl *ExternalConnectionDesktopCallbackURL `json:"desktop_callback_url,omitempty"`}// CreateRoomHistoryShare defines model for CreateRoomHistoryShare.@@ -5967,6 +5972,9 @@ type ExternalConnectionAgentAccessList struct {Agents []ExternalConnectionAgentAccess `json:"agents"`}+// ExternalConnectionDesktopCallbackURL One-time OAuth return address on the desktop client's IPv4 loopback listener.+type ExternalConnectionDesktopCallbackURL = string+// ExternalConnectionList defines model for ExternalConnectionList.type ExternalConnectionList struct {Connections []ExternalConnection `json:"connections"`diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.tsindex cea0acf5..4ca8e5d4 100644--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts@@ -6691,8 +6691,11 @@ export interface components {ExternalConnectionList: {connections: components["schemas"]["ExternalConnection"][];};+ /** @description One-time OAuth return address on the desktop client's IPv4 loopback listener. */+ ExternalConnectionDesktopCallbackURL: string;CreateExternalConnectionRequest: {app_key: components["schemas"]["ExternalAppKey"];+ desktop_callback_url?: components["schemas"]["ExternalConnectionDesktopCallbackURL"];};CompleteExternalConnectionAuthorizationRequest: {/** @description The connected account the Composio callback named, when it named one. */@@ -6727,6 +6730,7 @@ export interface components {CreateExternalConnectionReauthorizationRequest: {/** Format: int64 */expected_revision: number;+ desktop_callback_url?: components["schemas"]["ExternalConnectionDesktopCallbackURL"];};SlackConversation: {id: string;diff --git a/contracts/openapi/components/external-sources.yaml b/contracts/openapi/components/external-sources.yamlindex 3ca84699..8b5458d9 100644--- a/contracts/openapi/components/external-sources.yaml+++ b/contracts/openapi/components/external-sources.yaml@@ -93,6 +93,13 @@ components:properties:app_key:$ref: "#/components/schemas/ExternalAppKey"+ desktop_callback_url:+ $ref: "#/components/schemas/ExternalConnectionDesktopCallbackURL"+ ExternalConnectionDesktopCallbackURL:+ type: string+ maxLength: 100+ description: One-time OAuth return address on the desktop client's IPv4 loopback listener.+ pattern: '^http://127\.0\.0\.1:[1-9][0-9]{0,4}/oauth/connector/[a-f0-9]{48}$'ExternalConnectionStatus:type: stringenum:@@ -376,3 +383,5 @@ components:required: [expected_revision]properties:expected_revision: { type: integer, format: int64, minimum: 1 }+ desktop_callback_url:+ $ref: "#/components/schemas/ExternalConnectionDesktopCallbackURL"