Elffuss BraidHub

kikocis/continue public

3ff29c567dd0 · 10.6 KiBRawPermalink
1import {
2 OAuthClientProvider,
3 auth,
4} from "@modelcontextprotocol/sdk/client/auth.js";
5import {
6 OAuthClientInformationFull,
7 OAuthClientInformationSchema,
8 OAuthTokens,
9 OAuthTokensSchema,
10} from "@modelcontextprotocol/sdk/shared/auth.js";
11import { IDE, MCPServerStatus, SSEOptions } from "../..";
12
13import http from "http";
14import url from "url";
15import { v4 as uuidv4 } from "uuid";
16import { GlobalContext, GlobalContextType } from "../../util/GlobalContext";
17
18// Use a Map to support concurrent authentications for different servers
19const 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
29const stateToServerUrl = new Map<string, string>();
30
31const PORT = 3000;
32
33let serverInstance: http.Server | null = null;
34
35const 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 }
46
47 const code = parsedUrl.query["code"] as string;
48 const state = parsedUrl.query["state"] as string | undefined;
49
50 void handleMCPOauthCode(code, state);
51
52 const html = `
53<!DOCTYPE html>
54<html>
55<head><title>Authentication Complete</title></head>
56<body>Authentication Complete. You can close this page now.</body>
57</html>`;
58
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 });
68
69type MCPOauthStorage = GlobalContextType["mcpOauthStorage"][string];
70type MCPOauthStorageKey = keyof MCPOauthStorage;
71
72class MCPConnectionOauthProvider implements OAuthClientProvider {
73 private globalContext: GlobalContext;
74 private _redirectUrl: string;
75 private _redirectUrlInitialized: Promise<void>;
76
77 constructor(
78 public oauthServerUrl: string,
79 private ide: IDE,
80 ) {
81 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 }
101 }
102
103 get redirectUrl() {
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;
119 }
120
121 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
128 return {
129 redirect_uris: [redirectUri],
130 token_endpoint_auth_method: "none",
131 grant_types: ["authorization_code", "refresh_token"],
132 response_types: ["code"],
133 client_name: "Continue Dev, Inc", // get this from package.json?
134 client_uri: "https://continue.dev", // get this from package.json?
135 };
136 }
137
138 private _getOauthStorage<K extends MCPOauthStorageKey>(key: K) {
139 return this.globalContext.get("mcpOauthStorage")?.[this.oauthServerUrl]?.[
140 key
141 ];
142 }
143
144 private _updateOauthStorage<K extends MCPOauthStorageKey>(
145 key: K,
146 value: MCPOauthStorage[K],
147 ) {
148 const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
149 const existingServerStorage = existingStorage[this.oauthServerUrl] ?? {};
150
151 this.globalContext.update("mcpOauthStorage", {
152 ...existingStorage,
153 [this.oauthServerUrl]: {
154 ...existingServerStorage,
155 [key]: value,
156 },
157 });
158 }
159
160 private _clearOauthStorage() {
161 const existingStorage = this.globalContext.get("mcpOauthStorage") ?? {};
162 delete existingStorage[this.oauthServerUrl];
163 this.globalContext.update("mcpOauthStorage", existingStorage);
164 }
165
166 saveClientInformation(clientInformation: OAuthClientInformationFull) {
167 this._updateOauthStorage("clientInformation", clientInformation);
168 }
169
170 async clientInformation() {
171 const existingClientInformation =
172 this._getOauthStorage("clientInformation");
173 if (!existingClientInformation) {
174 return undefined;
175 }
176 return await OAuthClientInformationSchema.parseAsync(
177 existingClientInformation,
178 );
179 }
180
181 async tokens() {
182 const existingTokens = this._getOauthStorage("tokens");
183 if (!existingTokens) {
184 return undefined;
185 }
186 return await OAuthTokensSchema.parseAsync(existingTokens);
187 }
188
189 saveTokens(tokens: OAuthTokens) {
190 this._updateOauthStorage("tokens", tokens);
191 }
192
193 codeVerifier(): string | Promise<string> {
194 const existingCodeVerifier = this._getOauthStorage("codeVerifier");
195 if (!existingCodeVerifier) {
196 return "";
197 }
198 return existingCodeVerifier;
199 }
200
201 saveCodeVerifier(codeVerifier: string) {
202 this._updateOauthStorage("codeVerifier", codeVerifier);
203 }
204
205 clear() {
206 this._clearOauthStorage();
207 }
208
209 async redirectToAuthorization(authorizationUrl: URL) {
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 }
230 }
231 await this.ide.openUrl(authorizationUrl.toString());
232 }
233}
234
235export async function getOauthToken(mcpServerUrl: string, ide: IDE) {
236 const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
237 const tokens = await authProvider.tokens();
238 return tokens?.access_token;
239}
240
241/**
242 * checks if the authentication is already done for the current server
243 * if not, starts the authentication process by opening a webpage url
244 */
245export async function performAuth(mcpServer: MCPServerStatus, ide: IDE) {
246 const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
247 const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
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 = uuidv4();
253
254 // Store context for this specific server with state
255 authenticatingContexts.set(mcpServerUrl, {
256 authenticatingServer: mcpServer,
257 ide,
258 state,
259 });
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 }
274}
275
276/**
277 * handle the authentication code received from the oauth redirect
278 */
279async 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 }
297 }
298
299 if (!context || !serverUrl) {
300 console.error("No matching authenticating context found for state:", state);
301 return;
302 }
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 }
350 }
351}
352
353export function removeMCPAuth(mcpServer: MCPServerStatus, ide: IDE) {
354 const mcpServerUrl = (mcpServer.transport as SSEOptions).url;
355 const authProvider = new MCPConnectionOauthProvider(mcpServerUrl, ide);
356 authProvider.clear();
357}