-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathclerkMiddleware.ts
More file actions
590 lines (506 loc) · 21.2 KB
/
clerkMiddleware.ts
File metadata and controls
590 lines (506 loc) · 21.2 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
import type { AuthObject, ClerkClient } from '@clerk/backend';
import type {
AuthenticatedState,
AuthenticateRequestOptions,
ClerkRequest,
RedirectFun,
RequestState,
SignedInAuthObject,
SignedOutAuthObject,
UnauthenticatedState,
} from '@clerk/backend/internal';
import {
AuthStatus,
constants,
createClerkRequest,
createRedirect,
getAuthObjectForAcceptedToken,
isMachineTokenByPrefix,
isTokenTypeAccepted,
makeAuthObjectSerializable,
TokenType,
} from '@clerk/backend/internal';
import { clerkFrontendApiProxy, DEFAULT_PROXY_PATH, matchProxyPath } from '@clerk/backend/proxy';
import { parsePublishableKey } from '@clerk/shared/keys';
import { handleNetlifyCacheInDevInstance } from '@clerk/shared/netlifyCacheHandler';
import { isVercelPreviewDeploy } from '@clerk/shared/proxy';
import { notFound as nextjsNotFound } from 'next/navigation';
import type { NextMiddleware, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import type { AuthFn } from '../app-router/server/auth';
import type { GetAuthOptions } from '../server/createGetAuth';
import { isRedirect, serverRedirectWithAuth, setHeader } from '../utils';
import { withLogger } from '../utils/debugLogger';
import { canUseKeyless } from '../utils/feature-flags';
import { clerkClient } from './clerkClient';
import { DOMAIN, PROXY_URL, PUBLISHABLE_KEY, SECRET_KEY, SIGN_IN_URL, SIGN_UP_URL } from './constants';
import { type ContentSecurityPolicyOptions, createContentSecurityPolicyHeaders } from './content-security-policy';
import { errorThrower } from './errorThrower';
import { getHeader } from './headers-utils';
import { getKeylessCookieValue } from './keyless';
import { clerkMiddlewareRequestDataStorage, clerkMiddlewareRequestDataStore } from './middleware-storage';
import {
isNextjsNotFoundError,
isNextjsRedirectError,
isNextjsUnauthorizedError,
isRedirectToSignInError,
isRedirectToSignUpError,
nextjsRedirectError,
redirectToSignInError,
redirectToSignUpError,
unauthorized,
} from './nextErrors';
import type { AuthProtect } from './protect';
import { createProtect } from './protect';
import type {
FrontendApiProxyOptions,
NextMiddlewareEvtParam,
NextMiddlewareRequestParam,
NextMiddlewareReturn,
} from './types';
import {
assertKey,
decorateRequest,
handleMultiDomainAndProxy,
redirectAdapter,
setRequestHeadersOnNextResponse,
} from './utils';
export type ClerkMiddlewareSessionAuthObject = (SignedInAuthObject | SignedOutAuthObject) & {
redirectToSignIn: RedirectFun<Response>;
redirectToSignUp: RedirectFun<Response>;
};
export type ClerkMiddlewareAuth = AuthFn;
type ClerkMiddlewareHandler = (
auth: ClerkMiddlewareAuth,
request: NextMiddlewareRequestParam,
event: NextMiddlewareEvtParam,
) => NextMiddlewareReturn;
type AuthenticateAnyRequestOptions = Omit<AuthenticateRequestOptions, 'acceptsToken'>;
/**
* The `clerkMiddleware()` function accepts an optional object. The following options are available.
* @interface
*/
export interface ClerkMiddlewareOptions extends AuthenticateAnyRequestOptions {
/**
* If true, additional debug information will be logged to the console.
*/
debug?: boolean;
/**
* When set, automatically injects a Content-Security-Policy header(s) compatible with Clerk.
*/
contentSecurityPolicy?: ContentSecurityPolicyOptions;
/**
* When set, enables the middleware to proxy Frontend API requests to Clerk.
* This is useful when direct communication with Clerk's API is blocked.
*/
frontendApiProxy?: FrontendApiProxyOptions;
}
type ClerkMiddlewareOptionsCallback = (req: NextRequest) => ClerkMiddlewareOptions | Promise<ClerkMiddlewareOptions>;
/**
* Middleware for Next.js that handles authentication and authorization with Clerk.
* For more details, please refer to the docs: https://clerk.com/docs/reference/nextjs/clerk-middleware
*/
interface ClerkMiddleware {
/**
* @example
* export default clerkMiddleware((auth, request, event) => { ... }, options);
*/
(handler: ClerkMiddlewareHandler, options?: ClerkMiddlewareOptions): NextMiddleware;
/**
* @example
* export default clerkMiddleware((auth, request, event) => { ... }, (req) => options);
*/
(handler: ClerkMiddlewareHandler, options?: ClerkMiddlewareOptionsCallback): NextMiddleware;
/**
* @example
* export default clerkMiddleware(options);
*/
(options?: ClerkMiddlewareOptions): NextMiddleware;
/**
* @example
* export default clerkMiddleware;
*/
(request: NextMiddlewareRequestParam, event: NextMiddlewareEvtParam): NextMiddlewareReturn;
}
/**
* The `clerkMiddleware()` helper integrates Clerk authentication into your Next.js application through Middleware. `clerkMiddleware()` is compatible with both the App and Pages routers.
*/
export const clerkMiddleware = ((...args: unknown[]): NextMiddleware | NextMiddlewareReturn => {
const [request, event] = parseRequestAndEvent(args);
const [handler, params] = parseHandlerAndOptions(args);
const middleware = clerkMiddlewareRequestDataStorage.run(clerkMiddlewareRequestDataStore, () => {
const baseNextMiddleware: NextMiddleware = withLogger('clerkMiddleware', logger => async (request, event) => {
// Handles the case where `options` is a callback function to dynamically access `NextRequest`
const resolvedParams = typeof params === 'function' ? await params(request) : params;
const keyless = await getKeylessCookieValue(name => request.cookies.get(name)?.value);
const publishableKey = assertKey(
resolvedParams.publishableKey || PUBLISHABLE_KEY || keyless?.publishableKey,
() => errorThrower.throwMissingPublishableKeyError(),
);
const secretKey = assertKey(resolvedParams.secretKey || SECRET_KEY || keyless?.secretKey, () =>
errorThrower.throwMissingSecretKeyError(),
);
// Handle Frontend API proxy requests early, before authentication
const requestUrl = new URL(request.url);
const frontendApiProxyConfig =
resolvedParams.frontendApiProxy ??
(resolvedParams.proxyUrl || PROXY_URL || resolvedParams.domain || DOMAIN
? undefined
: getAutoDetectedProxyConfig(requestUrl));
if (frontendApiProxyConfig) {
const { enabled, path: proxyPath = DEFAULT_PROXY_PATH } = frontendApiProxyConfig;
// Resolve enabled - either boolean or function
const isEnabled = typeof enabled === 'function' ? enabled(requestUrl) : enabled;
if (isEnabled && matchProxyPath(request, { proxyPath })) {
return clerkFrontendApiProxy(request, {
proxyPath,
publishableKey,
secretKey,
});
}
}
const signInUrl = resolvedParams.signInUrl || SIGN_IN_URL;
const signUpUrl = resolvedParams.signUpUrl || SIGN_UP_URL;
const options = {
publishableKey,
secretKey,
signInUrl,
signUpUrl,
...resolvedParams,
};
// Propagates the request data to be accessed on the server application runtime from helpers such as `clerkClient`
clerkMiddlewareRequestDataStore.set('requestData', options);
const resolvedClerkClient = await clerkClient();
if (options.debug) {
logger.enable();
}
const clerkRequest = createClerkRequest(request);
logger.debug('options', options);
logger.debug('url', () => clerkRequest.toJSON());
const authHeader = request.headers.get(constants.Headers.Authorization);
if (authHeader && authHeader.startsWith('Basic ')) {
logger.debug('Basic Auth detected');
}
const cspHeader = request.headers.get(constants.Headers.ContentSecurityPolicy);
if (cspHeader) {
logger.debug('Content-Security-Policy detected', () => ({
value: cspHeader,
}));
}
const requestState = await resolvedClerkClient.authenticateRequest(
clerkRequest,
createAuthenticateRequestOptions(clerkRequest, options),
);
logger.debug('requestState', () => ({
status: requestState.status,
headers: JSON.stringify(Object.fromEntries(requestState.headers)),
reason: requestState.reason,
}));
const locationHeader = requestState.headers.get(constants.Headers.Location);
if (locationHeader) {
handleNetlifyCacheInDevInstance({
locationHeader,
requestStateHeaders: requestState.headers,
publishableKey: requestState.publishableKey,
});
const res = NextResponse.redirect(requestState.headers.get(constants.Headers.Location) || locationHeader);
requestState.headers.forEach((value, key) => {
if (key === constants.Headers.Location) {
return;
}
res.headers.append(key, value);
});
return res;
} else if (requestState.status === AuthStatus.Handshake) {
throw new Error('Clerk: handshake status without redirect');
}
const authObject = requestState.toAuth();
logger.debug('auth', () => ({ auth: authObject, debug: authObject.debug() }));
const redirectToSignIn = createMiddlewareRedirectToSignIn(clerkRequest);
const redirectToSignUp = createMiddlewareRedirectToSignUp(clerkRequest);
const protect = await createMiddlewareProtect(clerkRequest, authObject, redirectToSignIn);
const authHandler = createMiddlewareAuthHandler(requestState, redirectToSignIn, redirectToSignUp);
authHandler.protect = protect;
let handlerResult: Response = NextResponse.next();
try {
const userHandlerResult = await clerkMiddlewareRequestDataStorage.run(
clerkMiddlewareRequestDataStore,
async () => handler?.(authHandler, request, event),
);
handlerResult = userHandlerResult || handlerResult;
} catch (e: any) {
handlerResult = handleControlFlowErrors(e, clerkRequest, request, requestState);
}
if (options.contentSecurityPolicy) {
const { headers } = createContentSecurityPolicyHeaders(
(parsePublishableKey(publishableKey)?.frontendApi ?? '').replace('$', ''),
options.contentSecurityPolicy,
);
const cspRequestHeaders: Record<string, string> = {};
headers.forEach(([key, value]) => {
setHeader(handlerResult, key, value);
cspRequestHeaders[key] = value;
});
// Forward CSP headers as request headers so server components
// can access the nonce via headers()
setRequestHeadersOnNextResponse(handlerResult, clerkRequest, cspRequestHeaders);
logger.debug('Clerk generated CSP', () => ({
headers,
}));
}
// TODO @nikos: we need to make this more generic
// and move the logic in clerk/backend
if (requestState.headers) {
requestState.headers.forEach((value, key) => {
if (key === constants.Headers.ContentSecurityPolicy) {
logger.debug('Content-Security-Policy detected', () => ({
value,
}));
}
handlerResult.headers.append(key, value);
});
}
if (isRedirect(handlerResult)) {
logger.debug('handlerResult is redirect');
return serverRedirectWithAuth(clerkRequest, handlerResult, options);
}
if (options.debug) {
setRequestHeadersOnNextResponse(handlerResult, clerkRequest, { [constants.Headers.EnableDebug]: 'true' });
}
const keylessKeysForRequestData =
// Only pass keyless credentials when there are no explicit keys
secretKey === keyless?.secretKey
? {
publishableKey: keyless?.publishableKey,
secretKey: keyless?.secretKey,
}
: {};
decorateRequest(
clerkRequest,
handlerResult,
requestState,
resolvedParams,
keylessKeysForRequestData,
authObject.tokenType === 'session_token' ? null : makeAuthObjectSerializable(authObject),
);
return handlerResult;
});
const keylessMiddleware: NextMiddleware = async (request, event) => {
/**
* This mechanism replaces a full-page reload. Ensures that middleware will re-run and authenticate the request properly without the secret key or publishable key to be missing.
*/
if (isKeylessSyncRequest(request)) {
return returnBackFromKeylessSync(request);
}
const resolvedParams = typeof params === 'function' ? await params(request) : params;
const keyless = await getKeylessCookieValue(name => request.cookies.get(name)?.value);
const isMissingPublishableKey = !(resolvedParams.publishableKey || PUBLISHABLE_KEY || keyless?.publishableKey);
const authHeader = getHeader(request, constants.Headers.Authorization)?.replace('Bearer ', '') ?? '';
/**
* In keyless mode, if the publishable key is missing, let the request through, to render `<ClerkProvider/>` that will resume the flow gracefully.
*/
if (isMissingPublishableKey && !isMachineTokenByPrefix(authHeader)) {
const res = NextResponse.next();
setRequestHeadersOnNextResponse(res, request, {
[constants.Headers.AuthStatus]: 'signed-out',
});
return res;
}
return baseNextMiddleware(request, event);
};
const nextMiddleware: NextMiddleware = async (request, event) => {
if (canUseKeyless) {
return keylessMiddleware(request, event);
}
return baseNextMiddleware(request, event);
};
// If we have a request and event, we're being called as a middleware directly
// eg, export default clerkMiddleware;
if (request && event) {
return nextMiddleware(request, event);
}
// Otherwise, return a middleware that can be called with a request and event
// eg, export default clerkMiddleware(auth => { ... });
return nextMiddleware;
});
return middleware;
}) as ClerkMiddleware;
const parseRequestAndEvent = (args: unknown[]) => {
return [args[0] instanceof Request ? args[0] : undefined, args[0] instanceof Request ? args[1] : undefined] as [
NextMiddlewareRequestParam | undefined,
NextMiddlewareEvtParam | undefined,
];
};
const parseHandlerAndOptions = (args: unknown[]) => {
return [
typeof args[0] === 'function' ? args[0] : undefined,
(args.length === 2 ? args[1] : typeof args[0] === 'function' ? {} : args[0]) || {},
] as [ClerkMiddlewareHandler | undefined, ClerkMiddlewareOptions | ClerkMiddlewareOptionsCallback];
};
const isKeylessSyncRequest = (request: NextMiddlewareRequestParam) =>
request.nextUrl.pathname === '/clerk-sync-keyless';
const returnBackFromKeylessSync = (request: NextMiddlewareRequestParam) => {
const returnUrl = request.nextUrl.searchParams.get('returnUrl');
const url = new URL(request.url);
url.pathname = '';
return NextResponse.redirect(returnUrl || url.toString());
};
type AuthenticateRequest = Pick<ClerkClient, 'authenticateRequest'>['authenticateRequest'];
export const createAuthenticateRequestOptions = (
clerkRequest: ClerkRequest,
options: ClerkMiddlewareOptions,
): Parameters<AuthenticateRequest>[1] => {
// Auto-derive proxyUrl from frontendApiProxy config if not explicitly set
let resolvedOptions = options;
if (options.frontendApiProxy && !options.proxyUrl) {
const { enabled, path: proxyPath = DEFAULT_PROXY_PATH } = options.frontendApiProxy;
const requestUrl = new URL(clerkRequest.url);
const isEnabled = typeof enabled === 'function' ? enabled(requestUrl) : enabled;
if (isEnabled) {
const derivedProxyUrl = `${requestUrl.origin}${proxyPath}`;
resolvedOptions = { ...options, proxyUrl: derivedProxyUrl };
}
}
return {
...resolvedOptions,
...handleMultiDomainAndProxy(clerkRequest, resolvedOptions),
// TODO: Leaving the acceptsToken as 'any' opens up the possibility of
// an economic attack. We should revisit this and only verify a token
// when auth() or auth.protect() is invoked.
acceptsToken: 'any',
};
};
const createMiddlewareRedirectToSignIn = (
clerkRequest: ClerkRequest,
): ClerkMiddlewareSessionAuthObject['redirectToSignIn'] => {
return (opts = {}) => {
const url = clerkRequest.clerkUrl.toString();
redirectToSignInError(url, opts.returnBackUrl);
};
};
const createMiddlewareRedirectToSignUp = (
clerkRequest: ClerkRequest,
): ClerkMiddlewareSessionAuthObject['redirectToSignUp'] => {
return (opts = {}) => {
const url = clerkRequest.clerkUrl.toString();
redirectToSignUpError(url, opts.returnBackUrl);
};
};
const createMiddlewareProtect = (
clerkRequest: ClerkRequest,
rawAuthObject: AuthObject,
redirectToSignIn: RedirectFun<Response>,
) => {
return (async (params: any, options: any) => {
const notFound = () => nextjsNotFound();
const redirect = (url: string) =>
nextjsRedirectError(url, {
redirectUrl: url,
});
const requestedToken = params?.token || options?.token || TokenType.SessionToken;
const authObject = getAuthObjectForAcceptedToken({ authObject: rawAuthObject, acceptsToken: requestedToken });
return createProtect({
request: clerkRequest,
redirect,
notFound,
unauthorized,
authObject,
redirectToSignIn,
})(params, options);
}) as unknown as Promise<AuthProtect>;
};
/**
* Modifies the auth object based on the token type.
* - For session tokens: adds redirect functions to the auth object
* - For machine tokens: validates token type and returns appropriate auth object
*/
const createMiddlewareAuthHandler = (
requestState: AuthenticatedState<'session_token'> | UnauthenticatedState<'session_token'>,
redirectToSignIn: RedirectFun<Response>,
redirectToSignUp: RedirectFun<Response>,
): ClerkMiddlewareAuth => {
const authHandler = async (options?: GetAuthOptions) => {
const rawAuthObject = requestState.toAuth({ treatPendingAsSignedOut: options?.treatPendingAsSignedOut });
const acceptsToken = options?.acceptsToken ?? TokenType.SessionToken;
const authObject = getAuthObjectForAcceptedToken({
authObject: rawAuthObject,
acceptsToken,
});
if (authObject.tokenType === TokenType.SessionToken && isTokenTypeAccepted(TokenType.SessionToken, acceptsToken)) {
return Object.assign(authObject, {
redirectToSignIn,
redirectToSignUp,
});
}
return authObject;
};
return authHandler as ClerkMiddlewareAuth;
};
// Handle errors thrown by protect() and redirectToSignIn() calls,
// as we want to align the APIs between middleware, pages and route handlers
// Normally, middleware requires to explicitly return a response, but we want to
// avoid discrepancies between the APIs as it's easy to miss the `return` statement
// especially when copy-pasting code from one place to another.
// This function handles the known errors thrown by the APIs described above,
// and returns the appropriate response.
const handleControlFlowErrors = (
e: any,
clerkRequest: ClerkRequest,
nextRequest: NextRequest,
requestState: RequestState,
): Response => {
if (isNextjsUnauthorizedError(e)) {
const response = new NextResponse(null, { status: 401 });
// RequestState.toAuth() returns a session_token type by default.
// We need to cast it to the correct type to check for OAuth tokens.
const authObject = (requestState as RequestState<TokenType>).toAuth();
if (authObject && authObject.tokenType === TokenType.OAuthToken) {
// Following MCP spec, we return WWW-Authenticate header on 401 responses
// to enable OAuth 2.0 authorization server discovery (RFC9728).
// See https://modelcontextprotocol.io/specification/draft/basic/authorization#2-3-1-authorization-server-location
const publishableKey = parsePublishableKey(requestState.publishableKey);
return setHeader(
response,
'WWW-Authenticate',
`Bearer resource_metadata="https://${publishableKey?.frontendApi}/.well-known/oauth-protected-resource"`,
);
}
return response;
}
if (isNextjsNotFoundError(e)) {
// Rewrite to a bogus URL to force not found error
return setHeader(
// This is an internal rewrite purely to trigger a not found error. We do not want Next.js to think that the
// destination URL is a valid page, so we use `nextRequest.url` as the base for the fake URL, which Next.js
// understands is an internal URL and won't run middleware against the request.
NextResponse.rewrite(new URL(`/clerk_${Date.now()}`, nextRequest.url)),
constants.Headers.AuthReason,
'protect-rewrite',
);
}
const isRedirectToSignIn = isRedirectToSignInError(e);
const isRedirectToSignUp = isRedirectToSignUpError(e);
if (isRedirectToSignIn || isRedirectToSignUp) {
const redirect = createRedirect({
redirectAdapter,
baseUrl: clerkRequest.clerkUrl,
signInUrl: requestState.signInUrl,
signUpUrl: requestState.signUpUrl,
publishableKey: requestState.publishableKey,
sessionStatus: requestState.toAuth()?.sessionStatus,
isSatellite: requestState.isSatellite,
});
const { returnBackUrl } = e;
return redirect[isRedirectToSignIn ? 'redirectToSignIn' : 'redirectToSignUp']({ returnBackUrl });
}
if (isNextjsRedirectError(e)) {
return redirectAdapter(e.redirectUrl);
}
throw e;
};
function getAutoDetectedProxyConfig(requestUrl: URL): FrontendApiProxyOptions | undefined {
if (isVercelPreviewDeploy(requestUrl.hostname)) {
return { enabled: true };
}
return undefined;
}