-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathroute.ts
More file actions
311 lines (273 loc) · 9.31 KB
/
Copy pathroute.ts
File metadata and controls
311 lines (273 loc) · 9.31 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import { NextRequest, NextResponse } from "next/server"
import { upsertUser, setUserGithubTokens } from "@/lib/db/queries"
import { createSessionToken, getSessionCookieOptions } from "@/lib/auth"
import { encryptSecret } from "@/lib/security/encryption"
const OAUTH_STATE_COOKIE = "cla-github-oauth-state"
const OAUTH_STATE_TTL_SECONDS = 60 * 10
type OAuthStateCookie = {
nonce: string
returnTo: string
}
type ResolvedGitHubEmail = {
email: string
verified: boolean
source: "profile" | "primary_verified" | "verified" | "any" | "none"
}
/**
* GitHub OAuth Callback
*
* Flow:
* 1. User clicks "Sign in with GitHub" -> GET with no code -> redirect to GitHub authorize URL
* 2. GitHub redirects back here with a `code` query param
* 3. Exchange code for access token
* 4. Fetch user profile from GitHub API
* 5. Upsert user in Neon DB
* 6. Create JWT session cookie
* 7. Redirect to the original destination (or /dashboard)
*/
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const code = searchParams.get("code")
const state = searchParams.get("state")
if (!code) {
// Step 1: Redirect to GitHub authorize
const clientId = process.env.GITHUB_CLIENT_ID
if (!clientId) {
return NextResponse.json({ error: "GITHUB_CLIENT_ID is not configured" }, { status: 500 })
}
const redirectUri = `${new URL(request.url).origin}/api/auth/github`
const returnTo = sanitizeReturnTo(searchParams.get("returnTo"), "/dashboard")
const nonce = crypto.randomUUID()
const githubAuthUrl = new URL("https://github.com/login/oauth/authorize")
githubAuthUrl.searchParams.set("client_id", clientId)
githubAuthUrl.searchParams.set("redirect_uri", redirectUri)
githubAuthUrl.searchParams.set("scope", "read:user,read:org,user:email")
githubAuthUrl.searchParams.set("state", nonce)
const response = NextResponse.redirect(githubAuthUrl.toString())
response.cookies.set(OAUTH_STATE_COOKIE, encodeOAuthStateCookie({ nonce, returnTo }), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: OAUTH_STATE_TTL_SECONDS,
})
return response
}
const makeAuthErrorRedirect = (reason: string) => {
const response = NextResponse.redirect(new URL(`/auth/signin?error=${reason}`, request.url))
clearOAuthStateCookie(response)
return response
}
const oauthState = parseOAuthStateCookie(request.cookies.get(OAUTH_STATE_COOKIE)?.value ?? null)
if (!state || !oauthState || oauthState.nonce !== state) {
return makeAuthErrorRedirect("github_state")
}
const returnTo = sanitizeReturnTo(oauthState.returnTo, "/dashboard")
// Step 2: Exchange code for access token
const clientId = process.env.GITHUB_CLIENT_ID
const clientSecret = process.env.GITHUB_CLIENT_SECRET
if (!clientId || !clientSecret) {
return NextResponse.json({ error: "GitHub OAuth credentials not configured" }, { status: 500 })
}
const tokenRes = await fetch("https://github.com/login/oauth/access_token", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code,
}),
})
const tokenData = await tokenRes.json()
if (tokenData.error) {
console.error("GitHub OAuth token error:", tokenData)
return makeAuthErrorRedirect("github_token")
}
const accessToken: string | undefined = tokenData.access_token
const refreshToken: string | undefined = tokenData.refresh_token
const expiresIn: number | undefined =
typeof tokenData.expires_in === "number" ? tokenData.expires_in : undefined
const refreshTokenExpiresIn: number | undefined =
typeof tokenData.refresh_token_expires_in === "number"
? tokenData.refresh_token_expires_in
: undefined
if (!accessToken) {
console.error("GitHub OAuth token error: missing access token", tokenData)
return makeAuthErrorRedirect("github_token")
}
if (!refreshToken || !expiresIn || !refreshTokenExpiresIn) {
console.error(
"GitHub OAuth token error: response missing refresh_token / expires_in fields. " +
"Confirm that 'Expire user authorization tokens' is enabled on the GitHub App.",
{
hasRefreshToken: Boolean(refreshToken),
hasExpiresIn: Boolean(expiresIn),
hasRefreshTokenExpiresIn: Boolean(refreshTokenExpiresIn),
}
)
return makeAuthErrorRedirect("github_token")
}
// Step 3: Fetch user profile from GitHub API
const userRes = await fetch("https://api.github.com/user", {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/vnd.github+json",
},
})
if (!userRes.ok) {
console.error("GitHub user fetch error:", userRes.status)
return makeAuthErrorRedirect("github_user")
}
const githubUser = await userRes.json()
const githubEmail = await resolveGitHubEmail(accessToken, githubUser.email)
// Step 4: Upsert user in DB
const user = await upsertUser({
githubId: githubUser.id,
githubUsername: githubUser.login,
avatarUrl: githubUser.avatar_url,
name: githubUser.name || githubUser.login,
email: githubEmail.email,
emailVerified: githubEmail.verified,
emailSource: githubEmail.source,
})
const encryptedAccessToken = encryptSecret(accessToken)
const encryptedRefreshToken = encryptSecret(refreshToken)
if (!encryptedAccessToken || !encryptedRefreshToken) {
console.error(
"Failed to encrypt GitHub OAuth tokens: ENCRYPTION_KEY or SESSION_SECRET is missing"
)
return makeAuthErrorRedirect("server_config")
}
const now = Date.now()
await setUserGithubTokens(user.id, {
accessTokenEncrypted: encryptedAccessToken,
accessTokenExpiresAt: new Date(now + expiresIn * 1000).toISOString(),
refreshTokenEncrypted: encryptedRefreshToken,
refreshTokenExpiresAt: new Date(now + refreshTokenExpiresIn * 1000).toISOString(),
tokenScopes: tokenData.scope ?? "",
})
// Step 5: Determine role — check if user is admin of any org
// For now, use the role from the DB (set during org creation or default "contributor")
const role = user.role as "admin" | "contributor"
// Step 6: Create JWT session and set cookie
const token = await createSessionToken({
userId: user.id,
githubUsername: user.githubUsername,
role,
jti: crypto.randomUUID(),
})
const response = NextResponse.redirect(new URL(returnTo, request.url))
clearOAuthStateCookie(response)
const cookieOpts = getSessionCookieOptions()
response.cookies.set(cookieOpts.name, token, {
httpOnly: cookieOpts.httpOnly,
secure: cookieOpts.secure,
sameSite: cookieOpts.sameSite,
path: cookieOpts.path,
maxAge: cookieOpts.maxAge,
})
return response
}
function sanitizeReturnTo(raw: string | null, fallback: string): string {
if (!raw) return fallback
if (!raw.startsWith("/") || raw.startsWith("//")) return fallback
return raw
}
function encodeOAuthStateCookie(value: OAuthStateCookie): string {
return `${value.nonce}:${encodeURIComponent(value.returnTo)}`
}
function parseOAuthStateCookie(raw: string | null): OAuthStateCookie | null {
if (!raw) return null
const separatorIndex = raw.indexOf(":")
if (separatorIndex <= 0) return null
const nonce = raw.slice(0, separatorIndex)
const encodedReturnTo = raw.slice(separatorIndex + 1)
if (!nonce || !encodedReturnTo) return null
try {
return {
nonce,
returnTo: decodeURIComponent(encodedReturnTo),
}
} catch {
return null
}
}
function clearOAuthStateCookie(response: NextResponse) {
response.cookies.set(OAUTH_STATE_COOKIE, "", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: 0,
})
}
async function resolveGitHubEmail(
accessToken: string,
profileEmail: unknown
): Promise<ResolvedGitHubEmail> {
if (typeof profileEmail === "string" && profileEmail.trim()) {
return {
email: profileEmail.trim(),
verified: false,
source: "profile",
}
}
try {
const emailsRes = await fetch("https://api.github.com/user/emails", {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/vnd.github+json",
},
})
if (!emailsRes.ok) {
return {
email: "",
verified: false,
source: "none",
}
}
const emails = (await emailsRes.json()) as Array<{
email?: string
primary?: boolean
verified?: boolean
}>
const primaryVerified = emails.find((entry) => entry.primary && entry.verified && entry.email)
if (primaryVerified?.email) {
return {
email: primaryVerified.email,
verified: true,
source: "primary_verified",
}
}
const verified = emails.find((entry) => entry.verified && entry.email)
if (verified?.email) {
return {
email: verified.email,
verified: true,
source: "verified",
}
}
const any = emails.find((entry) => entry.email)
if (any?.email) {
return {
email: any.email,
verified: Boolean(any.verified),
source: "any",
}
}
return {
email: "",
verified: false,
source: "none",
}
} catch {
return {
email: "",
verified: false,
source: "none",
}
}
}