()
| 302 | let pendingOAuth: PendingOAuth | undefined |
| 303 | |
| 304 | async function startOAuthServer(): Promise<{ port: number; redirectUri: string }> { |
| 305 | if (oauthServer) return { port: OAUTH_PORT, redirectUri: REDIRECT_URI } |
| 306 | |
| 307 | const server = createServer((req, res) => { |
| 308 | const reqUrl = req.url || "/" |
| 309 | const url = new URL(reqUrl, `http://${OAUTH_HOST}:${OAUTH_PORT}`) |
| 310 | |
| 311 | const origin = req.headers["origin"] |
| 312 | const allowOrigin = typeof origin === "string" && CORS_ALLOWED_ORIGINS.has(origin) ? origin : "" |
| 313 | if (allowOrigin) { |
| 314 | res.setHeader("Access-Control-Allow-Origin", allowOrigin) |
| 315 | res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS") |
| 316 | res.setHeader("Access-Control-Allow-Headers", "Content-Type") |
| 317 | res.setHeader("Access-Control-Allow-Private-Network", "true") |
| 318 | res.setHeader("Vary", "Origin") |
| 319 | } |
| 320 | |
| 321 | if (req.method === "OPTIONS") { |
| 322 | res.writeHead(204) |
| 323 | res.end() |
| 324 | return |
| 325 | } |
| 326 | |
| 327 | if (url.pathname === OAUTH_REDIRECT_PATH) { |
| 328 | const code = url.searchParams.get("code") |
| 329 | const state = url.searchParams.get("state") |
| 330 | const error = url.searchParams.get("error") |
| 331 | const errorDescription = url.searchParams.get("error_description") |
| 332 | |
| 333 | if (error) { |
| 334 | const errorMsg = errorDescription || error |
| 335 | pendingOAuth?.reject(new Error(errorMsg)) |
| 336 | pendingOAuth = undefined |
| 337 | res.writeHead(200, { "Content-Type": "text/html" }) |
| 338 | res.end(OauthCallbackPage.error(errorMsg, { provider: "xAI" })) |
| 339 | return |
| 340 | } |
| 341 | |
| 342 | if (!code) { |
| 343 | const errorMsg = "Missing authorization code" |
| 344 | pendingOAuth?.reject(new Error(errorMsg)) |
| 345 | pendingOAuth = undefined |
| 346 | res.writeHead(400, { "Content-Type": "text/html" }) |
| 347 | res.end(OauthCallbackPage.error(errorMsg, { provider: "xAI" })) |
| 348 | return |
| 349 | } |
| 350 | |
| 351 | if (!pendingOAuth || state !== pendingOAuth.state) { |
| 352 | const errorMsg = "Invalid state - potential CSRF attack" |
| 353 | pendingOAuth?.reject(new Error(errorMsg)) |
| 354 | pendingOAuth = undefined |
| 355 | res.writeHead(400, { "Content-Type": "text/html" }) |
| 356 | res.end(OauthCallbackPage.error(errorMsg, { provider: "xAI" })) |
| 357 | return |
| 358 | } |
| 359 | |
| 360 | const current = pendingOAuth |
| 361 | pendingOAuth = undefined |
no test coverage detected