-
Notifications
You must be signed in to change notification settings - Fork 441
Expand file tree
/
Copy pathclerk-middleware.ts
More file actions
407 lines (350 loc) · 14.4 KB
/
clerk-middleware.ts
File metadata and controls
407 lines (350 loc) · 14.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
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
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 { isDevelopmentFromPublishableKey, isDevelopmentFromSecretKey } from '@clerk/shared/keys';
import { isHttpOrHttps } from '@clerk/shared/proxy';
import { eventMethodCalled } from '@clerk/shared/telemetry';
import { handleValueOrFn } from '@clerk/shared/utils';
import type { APIContext } from 'astro';
import { authAsyncStorage } from '#async-local-storage';
import { NETLIFY_CACHE_BUST_PARAM } from '../internal';
import { buildClerkHotloadScript } from './build-clerk-hotload-script';
import { clerkClient } from './clerk-client';
import { createCurrentUser } from './current-user';
import { getAuth } from './get-auth';
import { getClientSafeEnv, getSafeEnv } from './get-safe-env';
import { serverRedirectWithAuth } from './server-redirect-with-auth';
import type {
AstroMiddleware,
AstroMiddlewareContextParam,
AstroMiddlewareNextParam,
AstroMiddlewareReturn,
} from './types';
import { isRedirect, setHeader } from './utils';
const CONTROL_FLOW_ERROR = {
REDIRECT_TO_SIGN_IN: 'CLERK_PROTECT_REDIRECT_TO_SIGN_IN',
};
type ClerkMiddlewareAuthObject = AuthObject & {
redirectToSignIn: (opts?: { returnBackUrl?: URL | string | null }) => Response;
};
type ClerkAstroMiddlewareHandler = (
auth: () => ClerkMiddlewareAuthObject,
context: AstroMiddlewareContextParam,
next: AstroMiddlewareNextParam,
) => AstroMiddlewareReturn | undefined;
type ClerkAstroMiddlewareOptions = AuthenticateRequestOptions;
/**
* Middleware for Astro that handles authentication and authorization with Clerk.
*/
interface ClerkMiddleware {
/**
* @example
* export default clerkMiddleware((auth, context, next) => { ... }, options);
*/
(handler: ClerkAstroMiddlewareHandler, options?: ClerkAstroMiddlewareOptions): AstroMiddleware;
/**
* @example
* export default clerkMiddleware(options);
*/
(options?: ClerkAstroMiddlewareOptions): AstroMiddleware;
}
export const clerkMiddleware: ClerkMiddleware = (...args: unknown[]): any => {
const [handler, options] = parseHandlerAndOptions(args);
const astroMiddleware: AstroMiddleware = async (context, next) => {
// if the current page is prerendered, do nothing
if (isPrerenderedPage(context)) {
return next();
}
const clerkRequest = createClerkRequest(context.request);
clerkClient(context).telemetry.record(
eventMethodCalled('clerkMiddleware', {
handler: Boolean(handler),
satellite: Boolean(options.isSatellite),
proxy: Boolean(options.proxyUrl),
}),
);
const requestState = await clerkClient(context).authenticateRequest(
clerkRequest,
createAuthenticateRequestOptions(clerkRequest, { ...options, entity: 'any' }, context),
);
const locationHeader = requestState.headers.get(constants.Headers.Location);
if (locationHeader) {
handleNetlifyCacheInDevInstance(locationHeader, requestState);
const res = new Response(null, { status: 307, headers: requestState.headers });
return decorateResponseWithObservabilityHeaders(res, requestState);
} else if (requestState.status === AuthStatus.Handshake) {
throw new Error('Clerk: handshake status without redirect');
}
const authObject = requestState.toAuth();
const redirectToSignIn = createMiddlewareRedirectToSignIn(clerkRequest);
const authObjWithMethods: ClerkMiddlewareAuthObject = Object.assign(authObject, { redirectToSignIn });
decorateAstroLocal(clerkRequest, context, requestState);
/**
* ALS is crucial for guaranteeing SSR in UI frameworks like React.
* This currently powers the `useAuth()` React hook and any other hook or Component that depends on it.
*/
return authAsyncStorage.run(context.locals.auth(), async () => {
/**
* Generate SSR page
*/
let handlerResult: Response;
try {
handlerResult = (await handler?.(() => authObjWithMethods, context, next)) || (await next());
} catch (e: any) {
handlerResult = handleControlFlowErrors(e, clerkRequest, requestState, context);
}
if (isRedirect(handlerResult)) {
return serverRedirectWithAuth(context, clerkRequest, handlerResult, options);
}
const response = decorateRequest(context.locals, handlerResult);
if (requestState.headers) {
requestState.headers.forEach((value, key) => {
response.headers.append(key, value);
});
}
return response;
});
};
return astroMiddleware;
};
const isPrerenderedPage = (context: APIContext) => {
return (
// for Astro v5
('isPrerendered' in context && context.isPrerendered) ||
// for Astro v4
('_isPrerendered' in context && context._isPrerendered)
);
};
// TODO-SHARED: Duplicate from '@clerk/nextjs'
const parseHandlerAndOptions = (args: unknown[]) => {
return [
typeof args[0] === 'function' ? args[0] : undefined,
(args.length === 2 ? args[1] : typeof args[0] === 'function' ? {} : args[0]) || {},
] as [ClerkAstroMiddlewareHandler | undefined, ClerkAstroMiddlewareOptions];
};
type AuthenticateRequest = Pick<ClerkClient, 'authenticateRequest'>['authenticateRequest'];
// TODO-SHARED: Duplicate from '@clerk/nextjs'
export const createAuthenticateRequestOptions = (
clerkRequest: ClerkRequest,
options: ClerkAstroMiddlewareOptions,
context: AstroMiddlewareContextParam,
): Parameters<AuthenticateRequest>[1] => {
return {
...options,
secretKey: options.secretKey || getSafeEnv(context).sk,
publishableKey: options.publishableKey || getSafeEnv(context).pk,
signInUrl: options.signInUrl || getSafeEnv(context).signInUrl,
signUpUrl: options.signUpUrl || getSafeEnv(context).signUpUrl,
...handleMultiDomainAndProxy(clerkRequest, options, context),
};
};
// TODO-SHARED: Duplicate from '@clerk/nextjs'
export const decorateResponseWithObservabilityHeaders = (res: Response, requestState: RequestState): Response => {
if (requestState.message) {
res.headers.set(constants.Headers.AuthMessage, encodeURIComponent(requestState.message));
}
if (requestState.reason) {
res.headers.set(constants.Headers.AuthReason, encodeURIComponent(requestState.reason));
}
if (requestState.status) {
res.headers.set(constants.Headers.AuthStatus, encodeURIComponent(requestState.status));
}
return res;
};
// TODO-SHARED: Duplicate from '@clerk/nextjs'
export const handleMultiDomainAndProxy = (
clerkRequest: ClerkRequest,
opts: AuthenticateRequestOptions,
context: AstroMiddlewareContextParam,
) => {
const relativeOrAbsoluteProxyUrl = handleValueOrFn(
opts?.proxyUrl,
clerkRequest.clerkUrl,
getSafeEnv(context).proxyUrl,
);
let proxyUrl;
if (!!relativeOrAbsoluteProxyUrl && !isHttpOrHttps(relativeOrAbsoluteProxyUrl)) {
proxyUrl = new URL(relativeOrAbsoluteProxyUrl, clerkRequest.clerkUrl).toString();
} else {
proxyUrl = relativeOrAbsoluteProxyUrl;
}
const isSatellite = handleValueOrFn(opts.isSatellite, new URL(clerkRequest.url), getSafeEnv(context).isSatellite);
const domain = handleValueOrFn(opts.domain, new URL(clerkRequest.url), getSafeEnv(context).domain);
const signInUrl = opts?.signInUrl || getSafeEnv(context).signInUrl;
if (isSatellite && !proxyUrl && !domain) {
throw new Error(missingDomainAndProxy);
}
if (
isSatellite &&
!isHttpOrHttps(signInUrl) &&
isDevelopmentFromSecretKey(opts.secretKey || getSafeEnv(context).sk!)
) {
throw new Error(missingSignInUrlInDev);
}
return {
proxyUrl,
isSatellite,
domain,
};
};
export const missingDomainAndProxy = `
Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.
1) With middleware
e.g. export default clerkMiddleware({domain:'YOUR_DOMAIN',isSatellite:true});
2) With environment variables e.g.
PUBLIC_CLERK_DOMAIN='YOUR_DOMAIN'
PUBLIC_CLERK_IS_SATELLITE='true'
`;
export const missingSignInUrlInDev = `
Invalid signInUrl. A satellite application requires a signInUrl for development instances.
Check if signInUrl is missing from your configuration or if it is not an absolute URL
1) With middleware
e.g. export default clerkMiddleware({signInUrl:'SOME_URL', isSatellite:true});
2) With environment variables e.g.
PUBLIC_CLERK_SIGN_IN_URL='SOME_URL'
PUBLIC_CLERK_IS_SATELLITE='true'`;
/**
* Prevents infinite redirects in Netlify's functions
* by adding a cache bust parameter to the original redirect URL. This ensures Netlify
* doesn't serve a cached response during the authentication flow.
*/
function handleNetlifyCacheInDevInstance(locationHeader: string, requestState: RequestState) {
// Only run on Netlify environment and Clerk development instance
// eslint-disable-next-line turbo/no-undeclared-env-vars
if (import.meta.env.NETLIFY && isDevelopmentFromPublishableKey(requestState.publishableKey)) {
const hasHandshakeQueryParam = locationHeader.includes('__clerk_handshake');
// If location header is the original URL before the handshake redirects, add cache bust param
if (!hasHandshakeQueryParam) {
const url = new URL(locationHeader);
url.searchParams.append(NETLIFY_CACHE_BUST_PARAM, Date.now().toString());
requestState.headers.set('Location', url.toString());
}
}
}
function decorateAstroLocal(clerkRequest: ClerkRequest, context: APIContext, requestState: RequestState) {
const { reason, message, status, token } = requestState;
context.locals.authToken = token;
context.locals.authStatus = status;
context.locals.authMessage = message;
context.locals.authReason = reason;
context.locals.auth = () => {
const authObject = getAuth(clerkRequest, context.locals);
const clerkUrl = clerkRequest.clerkUrl;
const redirectToSignIn: RedirectFun<Response> = (opts = {}) => {
const devBrowserToken =
clerkRequest.clerkUrl.searchParams.get(constants.QueryParameters.DevBrowser) ||
clerkRequest.cookies.get(constants.Cookies.DevBrowser);
return createRedirect({
redirectAdapter,
devBrowserToken: devBrowserToken,
baseUrl: clerkUrl.toString(),
publishableKey: getSafeEnv(context).pk!,
signInUrl: requestState.signInUrl,
signUpUrl: requestState.signUpUrl,
}).redirectToSignIn({
returnBackUrl: opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkUrl.toString(),
});
};
return Object.assign(authObject, { redirectToSignIn });
};
context.locals.currentUser = createCurrentUser(clerkRequest, context);
}
/**
* Find the index of the closing head tag in the chunk.
*
* Note: This implementation uses a simple approach that works for most of our
* current use cases.
*/
function findClosingHeadTagIndex(chunk: Uint8Array, endHeadTag: Uint8Array) {
return chunk.findIndex((_, i) => endHeadTag.every((value, j) => value === chunk[i + j]));
}
function decorateRequest(locals: APIContext['locals'], res: Response): Response {
/**
* Populate every page with the authObject. This allows for SSR to work properly
* without sucrificing DX and having developers wrap each page with a Layout that would handle this.
*/
if (res.headers.get('content-type') === 'text/html') {
const encoder = new TextEncoder();
const closingHeadTag = encoder.encode('</head>');
const clerkAstroData = encoder.encode(
`<script id="__CLERK_ASTRO_DATA__" type="application/json">${JSON.stringify(locals.auth())}</script>\n`,
);
const clerkSafeEnvVariables = encoder.encode(
`<script id="__CLERK_ASTRO_SAFE_VARS__" type="application/json">${JSON.stringify(getClientSafeEnv(locals))}</script>\n`,
);
const hotloadScript = encoder.encode(buildClerkHotloadScript(locals));
const stream = res.body!.pipeThrough(
new TransformStream({
transform(chunk, controller) {
const index = findClosingHeadTagIndex(chunk, closingHeadTag);
const isClosingHeadTagFound = index !== -1;
/**
* Hijack html response to position `__CLERK_ASTRO_DATA__` before the closing `head` html tag
*/
if (isClosingHeadTagFound) {
controller.enqueue(chunk.slice(0, index));
controller.enqueue(clerkAstroData);
controller.enqueue(clerkSafeEnvVariables);
controller.enqueue(hotloadScript);
controller.enqueue(closingHeadTag);
controller.enqueue(chunk.slice(index + closingHeadTag.length));
} else {
controller.enqueue(chunk);
}
},
}),
);
const modifiedResponse = new Response(stream, {
status: res.status,
statusText: res.statusText,
headers: res.headers,
});
return modifiedResponse;
}
return res;
}
const redirectAdapter = (url: string | URL) => {
const res = new Response(null, {
status: 307,
});
/**
* Hint to clerk to add cookie with db jwt
*/
setHeader(res, constants.Headers.ClerkRedirectTo, 'true');
return setHeader(res, 'Location', url instanceof URL ? url.href : url);
};
const createMiddlewareRedirectToSignIn = (
clerkRequest: ClerkRequest,
): ClerkMiddlewareAuthObject['redirectToSignIn'] => {
return (opts = {}) => {
const err = new Error(CONTROL_FLOW_ERROR.REDIRECT_TO_SIGN_IN) as any;
err.returnBackUrl = opts.returnBackUrl === null ? '' : opts.returnBackUrl || clerkRequest.clerkUrl.toString();
throw err;
};
};
// Handle errors thrown by 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,
requestState: RequestState,
context: AstroMiddlewareContextParam,
): Response => {
switch (e.message) {
case CONTROL_FLOW_ERROR.REDIRECT_TO_SIGN_IN:
return createRedirect({
redirectAdapter,
baseUrl: clerkRequest.clerkUrl,
signInUrl: requestState.signInUrl,
signUpUrl: requestState.signUpUrl,
publishableKey: getSafeEnv(context).pk!,
}).redirectToSignIn({ returnBackUrl: e.returnBackUrl });
default:
throw e;
}
};