File size: 4,994 Bytes
05c5ed5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import { NextRequest } from "next/server";
import { mcpOAuthRepository } from "@/lib/db/repository";
import { mcpClientsManager } from "lib/ai/mcp/mcp-manager";

import globalLogger from "logger";
import { colorize } from "consola/utils";

interface OAuthResponseOptions {
  type: "success" | "error";
  title: string;
  heading: string;
  message: string;
  postMessageType: string;
  postMessageData: Record<string, any>;
  statusCode: number;
}

function createOAuthResponsePage(options: OAuthResponseOptions): Response {
  const {
    type,
    title,
    heading,
    message,
    postMessageType,
    postMessageData,
    statusCode,
  } = options;
  if (type === "success") {
    logger.info("OAuth callback successful", message);
  } else {
    logger.error("OAuth callback failed", message);
  }
  const colorClass = type === "success" ? "success" : "error";
  const color = type === "success" ? "#22c55e" : "#ef4444";

  const html = `
<!DOCTYPE html>
<html>
<head>
  <title>${title}</title>
  <style>
    body { font-family: system-ui, sans-serif; text-align: center; padding: 2rem; }
    .${colorClass} { color: ${color}; }
  </style>
</head>
<body>
  <script>
    try {
      window.opener?.postMessage({
        type: '${postMessageType}',
        ${Object.entries(postMessageData)
          .map(([key, value]) => `${key}: '${value}'`)
          .join(", ")}
      }, window.location.origin);
    } catch (e) {
      console.error('Failed to post message:', e);
    }
    setTimeout(() => window.close(), 1000);
  </script>
  <div class="${colorClass}">
    <h2>${heading}</h2>
    <p>${message}</p>
    <p>This window will close automatically.</p>
  </div>
</body>
</html>`;

  return new Response(html, {
    status: statusCode,
    headers: { "Content-Type": "text/html" },
  });
}

const logger = globalLogger.withDefaults({
  message: colorize("bgGreen", `MCP OAuth Callback: `),
});

/**
 * OAuth callback endpoint for MCP servers
 * Handles the authorization code exchange and token storage
 */
export async function GET(request: NextRequest) {
  logger.info("OAuth callback received Authorization Code");
  const { searchParams } = new URL(request.url);

  const callbackData = {
    code: searchParams.get("code") || undefined,
    state: searchParams.get("state") || undefined,
    error: searchParams.get("error") || undefined,
    error_description: searchParams.get("error_description") || undefined,
  };

  // Handle OAuth error responses
  if (callbackData.error) {
    return createOAuthResponsePage({
      type: "error",
      title: "OAuth Error",
      heading: "Authentication Failed",
      message: `Error: ${callbackData.error}<br/>${callbackData.error_description || "Unknown error occurred"}`,
      postMessageType: "MCP_OAUTH_ERROR",
      postMessageData: {
        error: callbackData.error,
        error_description: callbackData.error_description || "Unknown error",
      },
      statusCode: 400,
    });
  }

  // Validate required parameters
  if (!callbackData.code || !callbackData.state) {
    return createOAuthResponsePage({
      type: "error",
      title: "OAuth Error",
      heading: "Authentication Failed",
      message: "Missing required parameters",
      postMessageType: "MCP_OAUTH_ERROR",
      postMessageData: {
        error: "invalid_request",
        error_description: "Missing authorization code or state parameter",
      },
      statusCode: 400,
    });
  }

  // Find the OAuth session by state
  const session = await mcpOAuthRepository.getSessionByState(
    callbackData.state,
  );
  if (!session) {
    return createOAuthResponsePage({
      type: "error",
      title: "OAuth Error",
      heading: "Authentication Failed",
      message: "Invalid or expired session",
      postMessageType: "MCP_OAUTH_ERROR",
      postMessageData: {
        error: "invalid_state",
        error_description: "Invalid or expired state parameter",
      },
      statusCode: 400,
    });
  }

  const client = await mcpClientsManager.getClient(session.mcpServerId);

  try {
    await client?.client.finishAuth(callbackData.code, callbackData.state);
    await mcpClientsManager.refreshClient(session.mcpServerId);

    return createOAuthResponsePage({
      type: "success",
      title: "OAuth Success",
      heading: "Authentication Successful!",
      message: "You can now close this window.",
      postMessageType: "MCP_OAUTH_SUCCESS",
      postMessageData: {
        success: true,
      },
      statusCode: 200,
    });
  } catch (error: any) {
    logger.error("OAuth callback failed", error);
    return createOAuthResponsePage({
      type: "error",
      title: "OAuth Error",
      heading: "Authentication Failed",
      message: error.message || "Failed to complete the authentication process",
      postMessageType: "MCP_OAUTH_ERROR",
      postMessageData: {
        error: "auth_failed",
        error_description: "Failed to complete authentication",
      },
      statusCode: 500,
    });
  }
}