Elffuss BraidHub

kikocis/continue public

Merge pull request #7651 from JonZeolla/feat/oauth/redirect_uri

feat(oauth): use asExternalUrl to get the correct callback
Changesetf2c19af1c135a977798eadda25d497450678576bf68b39d39b7ea83124bb59a4
AuthorDallin Romney <dallinromney@gmail.com> · 2025-09-22 13:32 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-22 13:32 -07:00
Parents9070cd9e51aa, b916208dc74e

Browse the files at this changeset

5 files changed

modified core/config/types.ts +2 −0
@@ -687,6 +687,8 @@
687687
688688 openUrl(url: string): Promise<void>;
689689
690+ getExternalUri?(uri: string): Promise<string>;
691+
690692 runCommand(command: string): Promise<void>;
691693
692694 saveFile(filepath: string): Promise<void>;
modified core/context/mcp/MCPOauth.ts +193 −63
@@ -12,65 +12,121 @@
1212
1313 import http from "http";
1414 import url from "url";
15+import crypto from "crypto";
1516 import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
1617
17-let authenticatingMCPContext = null as {
18- authenticatingServer: MCPServerStatus;
19- ide: IDE;
20-} | null;
18+// Use a Map to support concurrent authentications for different servers
19+const authenticatingContexts = new Map<
20+ string,
21+ {
22+ authenticatingServer: MCPServerStatus;
23+ ide: IDE;
24+ state?: string;
25+ }
26+>();
27+
28+// Map state parameters to server URLs for OAuth callback matching
29+const stateToServerUrl = new Map<string, string>();
2130
2231 const PORT = 3000;
2332
24-const server = http.createServer((req, res) => {
25- try {
26- if (!req.url) {
27- throw new Error("no url found");
28- }
33+let serverInstance: http.Server | null = null;
2934
30- const parsedUrl = url.parse(req.url, true);
31- if (!parsedUrl.query["code"]) {
32- throw new Error("no query params found");
33- }
35+const createServerForOAuth = () =>
36+ http.createServer((req, res) => {
37+ try {
38+ if (!req.url) {
39+ throw new Error("no url found");
40+ }
41+
42+ const parsedUrl = url.parse(req.url, true);
43+ if (!parsedUrl.query["code"]) {
44+ throw new Error("no query params found");
45+ }
3446
35- void handleMCPOauthCode(parsedUrl.query["code"] as string);
47+ const code = parsedUrl.query["code"] as string;
48+ const state = parsedUrl.query["state"] as string | undefined;
3649
37- const html = `
50+ void handleMCPOauthCode(code, state);
51+
52+ const html = `
3853 <!DOCTYPE html>
3954 <html>
4055 <head><title>Authentication Complete</title></head>
4156 <body>Authentication Complete. You can close this page now.</body>
4257 </html>`;
4358
44- res.writeHead(200, {
45- "Content-Type": "text/html",
46- });
47- res.end(html);
48- } catch (error) {
49- res.writeHead(400, { "Content-Type": "text/plain" });
50- res.end(`Unexpected redirect error: ${(error as Error).message}`);
51- }
52-});
59+ res.writeHead(200, {
60+ "Content-Type": "text/html",
61+ });
62+ res.end(html);
63+ } catch (error) {
64+ res.writeHead(400, { "Content-Type": "text/plain" });
65+ res.end(`Unexpected redirect error: ${(error as Error).message}`);
66+ }
67+ });
5368
5469 type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
5570 type MCPOauthStorageKey = keyof MCPOauthStorage;
5671
5772 class MCPConnectionOauthProvider implements OAuthClientProvider {
5873 private globalContext: GlobalContext;
74+ private _redirectUrl: string;
75+ private _redirectUrlInitialized: Promise<void>;
5976
6077 constructor(
6178 public oauthServerUrl: string,
6279 private ide: IDE,
6380 ) {
6481 this.globalContext = new GlobalContext();
82+ // Set default redirect URL immediately for synchronous access
83+ this._redirectUrl = `http://localhost:${PORT}`;
84+ // Initialize actual redirect URL asynchronously
85+ this._redirectUrlInitialized = this._initializeRedirectUrl();
86+ }
87+
88+ private async _initializeRedirectUrl(): Promise<void> {
89+ try {
90+ // If IDE supports getExternalUri (VS Code extension), use it for dynamic redirect URI
91+ if (this.ide.getExternalUri) {
92+ const localUri = `http://localhost:${PORT}`;
93+ const externalUri = await this.ide.getExternalUri(localUri);
94+ this._redirectUrl = externalUri;
95+ }
96+ // Otherwise keep the default localhost URL
97+ } catch (error) {
98+ console.error("Failed to initialize redirect URL:", error);
99+ // Keep default URL on error
100+ }
65101 }
66102
67103 get redirectUrl() {
68- return `http://localhost:${PORT}`; // TODO: this has to be a hub url or should we spin up a server?
104+ // Always return a valid URL, even if initialization is pending
105+ return this._redirectUrl;
106+ }
107+
108+ getRedirectUrlWithState(state: string): string {
109+ // Add state parameter to redirect URL
110+ const urlObj = new URL(this._redirectUrl);
111+ urlObj.searchParams.set("state", state);
112+ return urlObj.toString();
113+ }
114+
115+ async ensureRedirectUrl(): Promise<string> {
116+ // Wait for initialization to complete before returning
117+ await this._redirectUrlInitialized;
118+ return this._redirectUrl;
69119 }
70120
71121 get clientMetadata() {
122+ // Generate state parameter if needed
123+ const state = authenticatingContexts.get(this.oauthServerUrl)?.state;
124+ const redirectUri = state
125+ ? this.getRedirectUrlWithState(state)
126+ : this.redirectUrl;
127+
72128 return {
73- redirect_uris: [this.redirectUrl],
129+ redirect_uris: [redirectUri],
74130 token_endpoint_auth_method: "none",
75131 grant_types: ["authorization_code", "refresh_token"],
76132 response_types: ["code"],
@@ -151,14 +207,28 @@
151207 }
152208
153209 async redirectToAuthorization(authorizationUrl: URL) {
154- if (!server.listening) {
155- server.listen(PORT, () => {
156- console.debug(
157- `Server started for MCP Oauth process at http://localhost:${PORT}/`,
158- );
159- });
210+ // Ensure redirect URL is initialized before proceeding
211+ await this.ensureRedirectUrl();
212+
213+ // Only create and start local server if using localhost redirect
214+ // For web-based VS Code, the redirect will be handled by VS Code's built-in mechanism
215+ if (!this.ide.getExternalUri || this._redirectUrl.includes("localhost")) {
216+ if (!serverInstance) {
217+ serverInstance = createServerForOAuth();
218+ }
219+ if (!serverInstance.listening) {
220+ await new Promise<void>((resolve, reject) => {
221+ serverInstance!.listen(PORT, () => {
222+ console.debug(
223+ `Server started for MCP Oauth process at http://localhost:${PORT}/`,
224+ );
225+ resolve();
226+ });
227+ serverInstance!.on("error", reject);
228+ });
229+ }
160230 }
161- void this.ide.openUrl(authorizationUrl.toString());
231+ await this.ide.openUrl(authorizationUrl.toString());
162232 }
163233 }
164234
@@ -175,49 +245,109 @@
175245 export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
176246 const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
177247 const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
178- authenticatingMCPContext = {
248+ // Ensure redirect URL is ready before starting auth
249+ await authProvider.ensureRedirectUrl();
250+
251+ // Generate a unique state parameter for this auth flow
252+ const state = crypto.randomUUID();
253+
254+ // Store context for this specific server with state
255+ authenticatingContexts.set(mcpServerUrl, {
179256 authenticatingServer: mcpServer,
180257 ide,
181- };
182- return await auth(authProvider, {
183- serverUrl: mcpServerUrl,
258+ state,
184259 });
260+
261+ // Map state to server URL for callback matching
262+ stateToServerUrl.set(state, mcpServerUrl);
263+
264+ try {
265+ return await auth(authProvider, {
266+ serverUrl: mcpServerUrl,
267+ });
268+ } catch (error) {
269+ // Clean up on error
270+ authenticatingContexts.delete(mcpServerUrl);
271+ stateToServerUrl.delete(state);
272+ throw error;
273+ }
185274 }
186275
187276 /**
188277 * handle the authentication code received from the oauth redirect
189278 */
190-async function handleMCPOauthCode(authorizationCode: string) {
191- if (!authenticatingMCPContext) {
192- return;
279+async function handleMCPOauthCode(authorizationCode: string, state?: string) {
280+ let serverUrl: string | undefined;
281+ let context:
282+ | { authenticatingServer: MCPServerStatus; ide: IDE; state?: string }
283+ | undefined;
284+
285+ if (state) {
286+ // Use state parameter to find the correct server
287+ serverUrl = stateToServerUrl.get(state);
288+ if (serverUrl) {
289+ context = authenticatingContexts.get(serverUrl);
290+ }
291+ } else {
292+ // Fallback: if no state or single context, use the first one
293+ const contexts = Array.from(authenticatingContexts.entries());
294+ if (contexts.length === 1) {
295+ [serverUrl, context] = contexts[0];
296+ }
193297 }
194- const { ide, authenticatingServer } = authenticatingMCPContext;
195- const serverUrl = (authenticatingServer.transport as SSEOptions).url;
196298
197- if (!serverUrl) {
198- void ide.showToast("error", "No MCP server url found for authentication");
299+ if (!context || !serverUrl) {
300+ console.error("No matching authenticating context found for state:", state);
199301 return;
200302 }
201- if (!authorizationCode) {
202- void ide.showToast(
203- "error",
204- `No MCP authorization code found for ${serverUrl}`,
205- );
206- return;
207- }
208- server.close(() => console.debug("Server for MCP Oauth process was closed"));
209- const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
210- const authStatus = await auth(authProvider, {
211- serverUrl,
212- authorizationCode,
213- });
214- if (authStatus === "AUTHORIZED") {
215- const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
216- await MCPManagerSingleton.getInstance().refreshConnection(
217- authenticatingServer.id,
218- );
303+
304+ const { ide, authenticatingServer } = context;
305+
306+ try {
307+ if (!serverUrl) {
308+ throw new Error("No MCP server url found for authentication");
309+ }
310+ if (!authorizationCode) {
311+ throw new Error(`No MCP authorization code found for ${serverUrl}`);
312+ }
313+
314+ // Close the server before processing auth
315+ if (serverInstance) {
316+ await new Promise<void>((resolve) => {
317+ serverInstance!.close(() => {
318+ console.debug("Server for MCP Oauth process was closed");
319+ serverInstance = null;
320+ resolve();
321+ });
322+ });
323+ }
324+
325+ const authProvider = new MCPConnectionOauthProvider(serverUrl, ide);
326+ await authProvider.ensureRedirectUrl();
327+ const authStatus = await auth(authProvider, {
328+ serverUrl,
329+ authorizationCode,
330+ });
331+
332+ if (authStatus === "AUTHORIZED") {
333+ const { MCPManagerSingleton } = await import("./MCPManagerSingleton"); // put dynamic import to avoid cyclic imports
334+ await MCPManagerSingleton.getInstance().refreshConnection(
335+ authenticatingServer.id,
336+ );
337+ }
338+ } catch (error) {
339+ const errorMessage = error instanceof Error ? error.message : String(error);
340+ console.error("OAuth authorization failed:", errorMessage);
341+ if (context?.ide) {
342+ await context.ide.showToast("error", `OAuth failed: ${errorMessage}`);
343+ }
344+ } finally {
345+ // Always clean up the context and state mapping
346+ authenticatingContexts.delete(serverUrl);
347+ if (state) {
348+ stateToServerUrl.delete(state);
349+ }
219350 }
220- authenticatingMCPContext = null;
221351 }
222352
223353 export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
modified core/context/mcp/MCPOauth.vitest.ts +149 −0
@@ -33,6 +33,7 @@
3333 mockIde = {
3434 openUrl: vi.fn(),
3535 showToast: vi.fn(),
36+ getExternalUri: vi.fn((uri) => Promise.resolve(uri)),
3637 };
3738
3839 mockMcpServer = {
@@ -178,4 +179,152 @@
178179 });
179180 });
180181 });
182+
183+ describe("redirect URL handling", () => {
184+ test("should use getExternalUri when available for VS Code", async () => {
185+ const vscodeIde = {
186+ ...mockIde,
187+ getExternalUri: vi.fn((uri) =>
188+ Promise.resolve("https://vscode.dev/redirect"),
189+ ),
190+ };
191+
192+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
193+ const mockAuth = vi.mocked(auth);
194+ mockAuth.mockResolvedValue("AUTHORIZED");
195+
196+ await performAuth(mockMcpServer, vscodeIde);
197+
198+ expect(vscodeIde.getExternalUri).toHaveBeenCalledWith(
199+ "http://localhost:3000",
200+ );
201+ });
202+
203+ test("should fallback to localhost when getExternalUri is not available", async () => {
204+ const ideWithoutExternalUri = {
205+ openUrl: vi.fn(() => Promise.resolve()),
206+ showToast: vi.fn(() => Promise.resolve()),
207+ };
208+
209+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
210+ const mockAuth = vi.mocked(auth);
211+ mockAuth.mockResolvedValue("AUTHORIZED");
212+
213+ await performAuth(mockMcpServer, ideWithoutExternalUri as any);
214+
215+ // Should still work without getExternalUri
216+ expect(mockAuth).toHaveBeenCalled();
217+ });
218+
219+ test("should handle getExternalUri errors gracefully", async () => {
220+ const errorIde = {
221+ ...mockIde,
222+ getExternalUri: vi.fn(() => Promise.reject(new Error("Network error"))),
223+ };
224+
225+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
226+ const mockAuth = vi.mocked(auth);
227+ mockAuth.mockResolvedValue("AUTHORIZED");
228+
229+ // Should not throw, should fallback to localhost
230+ await performAuth(mockMcpServer, errorIde);
231+
232+ expect(mockAuth).toHaveBeenCalled();
233+ });
234+ });
235+
236+ describe("concurrent authentication", () => {
237+ test("should handle multiple concurrent auth flows", async () => {
238+ const server1 = {
239+ id: "server-1",
240+ transport: { type: "sse" as const, url: "https://server1.com" },
241+ status: "connected" as const,
242+ errors: [],
243+ isProtectedResource: false,
244+ prompts: [],
245+ tools: [],
246+ resources: [],
247+ resourceTemplates: [],
248+ name: "server-1",
249+ };
250+ const server2 = {
251+ id: "server-2",
252+ transport: { type: "sse" as const, url: "https://server2.com" },
253+ status: "connected" as const,
254+ errors: [],
255+ isProtectedResource: false,
256+ prompts: [],
257+ tools: [],
258+ resources: [],
259+ resourceTemplates: [],
260+ name: "server-2",
261+ };
262+
263+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
264+ const mockAuth = vi.mocked(auth);
265+ mockAuth.mockResolvedValue("AUTHORIZED");
266+
267+ // Start two auth flows concurrently
268+ const [result1, result2] = await Promise.all([
269+ performAuth(server1, mockIde),
270+ performAuth(server2, mockIde),
271+ ]);
272+
273+ expect(result1).toBe("AUTHORIZED");
274+ expect(result2).toBe("AUTHORIZED");
275+ expect(mockAuth).toHaveBeenCalledTimes(2);
276+ });
277+ });
278+
279+ describe("error handling", () => {
280+ test("should clean up context on auth failure", async () => {
281+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
282+ const mockAuth = vi.mocked(auth);
283+
284+ // First successful call to set up the context
285+ mockAuth.mockResolvedValueOnce("AUTHORIZED");
286+ await performAuth(mockMcpServer, mockIde);
287+
288+ // Reset mock for the failure test
289+ mockAuth.mockRejectedValueOnce(new Error("Auth failed"));
290+
291+ // Second call that should fail and clean up
292+ await expect(performAuth(mockMcpServer, mockIde)).rejects.toThrow(
293+ "Auth failed",
294+ );
295+
296+ // Verify auth was called twice
297+ expect(mockAuth).toHaveBeenCalledTimes(2);
298+
299+ // The context cleanup happens internally in performAuth's catch block
300+ // We can verify it indirectly by checking that a subsequent auth call works
301+ mockAuth.mockResolvedValueOnce("AUTHORIZED");
302+ const result = await performAuth(mockMcpServer, mockIde);
303+ expect(result).toBe("AUTHORIZED");
304+ });
305+
306+ test("should handle missing server URL", async () => {
307+ const invalidServer = {
308+ id: "invalid",
309+ transport: { type: "sse" as const, url: "" },
310+ status: "connected" as const,
311+ errors: [],
312+ isProtectedResource: false,
313+ prompts: [],
314+ tools: [],
315+ resources: [],
316+ resourceTemplates: [],
317+ name: "invalid",
318+ };
319+
320+ const { auth } = await import("@modelcontextprotocol/sdk/client/auth.js");
321+ const mockAuth = vi.mocked(auth);
322+ mockAuth.mockResolvedValue("AUTHORIZED");
323+
324+ await performAuth(invalidServer, mockIde);
325+
326+ // Should still attempt auth with empty URL
327+ expect(mockAuth).toHaveBeenCalled();
328+ });
329+ });
181330 });
modified core/index.d.ts +2 −0
@@ -819,6 +819,8 @@
819819
820820 openUrl(url: string): Promise<void>;
821821
822+ getExternalUri?(uri: string): Promise<string>;
823+
822824 runCommand(command: string, options?: TerminalOptions): Promise<void>;
823825
824826 saveFile(fileUri: string): Promise<void>;
modified extensions/vscode/src/VsCodeIde.ts +6 −0
@@ -408,6 +408,12 @@
408408 await vscode.env.openExternal(vscode.Uri.parse(url));
409409 }
410410
411+ async getExternalUri(uri: string): Promise<string> {
412+ const vsCodeUri = vscode.Uri.parse(uri);
413+ const externalUri = await vscode.env.asExternalUri(vsCodeUri);
414+ return externalUri.toString(true);
415+ }
416+
411417 async getOpenFiles(): Promise<string[]> {
412418 return this.ideUtils.getOpenFiles().map((uri) => uri.toString());
413419 }