-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy pathclerkMiddleware.ts
372 lines (315 loc) · 13.6 KB
/
clerkMiddleware.ts
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
import type { AuthObject, ClerkClient } from '@clerk/backend';
import type { AuthenticateRequestOptions, ClerkRequest, RedirectFun, RequestState } from '@clerk/backend/internal';
import { AuthStatus, constants, createClerkRequest, createRedirect } from '@clerk/backend/internal';
import { eventMethodCalled } from '@clerk/shared/telemetry';
import { notFound as nextjsNotFound } from 'next/navigation';
import type { NextMiddleware, NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
import { isRedirect, serverRedirectWithAuth, setHeader } from '../utils';
import { withLogger } from '../utils/debugLogger';
import { canUseKeyless } from '../utils/feature-flags';
import { clerkClient } from './clerkClient';
import { PUBLISHABLE_KEY, SECRET_KEY, SIGN_IN_URL, SIGN_UP_URL } from './constants';
import { errorThrower } from './errorThrower';
import { getKeylessCookieValue } from './keyless';
import { clerkMiddlewareRequestDataStorage, clerkMiddlewareRequestDataStore } from './middleware-storage';
import {
isNextjsNotFoundError,
isNextjsRedirectError,
isRedirectToSignInError,
nextjsRedirectError,
redirectToSignInError,
} from './nextErrors';
import type { AuthProtect } from './protect';
import { createProtect } from './protect';
import type { NextMiddlewareEvtParam, NextMiddlewareRequestParam, NextMiddlewareReturn } from './types';
import {
assertKey,
decorateRequest,
handleMultiDomainAndProxy,
redirectAdapter,
setRequestHeadersOnNextResponse,
} from './utils';
export type ClerkMiddlewareAuthObject = AuthObject & {
redirectToSignIn: RedirectFun<Response>;
};
export interface ClerkMiddlewareAuth {
(): Promise<ClerkMiddlewareAuthObject>;
protect: AuthProtect;
}
type ClerkMiddlewareHandler = (
auth: ClerkMiddlewareAuth,
request: NextMiddlewareRequestParam,
event: NextMiddlewareEvtParam,
) => NextMiddlewareReturn;
/**
* The `clerkMiddleware()` function accepts an optional object. The following options are available.
* @interface
*/
export type ClerkMiddlewareOptions = AuthenticateRequestOptions & {
/**
* If true, additional debug information will be logged to the console.
*/
debug?: boolean;
};
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/references/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(),
);
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();
resolvedClerkClient.telemetry.record(
eventMethodCalled('clerkMiddleware', {
handler: Boolean(handler),
satellite: Boolean(options.isSatellite),
proxy: Boolean(options.proxyUrl),
}),
);
if (options.debug) {
logger.enable();
}
const clerkRequest = createClerkRequest(request);
logger.debug('options', options);
logger.debug('url', () => clerkRequest.toJSON());
const authHeader = request.headers.get('authorization');
if (authHeader && authHeader.startsWith('Basic ')) {
logger.debug('Basic Auth detected');
}
const requestState = await resolvedClerkClient.authenticateRequest(
clerkRequest,
createAuthenticateRequestOptions(clerkRequest, options),
);
logger.debug('requestState', () => ({
status: requestState.status,
// @ts-expect-error : FIXME
headers: JSON.stringify(Object.fromEntries(requestState.headers)),
reason: requestState.reason,
}));
const locationHeader = requestState.headers.get(constants.Headers.Location);
if (locationHeader) {
return new Response(null, { status: 307, headers: requestState.headers });
} 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 protect = await createMiddlewareProtect(clerkRequest, authObject, redirectToSignIn);
const authObjWithMethods: ClerkMiddlewareAuthObject = Object.assign(authObject, { redirectToSignIn });
const authHandler = () => Promise.resolve(authObjWithMethods);
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);
}
// TODO @nikos: we need to make this more generic
// and move the logic in clerk/backend
if (requestState.headers) {
requestState.headers.forEach((value, key) => {
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);
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);
/**
* In keyless mode, if the publishable key is missing, let the request through, to render `<ClerkProvider/>` that will resume the flow gracefully.
*/
if (isMissingPublishableKey) {
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] => {
return {
...options,
...handleMultiDomainAndProxy(clerkRequest, options),
};
};
const createMiddlewareRedirectToSignIn = (
clerkRequest: ClerkRequest,
): ClerkMiddlewareAuthObject['redirectToSignIn'] => {
return (opts = {}) => {
const url = clerkRequest.clerkUrl.toString();
redirectToSignInError(url, opts.returnBackUrl);
};
};
const createMiddlewareProtect = (
clerkRequest: ClerkRequest,
authObject: AuthObject,
redirectToSignIn: RedirectFun<Response>,
) => {
return (async (params: any, options: any) => {
const notFound = () => nextjsNotFound();
const redirect = (url: string) =>
nextjsRedirectError(url, {
redirectUrl: url,
});
return createProtect({ request: clerkRequest, redirect, notFound, authObject, redirectToSignIn })(params, options);
}) as unknown as Promise<AuthProtect>;
};
// 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 (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',
);
}
if (isRedirectToSignInError(e)) {
return createRedirect({
redirectAdapter,
baseUrl: clerkRequest.clerkUrl,
signInUrl: requestState.signInUrl,
signUpUrl: requestState.signUpUrl,
publishableKey: requestState.publishableKey,
}).redirectToSignIn({ returnBackUrl: e.returnBackUrl });
}
if (isNextjsRedirectError(e)) {
return redirectAdapter(e.redirectUrl);
}
throw e;
};