-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathcallbackServer.ts
More file actions
222 lines (200 loc) · 6.66 KB
/
Copy pathcallbackServer.ts
File metadata and controls
222 lines (200 loc) · 6.66 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import * as http from "http"
import { t } from "../../../i18n"
import { OAUTH_FLOW_TIMEOUT_MS } from "../constants"
const HTML_RESPONSE_CONTENT_TYPE = "text/html; charset=utf-8"
const CHARSET_META_TAG = '<meta charset="utf-8">'
export interface CallbackResult {
code?: string
error?: string
error_description?: string
state?: string
}
/**
* Starts a local HTTP server to handle OAuth callback.
* @param port Optional port to use (defaults to random available port)
* @param expectedState Optional expected state for CSRF protection
* @returns Promise<{server: http.Server, port: number, result: Promise<CallbackResult>}>
*/
export function startCallbackServer(
port?: number,
expectedState?: string,
): Promise<{
server: http.Server
port: number
result: Promise<CallbackResult>
cancel: () => void
}> {
// In test mode, immediately resolve with mock data
if (process.env.MCP_OAUTH_TEST_MODE === "true") {
return new Promise((resolve) => {
const mockServer = http.createServer()
resolve({
server: mockServer,
port: 3000,
result: Promise.resolve({ code: "test-auth-code", state: expectedState }),
cancel: () => {},
})
})
}
return new Promise((resolve, reject) => {
const server = http.createServer()
server.listen(port || 0, "127.0.0.1", () => {
const address = server.address()
if (!address || typeof address === "string") {
reject(new Error("Failed to get server address"))
return
}
const actualPort = address.port
let resolveResult!: (value: CallbackResult) => void
let rejectResult!: (reason: unknown) => void
const resultPromise = new Promise<CallbackResult>((res, rej) => {
resolveResult = res
rejectResult = rej
})
let resolved = false
const timeout = setTimeout(() => {
if (!resolved) {
resolved = true
rejectResult(new Error("Callback timeout"))
server.close()
}
}, OAUTH_FLOW_TIMEOUT_MS)
const cancel = () => {
if (!resolved) {
resolved = true
clearTimeout(timeout)
rejectResult(new Error("Callback cancelled"))
}
}
server.on("request", (req: any, res: any) => {
if (resolved) return
const url = new URL(req.url || "", `http://localhost:${actualPort}`)
const pathname = url.pathname
if (pathname === "/callback") {
resolved = true
clearTimeout(timeout)
const code = url.searchParams.get("code")
const error = url.searchParams.get("error")
const errorDescription = url.searchParams.get("error_description")
const state = url.searchParams.get("state")
const hasError = !!error
// Verify state for CSRF protection
if (expectedState && state !== expectedState) {
res.writeHead(400, {
"Content-Type": HTML_RESPONSE_CONTENT_TYPE,
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
})
res.end(`
<!DOCTYPE html>
<html>
<head>
${CHARSET_META_TAG}
<title>${t("mcp:oauth.callback.title")}</title>
</head>
<body>
<h1>${t("mcp:oauth.callback.failed")}</h1>
<p>${t("mcp:oauth.callback.invalid_state")}</p>
</body>
</html>
`)
rejectResult(new Error("Invalid state parameter"))
server.close()
return
}
// Send HTML response
res.writeHead(200, {
"Content-Type": HTML_RESPONSE_CONTENT_TYPE,
"Content-Security-Policy":
"default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'",
})
res.end(`
<!DOCTYPE html>
<html>
<head>
${CHARSET_META_TAG}
<title>${t("mcp:oauth.callback.title")}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 400px; margin: 50px auto; text-align: center; padding: 20px; }
h1 { color: #28a745; }
.error h1 { color: #dc3545; }
.spinner { border: 4px solid #f3f3f3; border-top: 4px solid #28a745; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin: 20px auto; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
button { background: #007acc; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-size: 16px; }
.countdown { font-size: 18px; margin: 10px 0; }
</style>
</head>
<body>
<h1 id="title">${hasError ? t("mcp:oauth.callback.failed") : t("mcp:oauth.callback.success")}</h1>
<div class="spinner" id="spinner" style="${hasError ? "display:none;" : ""}"></div>
<p id="message">
${hasError ? t("mcp:oauth.callback.auth_failed") : t("mcp:oauth.callback.auth_success")}
</p>
<div id="countdown" class="countdown" style="${hasError ? "display:none;" : ""}">${t("mcp:oauth.callback.server_connection_complete")}</div>
<script>
const isError = ${hasError ? "true" : "false"};
if (!isError) {
let count = 5;
const countdownEl = document.getElementById('countdown');
if (countdownEl) {
countdownEl.innerHTML = \`${t("mcp:oauth.callback.tab_closing_in", { count: 5 })}\`;
}
const timer = setInterval(() => {
count--;
const currentCountEl = document.getElementById('count');
if (currentCountEl) currentCountEl.textContent = count;
if (count <= 0) {
clearInterval(timer);
window.close();
if (countdownEl) {
countdownEl.textContent = \`${t("mcp:oauth.callback.safe_to_close")}\`;
}
}
}, 1000);
}
</script>
</body>
</html>
`)
resolveResult({
code: code || undefined,
error: error || undefined,
error_description: errorDescription || undefined,
state: state || undefined,
})
// Close server immediately after response drains
res.on("finish", () => {
server.close()
})
} else {
res.writeHead(404)
res.end("Not found")
}
})
server.on("error", (error: any) => {
if (!resolved) {
resolved = true
clearTimeout(timeout)
rejectResult(error)
}
})
resolve({
server,
port: actualPort,
result: resultPromise,
cancel,
})
})
server.on("error", reject)
})
}
/**
* Stops the callback server and cancels any pending result promise so its
* timeout doesn't fire after the provider is already closed.
*/
export function stopCallbackServer(server: http.Server, cancel: () => void): Promise<void> {
cancel()
return new Promise((resolve) => {
server.close(() => resolve())
})
}