|
| 1 | +import { env } from "cloudflare:workers"; |
1 | 2 | import type { APIRoute } from "astro"; |
2 | | -import { getAuth } from "@/lib/auth"; |
| 3 | +import { |
| 4 | + DEFAULT_MCP_SESSION, |
| 5 | + DEFAULT_MCP_USER, |
| 6 | + ensureDefaultUserAndSession, |
| 7 | + getAuth, |
| 8 | + hashToken, |
| 9 | +} from "@/lib/auth"; |
3 | 10 |
|
4 | 11 | export const prerender = false; |
5 | 12 |
|
6 | 13 | export const ALL: APIRoute = async ({ request, locals }) => { |
7 | 14 | const origin = locals.siteUrl.origin; |
8 | 15 | const auth = getAuth(origin); |
| 16 | + const url = new URL(request.url); |
| 17 | + const pathname = url.pathname; |
| 18 | + const db = |
| 19 | + (locals as unknown as { db?: D1Database })?.db ?? |
| 20 | + (env as unknown as { DB?: D1Database })?.DB; |
| 21 | + |
| 22 | + // 1. Authorization Endpoint: Handle automated MCP Account Linking (RFC 6749 §4.1) |
| 23 | + if (pathname === "/oauth2/authorize" && request.method === "GET") { |
| 24 | + const clientId = url.searchParams.get("client_id"); |
| 25 | + const redirectUri = url.searchParams.get("redirect_uri"); |
| 26 | + const responseType = url.searchParams.get("response_type"); |
| 27 | + const state = url.searchParams.get("state"); |
| 28 | + const scope = |
| 29 | + url.searchParams.get("scope") || "read:content search mcp:tools agent"; |
| 30 | + const codeChallenge = url.searchParams.get("code_challenge"); |
| 31 | + const codeChallengeMethod = url.searchParams.get("code_challenge_method"); |
| 32 | + |
| 33 | + // If valid client_id and redirect_uri provided and D1 is available, complete automated account linking |
| 34 | + if (clientId && redirectUri && responseType === "code" && db) { |
| 35 | + try { |
| 36 | + const clientRow = await db |
| 37 | + .prepare("SELECT * FROM oauthClient WHERE clientId = ?") |
| 38 | + .bind(clientId) |
| 39 | + .first<{ |
| 40 | + clientId: string; |
| 41 | + redirectUris: string; |
| 42 | + disabled?: number; |
| 43 | + }>(); |
| 44 | + |
| 45 | + if (clientRow && !clientRow.disabled) { |
| 46 | + // Verify redirectUri matches registered URIs |
| 47 | + let registeredUris: string[] = []; |
| 48 | + try { |
| 49 | + registeredUris = JSON.parse(clientRow.redirectUris); |
| 50 | + } catch { |
| 51 | + registeredUris = [clientRow.redirectUris]; |
| 52 | + } |
| 53 | + |
| 54 | + const isUriAllowed = registeredUris.some( |
| 55 | + (uri) => |
| 56 | + uri === redirectUri || |
| 57 | + redirectUri.startsWith(uri.replace(/\/+$/, "")), |
| 58 | + ); |
| 59 | + |
| 60 | + if (isUriAllowed) { |
| 61 | + // Ensure default user and active session exist |
| 62 | + await ensureDefaultUserAndSession(db); |
| 63 | + |
| 64 | + // Generate secure authorization code |
| 65 | + const code = |
| 66 | + crypto.randomUUID().replace(/-/g, "") + |
| 67 | + crypto.randomUUID().replace(/-/g, ""); |
| 68 | + const identifier = await hashToken(code); |
| 69 | + const now = Date.now(); |
| 70 | + |
| 71 | + const verificationValue = JSON.stringify({ |
| 72 | + type: "authorization_code", |
| 73 | + query: { |
| 74 | + client_id: clientId, |
| 75 | + redirect_uri: redirectUri, |
| 76 | + response_type: "code", |
| 77 | + scope: scope, |
| 78 | + state: state || undefined, |
| 79 | + code_challenge: codeChallenge || undefined, |
| 80 | + code_challenge_method: codeChallengeMethod || undefined, |
| 81 | + }, |
| 82 | + userId: DEFAULT_MCP_USER.id, |
| 83 | + sessionId: DEFAULT_MCP_SESSION.id, |
| 84 | + authTime: now, |
| 85 | + resource: [`${origin}/mcp`], |
| 86 | + }); |
| 87 | + |
| 88 | + const verificationId = `auth_code_${now}_${Math.random().toString(36).slice(2, 8)}`; |
| 89 | + await db |
| 90 | + .prepare( |
| 91 | + `INSERT INTO verification (id, identifier, value, expiresAt, createdAt, updatedAt) |
| 92 | + VALUES (?, ?, ?, ?, ?, ?)`, |
| 93 | + ) |
| 94 | + .bind( |
| 95 | + verificationId, |
| 96 | + identifier, |
| 97 | + verificationValue, |
| 98 | + now + 600_000, // 10 minutes |
| 99 | + now, |
| 100 | + now, |
| 101 | + ) |
| 102 | + .run(); |
| 103 | + |
| 104 | + const dest = new URL(redirectUri); |
| 105 | + dest.searchParams.set("code", code); |
| 106 | + if (state) { |
| 107 | + dest.searchParams.set("state", state); |
| 108 | + } |
| 109 | + dest.searchParams.set("iss", origin); |
| 110 | + |
| 111 | + return new Response(null, { |
| 112 | + status: 302, |
| 113 | + headers: { |
| 114 | + Location: dest.toString(), |
| 115 | + "Cache-Control": "no-store", |
| 116 | + Pragma: "no-cache", |
| 117 | + }, |
| 118 | + }); |
| 119 | + } |
| 120 | + } |
| 121 | + } catch (err) { |
| 122 | + console.error("[oauth2/authorize] D1 auto-link error:", err); |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + // 2. Token Endpoint: Handle authorization code exchange and ensure refresh_token is returned for Gemini Account Linking |
| 128 | + if (pathname === "/oauth2/token" && request.method === "POST") { |
| 129 | + // Clone request to read body if needed |
| 130 | + const clonedReq = request.clone(); |
| 131 | + let clientIdFromBody: string | null = null; |
| 132 | + const authHeader = request.headers.get("authorization"); |
| 133 | + |
| 134 | + try { |
| 135 | + const text = await clonedReq.text(); |
| 136 | + const bodyParams = new URLSearchParams(text); |
| 137 | + clientIdFromBody = bodyParams.get("client_id"); |
| 138 | + } catch { |
| 139 | + // ignore |
| 140 | + } |
| 141 | + |
| 142 | + // Extract clientId from Basic Auth header if present |
| 143 | + if (!clientIdFromBody && authHeader?.toLowerCase().startsWith("basic ")) { |
| 144 | + try { |
| 145 | + const creds = atob(authHeader.slice(6)); |
| 146 | + const colon = creds.indexOf(":"); |
| 147 | + if (colon !== -1) { |
| 148 | + clientIdFromBody = creds.slice(0, colon); |
| 149 | + } |
| 150 | + } catch { |
| 151 | + // ignore |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + const response = await auth.handler(request); |
| 156 | + |
| 157 | + // If successful token response, ensure refresh_token is returned (required by Google Gemini Account Linking) |
| 158 | + if (response.status === 200) { |
| 159 | + try { |
| 160 | + const data = (await response.json()) as Record<string, any>; |
| 161 | + if (data.access_token && !data.refresh_token && clientIdFromBody) { |
| 162 | + const refreshToken = |
| 163 | + crypto.randomUUID().replace(/-/g, "") + |
| 164 | + crypto.randomUUID().replace(/-/g, ""); |
| 165 | + const now = Date.now(); |
| 166 | + const refreshId = `rt_${now}_${Math.random().toString(36).slice(2, 8)}`; |
| 167 | + |
| 168 | + if (db) { |
| 169 | + await db |
| 170 | + .prepare( |
| 171 | + `INSERT INTO oauthRefreshToken (id, token, clientId, sessionId, userId, createdAt, expiresAt, revoked, scopes) |
| 172 | + VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?)`, |
| 173 | + ) |
| 174 | + .bind( |
| 175 | + refreshId, |
| 176 | + refreshToken, |
| 177 | + clientIdFromBody, |
| 178 | + DEFAULT_MCP_SESSION.id, |
| 179 | + DEFAULT_MCP_USER.id, |
| 180 | + now, |
| 181 | + now + 30 * 24 * 3600 * 1000, // 30 days |
| 182 | + data.scope || "read:content search mcp:tools agent", |
| 183 | + ) |
| 184 | + .run(); |
| 185 | + } |
| 186 | + |
| 187 | + data.refresh_token = refreshToken; |
| 188 | + |
| 189 | + const headers = new Headers(response.headers); |
| 190 | + headers.set("content-type", "application/json; charset=utf-8"); |
| 191 | + return new Response(JSON.stringify(data), { |
| 192 | + status: 200, |
| 193 | + statusText: "OK", |
| 194 | + headers, |
| 195 | + }); |
| 196 | + } |
| 197 | + // Return parsed json if refresh_token was already present |
| 198 | + return new Response(JSON.stringify(data), { |
| 199 | + status: 200, |
| 200 | + headers: response.headers, |
| 201 | + }); |
| 202 | + } catch { |
| 203 | + return response; |
| 204 | + } |
| 205 | + } |
| 206 | + |
| 207 | + return response; |
| 208 | + } |
| 209 | + |
| 210 | + // 3. Fallback to Better Auth default handler |
9 | 211 | return auth.handler(request); |
10 | 212 | }; |
0 commit comments