-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathroute.ts
More file actions
362 lines (333 loc) · 11.4 KB
/
Copy pathroute.ts
File metadata and controls
362 lines (333 loc) · 11.4 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import { NextRequest, NextResponse } from "next/server";
import {
setOrgIdForJwt,
setOrgIdForRefreshToken,
deleteOrgIdForRefreshToken,
} from "@/lib/redis";
import { resolveOrgId } from "@/lib/org-utils";
import { REFRESH_TOKEN_ORG_TTL_SECONDS } from "@/lib/const";
import { normalizeLocalhostUri } from "@/lib/auth-utils";
export async function OPTIONS(): Promise<NextResponse> {
return new NextResponse(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
});
}
function createErrorResponse(
error: string,
errorDescription: string,
status: number = 400,
) {
return NextResponse.json(
{
error,
error_description: errorDescription,
},
{
status,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
},
);
}
interface ClerkTokenResponse {
access_token: string;
expires_in: number;
refresh_token: string;
token_type: string;
id_token?: string; // Optional, only present for authorization_code grants
}
export async function POST(request: NextRequest): Promise<NextResponse> {
// Step 1: Validate request format
const contentType = request.headers.get("content-type");
if (!contentType?.includes("application/x-www-form-urlencoded")) {
console.debug("[token] invalid content-type", { contentType });
return createErrorResponse(
"invalid_request",
"Content-Type must be application/x-www-form-urlencoded",
);
}
const body = await request.formData();
// Step 2: Validate server configuration
const clerkDomain = process.env.NEXT_PUBLIC_CLERK_DOMAIN;
if (!clerkDomain) {
console.error("NEXT_PUBLIC_CLERK_DOMAIN environment variable is not set");
return createErrorResponse(
"server_error",
"Server configuration error - clerk domain not found",
500,
);
}
try {
// Step 3: Prepare parameters for Clerk token exchange
// Normalize redirect_uri to match Vercel's query param normalization (127.0.0.1 → localhost)
const params = new URLSearchParams();
for (const [key, value] of body.entries()) {
if (key === "redirect_uri") {
params.append(key, normalizeLocalhostUri(value.toString()));
} else {
params.append(key, value.toString());
}
}
const grantType = body.get("grant_type") as string;
console.debug("[token] start", { grantType });
// Extract client_id from body or Authorization: Basic header
let clientId = body.get("client_id") as string | null;
let clientSecret = body.get("client_secret") as string | null;
if (!clientId) {
const authHeader = request.headers.get("authorization");
if (authHeader?.startsWith("Basic ")) {
try {
const decoded = atob(authHeader.slice(6));
const colonIdx = decoded.indexOf(":");
if (colonIdx !== -1) {
clientId = decodeURIComponent(decoded.slice(0, colonIdx));
clientSecret = decodeURIComponent(decoded.slice(colonIdx + 1));
params.set("client_id", clientId);
if (clientSecret) {
params.set("client_secret", clientSecret);
}
console.debug("[token] extracted client_id from Basic auth header");
}
} catch {
console.debug("[token] failed to decode Basic auth header");
}
}
}
if (!clientId) {
console.debug("[token] missing client_id");
return createErrorResponse(
"invalid_request",
"Missing required parameter: client_id",
);
}
// Extract direct org_id if provided (shared clients)
let directOrgId: string | undefined;
const directOrgIdParam = body.get("org_id");
if (directOrgIdParam) {
const orgIdParam = directOrgIdParam.toString();
directOrgId = orgIdParam;
const maskedOrgId = orgIdParam.slice(0, 4) + "..." + orgIdParam.slice(-4);
console.debug("[token] using org_id from request body", { maskedOrgId });
}
// For refresh_token flow, resolve org before calling Clerk
let resolvedOrgId: string | null = null;
let refreshTokenFromBody: string | null = null;
if (grantType === "refresh_token") {
refreshTokenFromBody = body.get("refresh_token") as string | null;
if (!refreshTokenFromBody) {
console.debug("[token] missing refresh_token in refresh flow");
return createErrorResponse(
"invalid_request",
"Missing required parameter: refresh_token",
);
}
const orgResultPre = await resolveOrgId({
grantType,
clientId,
directOrgId,
refreshToken: refreshTokenFromBody,
});
if (orgResultPre.error) {
console.debug(
"[token] resolveOrgId (pre) returned error for refresh flow",
);
return orgResultPre.error;
}
resolvedOrgId = orgResultPre.orgId;
if (!resolvedOrgId) {
console.debug("[token] no org_id resolved for refresh_token flow");
return createErrorResponse(
"invalid_grant",
"Organization context not found for refresh token. Please re-authorize.",
);
}
console.debug("[token] resolved org via refresh_token mapping");
}
// Step 4: Exchange with Clerk
const clerkTokenResponse = await fetch(
`https://${clerkDomain}/oauth/token`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: params,
},
);
if (!clerkTokenResponse.ok) {
console.error("[token] clerk token exchange failed");
return createErrorResponse(
"invalid_grant",
grantType === "refresh_token"
? "Failed to refresh token"
: "Failed to exchange authorization code",
);
}
const clerkTokens: ClerkTokenResponse = await clerkTokenResponse.json();
// Step 5: Resolve organization context for authorization_code flows (or confirm for refresh flows)
let orgId = resolvedOrgId;
if (!orgId) {
const orgResult = await resolveOrgId({
grantType,
clientId,
directOrgId,
});
if (orgResult.error) {
console.debug("[token] resolveOrgId returned error for auth_code flow");
return orgResult.error;
}
orgId = orgResult.orgId;
}
// Step 6: Validate organization context
if (!orgId || orgId === "") {
console.warn("[token] no org_id resolved for client", {
clientIdMasked: clientId.slice(0, 4) + "...",
});
return createErrorResponse(
"invalid_grant",
"Unable to resolve organization context. Please re-authorize.",
);
}
// Step 7: Validate grant type and extract JWT
let finalJwt: string;
let expiresIn: number;
if (grantType === "authorization_code") {
// For authorization_code: Use id_token directly (already has proper structure)
if (!clerkTokens.id_token) {
console.debug("[token] missing id_token in auth_code response");
return createErrorResponse(
"invalid_grant",
"Failed to retrieve id_token from Clerk authorization code",
);
}
finalJwt = clerkTokens.id_token;
expiresIn = clerkTokens.expires_in;
} else if (grantType === "refresh_token") {
if (!clerkTokens.id_token) {
console.debug("[token] missing id_token in refresh response");
return createErrorResponse(
"invalid_grant",
"Failed to retrieve id_token from Clerk refresh token",
);
}
finalJwt = clerkTokens.id_token;
expiresIn = clerkTokens.expires_in;
} else {
return createErrorResponse(
"unsupported_grant_type",
`Grant type '${grantType}' is not supported`,
);
}
// Step 8: Store refresh_token → org_id mapping (where applicable)
try {
if (grantType === "authorization_code" && clerkTokens.refresh_token) {
await setOrgIdForRefreshToken({
refreshToken: clerkTokens.refresh_token,
orgId,
ttlSeconds: REFRESH_TOKEN_ORG_TTL_SECONDS,
});
console.debug(
"[token] stored refresh_token→org_id mapping (auth_code)",
);
}
if (grantType === "refresh_token") {
// Update mapping for rotated refresh token if provided
if (clerkTokens.refresh_token) {
// Clean up old mapping before storing the new one
if (refreshTokenFromBody) {
try {
await deleteOrgIdForRefreshToken({
refreshToken: refreshTokenFromBody,
});
console.debug(
"[token] deleted old refresh_token→org_id mapping (refresh)",
);
} catch (e) {
console.warn(
"[token] failed to delete old refresh_token mapping",
{ error: e },
);
}
}
await setOrgIdForRefreshToken({
refreshToken: clerkTokens.refresh_token,
orgId,
ttlSeconds: REFRESH_TOKEN_ORG_TTL_SECONDS,
});
console.debug(
"[token] updated refresh_token→org_id mapping (refresh)",
);
}
}
} catch (error) {
console.error("[token] failed to store refresh_token→org_id mapping", {
error,
});
return createErrorResponse(
"server_error",
"Failed to store refresh token context",
500,
);
}
// Step 9: Store JWT to org_id mapping for verifyjwt.go
try {
// Store JWT to org_id mapping with JWT expiration time
await setOrgIdForJwt({
jwt: finalJwt,
orgId,
ttlSeconds: expiresIn,
});
console.debug("[token] stored jwt→org_id mapping", {
ttlSeconds: expiresIn,
});
} catch (error) {
console.error("[token] failed to store jwt→org_id mapping", { error });
return createErrorResponse(
"server_error",
"Failed to store authentication context",
500,
);
}
// Step 10: Build final token response
const mcpTokenResponse = {
...clerkTokens,
access_token: finalJwt,
expires_in: expiresIn,
};
console.debug("[token] success", { grantType });
return NextResponse.json(mcpTokenResponse, {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
});
} catch (error) {
console.error("[token] unhandled error", { error });
// If it's a Clerk error, log the detailed error information
if (error && typeof error === "object" && "clerkError" in error) {
const clerkError = error as any;
console.error("Clerk error details:");
console.error(" Status:", clerkError.status);
console.error(" Clerk Trace ID:", clerkError.clerkTraceId);
if (clerkError.errors && Array.isArray(clerkError.errors)) {
console.error(" Specific errors:");
clerkError.errors.forEach((err: any, index: number) => {
console.error(
` Error ${index + 1}:`,
JSON.stringify(err, null, 2),
);
});
}
}
return createErrorResponse("server_error", "Internal server error", 500);
}
}