|
| 1 | +import type { IncomingMessage, ServerResponse } from "node:http"; |
| 2 | +import { authorizationPage, createAuthorizationCode, isIssuedAccessToken } from "../../src/oauth.js"; |
| 3 | + |
| 4 | +async function readBody(req: IncomingMessage & { body?: unknown }): Promise<URLSearchParams> { |
| 5 | + if (typeof req.body === "string") return new URLSearchParams(req.body); |
| 6 | + if (req.body && typeof req.body === "object") return new URLSearchParams(req.body as Record<string, string>); |
| 7 | + const chunks: Buffer[] = []; |
| 8 | + for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); |
| 9 | + return new URLSearchParams(Buffer.concat(chunks).toString("utf8")); |
| 10 | +} |
| 11 | + |
| 12 | +export default async function handler(req: IncomingMessage & { body?: unknown }, res: ServerResponse) { |
| 13 | + if (req.method === "GET") { |
| 14 | + const url = new URL(req.url || "/api/oauth/authorize", "https://example.invalid"); |
| 15 | + res.setHeader("content-type", "text/html; charset=utf-8"); |
| 16 | + res.writeHead(200); |
| 17 | + res.end(authorizationPage(url.searchParams)); |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + if (req.method !== "POST") { |
| 22 | + res.writeHead(405, { allow: "GET, POST" }); |
| 23 | + res.end("Method not allowed"); |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + const form = await readBody(req); |
| 28 | + const accessToken = form.get("access_token")?.trim() || ""; |
| 29 | + const redirectUri = form.get("redirect_uri")?.trim() || ""; |
| 30 | + const clientId = form.get("client_id")?.trim() || "claude-ai-custom-connector"; |
| 31 | + const state = form.get("state") || ""; |
| 32 | + const responseType = form.get("response_type") || "code"; |
| 33 | + |
| 34 | + if (responseType !== "code" || !redirectUri) { |
| 35 | + res.writeHead(400, { "content-type": "text/html; charset=utf-8" }); |
| 36 | + res.end(authorizationPage(form, "Invalid OAuth request from client.")); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + if (!isIssuedAccessToken(accessToken)) { |
| 41 | + res.writeHead(401, { "content-type": "text/html; charset=utf-8" }); |
| 42 | + res.end(authorizationPage(form, "That access token was not recognized. Paste the token from the Education Agent Skills access email.")); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + const code = createAuthorizationCode({ |
| 47 | + token: accessToken, |
| 48 | + redirectUri, |
| 49 | + clientId, |
| 50 | + codeChallenge: form.get("code_challenge") || undefined, |
| 51 | + codeChallengeMethod: form.get("code_challenge_method") || undefined, |
| 52 | + }); |
| 53 | + |
| 54 | + const redirect = new URL(redirectUri); |
| 55 | + redirect.searchParams.set("code", code); |
| 56 | + if (state) redirect.searchParams.set("state", state); |
| 57 | + res.writeHead(302, { location: redirect.toString(), "cache-control": "no-store" }); |
| 58 | + res.end(); |
| 59 | +} |
0 commit comments