File size: 1,621 Bytes
aad94d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Utility for OAuth authentication with MCP servers
// Usage: import { authenticateWithOAuth } from "./oauth";

export async function authenticateWithOAuth({
  authUrl,
  clientId,
  redirectUri,
  scope = "openid profile",
}: {
  authUrl: string;
  clientId: string;
  redirectUri: string;
  scope?: string;
}): Promise<string> {
  // Open a popup for OAuth login
  const state = Math.random().toString(36).substring(2);
  const url = `${authUrl}?response_type=token&client_id=${encodeURIComponent(
    clientId
  )}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent(
    scope
  )}&state=${state}`;

  return new Promise((resolve, reject) => {
    const popup = window.open(url, "oauth-login", "width=500,height=700");
    if (!popup) return reject("Popup blocked");

    const interval = setInterval(() => {
      try {
        if (!popup || popup.closed) {
          clearInterval(interval);
          reject("Popup closed");
        }
        // Check for access token in URL
        const href = popup.location.href;
        if (href.startsWith(redirectUri)) {
          const hash = popup.location.hash;
          const params = new URLSearchParams(hash.substring(1));
          const token = params.get("access_token");
          if (token) {
            clearInterval(interval);
            popup.close();
            resolve(token);
          } else {
            clearInterval(interval);
            popup.close();
            reject("No access token found");
          }
        }
      } catch (e) {
        // Ignore cross-origin errors until redirect
      }
    }, 500);
  });
}