-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
201 lines (175 loc) · 6.05 KB
/
route.ts
File metadata and controls
201 lines (175 loc) · 6.05 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
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
import {
createSession,
findOrCreateOAuthUser,
getCurrentUserProfile,
linkOAuthAccount,
resolvePlatformUrl,
sanitizeRedirectPath,
SESSION_COOKIE_NAME,
SESSION_COOKIE_OPTIONS,
} from "@/lib/auth";
import { oauthFetch } from "@/lib/oauth-fetch";
import { timingSafeStateEqual } from "@/lib/timing-safe";
const STATE_COOKIE = "diffaudit_oauth_state";
type GitHubTokenResponse = { access_token?: string; error?: string };
type GitHubUserResponse = {
id: number;
login: string;
name?: string | null;
avatar_url: string | null;
email: string | null;
};
function readStoredState(raw: string | undefined) {
if (!raw) return null;
try {
return JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as {
state: string;
redirectTo?: string;
mode?: "login" | "connect";
userId?: string | null;
};
} catch {
return null;
}
}
function buildRedirectWithProviderStatus(
redirectTo: string | undefined,
providerLink: string,
platformUrl: string,
) {
const target = new URL(sanitizeRedirectPath(redirectTo, "/workspace/account"), platformUrl);
target.searchParams.set("providerLink", providerLink);
return target;
}
function buildPlatformRedirect(path: string, platformUrl: string) {
return new URL(path, platformUrl);
}
async function readGitHubTokenPayload(response: Response): Promise<GitHubTokenResponse | null> {
try {
return (await response.json()) as GitHubTokenResponse;
} catch {
return null;
}
}
export async function GET(request: Request) {
const url = new URL(request.url);
const code = url.searchParams.get("code");
const state = url.searchParams.get("state");
const clientId = process.env.GITHUB_CLIENT_ID;
const clientSecret = process.env.GITHUB_CLIENT_SECRET;
const platformUrl = resolvePlatformUrl(request);
if (!platformUrl) {
return NextResponse.json({ message: "Platform public URL is not configured." }, { status: 500 });
}
const cookieStore = await cookies();
const storedState = readStoredState(cookieStore.get(STATE_COOKIE)?.value);
cookieStore.delete(STATE_COOKIE);
if (!code || !state || !storedState || !timingSafeStateEqual(state, storedState.state)) {
return NextResponse.redirect(buildPlatformRedirect("/login?error=oauth_state", platformUrl));
}
if (!clientId || !clientSecret) {
return NextResponse.redirect(buildPlatformRedirect("/login?error=oauth_config", platformUrl));
}
let tokenRes: Response;
try {
tokenRes = await oauthFetch("https://github.com/login/oauth/access_token", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
client_id: clientId,
client_secret: clientSecret,
code,
redirect_uri: `${platformUrl}/api/auth/github/callback`,
state,
}),
});
} catch {
return NextResponse.redirect(buildPlatformRedirect("/login?error=oauth_network_github", platformUrl));
}
const tokenPayload = await readGitHubTokenPayload(tokenRes);
if (!tokenPayload?.access_token) {
return NextResponse.redirect(buildPlatformRedirect("/login?error=oauth_token", platformUrl));
}
let userRes: Response;
try {
userRes = await oauthFetch("https://api.github.com/user", {
headers: {
Authorization: `Bearer ${tokenPayload.access_token}`,
Accept: "application/vnd.github+json",
"User-Agent": "DiffAudit-Platform",
},
});
} catch {
return NextResponse.redirect(buildPlatformRedirect("/login?error=oauth_network_github", platformUrl));
}
if (!userRes.ok) {
return NextResponse.redirect(buildPlatformRedirect("/login?error=oauth_user", platformUrl));
}
const user = (await userRes.json()) as GitHubUserResponse;
let email = user.email;
let emailVerified = false;
if (!email) {
let emailRes: Response;
try {
emailRes = await oauthFetch("https://api.github.com/user/emails", {
headers: {
Authorization: `Bearer ${tokenPayload.access_token}`,
Accept: "application/vnd.github+json",
"User-Agent": "DiffAudit-Platform",
},
});
} catch {
return NextResponse.redirect(buildPlatformRedirect("/login?error=oauth_network_github", platformUrl));
}
if (emailRes.ok) {
const emails = (await emailRes.json()) as Array<{ email: string; primary: boolean; verified: boolean }>;
const preferred = emails.find((item) => item.primary) ?? emails[0];
email = preferred?.email ?? null;
emailVerified = Boolean(preferred?.verified);
}
}
const profile = {
username: user.login,
displayName: user.name ?? user.login,
email,
emailVerified,
avatarUrl: user.avatar_url,
};
if (storedState.mode === "connect" && storedState.userId) {
const sessionToken = cookieStore.get(SESSION_COOKIE_NAME)?.value;
const currentUser = getCurrentUserProfile(sessionToken);
if (!currentUser || currentUser.id !== storedState.userId) {
return NextResponse.redirect(
buildPlatformRedirect("/login?error=session_mismatch", platformUrl),
);
}
const result = linkOAuthAccount(storedState.userId, "github", String(user.id), profile);
if (!result.ok) {
return NextResponse.redirect(
buildRedirectWithProviderStatus(
storedState.redirectTo,
result.reason === "provider_in_use" ? "github_in_use" : "github_already_connected",
platformUrl,
),
);
}
return NextResponse.redirect(
buildRedirectWithProviderStatus(
storedState.redirectTo,
result.status === "already_linked" ? "github_already_connected" : "github_connected",
platformUrl,
),
);
}
const appUser = findOrCreateOAuthUser("github", String(user.id), profile);
const token = createSession(appUser.id);
cookieStore.set(SESSION_COOKIE_NAME, token, SESSION_COOKIE_OPTIONS);
return NextResponse.redirect(
buildPlatformRedirect(sanitizeRedirectPath(storedState.redirectTo), platformUrl),
);
}