-
Notifications
You must be signed in to change notification settings - Fork 462
Expand file tree
/
Copy pathrequest.ts
More file actions
955 lines (860 loc) · 36.5 KB
/
Copy pathrequest.ts
File metadata and controls
955 lines (860 loc) · 36.5 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
import type { JwtPayload } from '@clerk/shared/types';
import { constants } from '../constants';
import type { TokenCarrier } from '../errors';
import { MachineTokenVerificationError, TokenVerificationError, TokenVerificationErrorReason } from '../errors';
import { decodeJwt } from '../jwt/verifyJwt';
import { assertValidSecretKey } from '../util/optionsAssertions';
import { isDevelopmentFromSecretKey } from '../util/shared';
import type { AuthenticateContext } from './authenticateContext';
import { createAuthenticateContext } from './authenticateContext';
import type { SignedInAuthObject } from './authObjects';
import type { HandshakeState, RequestState, SignedInState, SignedOutState, UnauthenticatedState } from './authStatus';
import { AuthErrorReason, handshake, signedIn, signedOut, signedOutInvalidToken } from './authStatus';
import { createClerkRequest } from './clerkRequest';
import { getCookieName, getCookieValue } from './cookie';
import { HandshakeService } from './handshake';
import {
getMachineTokenType,
isMachineJwt,
isMachineToken,
isMachineTokenByPrefix,
isTokenTypeAccepted,
} from './machine';
import { checkMachineTokenRateLimit } from './machineTokenRateLimiter';
import { OrganizationMatcher } from './organizationMatcher';
import type { MachineTokenType, SessionTokenType } from './tokenTypes';
import { TokenType } from './tokenTypes';
import type { AuthenticateRequestOptions } from './types';
import { verifyMachineAuthToken, verifyToken } from './verify';
// NOTE: IP headers like x-forwarded-for can be spoofed by clients not behind a trusted proxy.
// cf-connecting-ip (set by Cloudflare) and x-real-ip (set by Nginx) are more reliable when present.
// The rate limiter is defense-in-depth against BAPI quota exhaustion, not a security boundary.
function extractCallerIp(request: Request): string {
const cfConnectingIp = request.headers.get(constants.Headers.CfConnectingIp);
if (cfConnectingIp) {
return cfConnectingIp;
}
const xRealIp = request.headers.get(constants.Headers.RealIp);
if (xRealIp) {
return xRealIp;
}
const xForwardedFor = request.headers.get(constants.Headers.ForwardedFor);
if (xForwardedFor) {
return xForwardedFor.split(',')[0]?.trim() ?? 'unknown';
}
return 'unknown';
}
export const RefreshTokenErrorReason = {
NonEligibleNoCookie: 'non-eligible-no-refresh-cookie',
NonEligibleNonGet: 'non-eligible-non-get',
InvalidSessionToken: 'invalid-session-token',
MissingApiClient: 'missing-api-client',
MissingSessionToken: 'missing-session-token',
MissingRefreshToken: 'missing-refresh-token',
ExpiredSessionTokenDecodeFailed: 'expired-session-token-decode-failed',
ExpiredSessionTokenMissingSidClaim: 'expired-session-token-missing-sid-claim',
FetchError: 'fetch-error',
UnexpectedSDKError: 'unexpected-sdk-error',
UnexpectedBAPIError: 'unexpected-bapi-error',
} as const;
function assertSignInUrlExists(signInUrl: string | undefined, key: string): asserts signInUrl is string {
if (!signInUrl && isDevelopmentFromSecretKey(key)) {
throw new Error(`Missing signInUrl. Pass a signInUrl for dev instances if an app is satellite`);
}
}
function assertProxyUrlOrDomain(proxyUrlOrDomain: string | undefined) {
if (!proxyUrlOrDomain) {
throw new Error(`Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl`);
}
}
function assertSignInUrlFormatAndOrigin(_signInUrl: string, origin: string) {
let signInUrl: URL;
try {
signInUrl = new URL(_signInUrl);
} catch {
throw new Error(`The signInUrl needs to have a absolute url format.`);
}
if (signInUrl.origin === origin) {
throw new Error(`The signInUrl needs to be on a different origin than your satellite application.`);
}
}
function assertMachineSecretOrSecretKey(authenticateContext: AuthenticateContext) {
if (!authenticateContext.machineSecretKey && !authenticateContext.secretKey) {
throw new Error(
'Machine token authentication requires either a Machine secret key or a Clerk secret key. ' +
'Ensure a Clerk secret key or Machine secret key is set.',
);
}
}
function isRequestEligibleForRefresh(
err: TokenVerificationError,
authenticateContext: { refreshTokenInCookie?: string },
request: Request,
) {
return (
err.reason === TokenVerificationErrorReason.TokenExpired &&
!!authenticateContext.refreshTokenInCookie &&
request.method === 'GET'
);
}
function checkTokenTypeMismatch(
parsedTokenType: MachineTokenType,
acceptsToken: NonNullable<AuthenticateRequestOptions['acceptsToken']>,
authenticateContext: AuthenticateContext,
): UnauthenticatedState<MachineTokenType> | null {
const mismatch = !isTokenTypeAccepted(parsedTokenType, acceptsToken);
if (mismatch) {
const tokenTypeToReturn = (typeof acceptsToken === 'string' ? acceptsToken : parsedTokenType) as MachineTokenType;
return signedOut({
tokenType: tokenTypeToReturn,
authenticateContext,
reason: AuthErrorReason.TokenTypeMismatch,
});
}
return null;
}
function isTokenTypeInAcceptedArray(acceptsToken: TokenType[], authenticateContext: AuthenticateContext): boolean {
let parsedTokenType: TokenType | null = null;
const { tokenInHeader } = authenticateContext;
if (tokenInHeader) {
if (isMachineToken(tokenInHeader)) {
parsedTokenType = getMachineTokenType(tokenInHeader);
} else {
parsedTokenType = TokenType.SessionToken;
}
}
const typeToCheck = parsedTokenType ?? TokenType.SessionToken;
return isTokenTypeAccepted(typeToCheck, acceptsToken);
}
export interface AuthenticateRequest {
/**
* @example
* clerkClient.authenticateRequest(request, { acceptsToken: ['session_token', 'api_key'] });
*/
<T extends readonly TokenType[]>(
request: Request,
options: AuthenticateRequestOptions & { acceptsToken: T },
): Promise<RequestState<T[number] | null>>;
/**
* @example
* clerkClient.authenticateRequest(request, { acceptsToken: 'session_token' });
*/
<T extends TokenType>(
request: Request,
options: AuthenticateRequestOptions & { acceptsToken: T },
): Promise<RequestState<T>>;
/**
* @example
* clerkClient.authenticateRequest(request, { acceptsToken: 'any' });
*/
(request: Request, options: AuthenticateRequestOptions & { acceptsToken: 'any' }): Promise<RequestState<TokenType>>;
/**
* @example
* clerkClient.authenticateRequest(request);
*/
(request: Request, options?: AuthenticateRequestOptions): Promise<RequestState<SessionTokenType>>;
}
export const authenticateRequest: AuthenticateRequest = (async (
request: Request,
options: AuthenticateRequestOptions,
): Promise<RequestState<TokenType> | UnauthenticatedState<null>> => {
const authenticateContext = await createAuthenticateContext(createClerkRequest(request), options);
// Default tokenType is session_token for backwards compatibility.
const acceptsToken = options.acceptsToken ?? TokenType.SessionToken;
// machine-to-machine tokens can accept a machine secret or a secret key
if (acceptsToken !== TokenType.M2MToken) {
assertValidSecretKey(authenticateContext.secretKey);
if (authenticateContext.isSatellite) {
assertSignInUrlExists(authenticateContext.signInUrl, authenticateContext.secretKey);
if (authenticateContext.signInUrl && authenticateContext.origin) {
assertSignInUrlFormatAndOrigin(authenticateContext.signInUrl, authenticateContext.origin);
}
assertProxyUrlOrDomain(authenticateContext.proxyUrl || authenticateContext.domain);
}
}
// Make sure a machine secret or instance secret key is provided if acceptsToken is m2m_token
if (acceptsToken === TokenType.M2MToken) {
assertMachineSecretOrSecretKey(authenticateContext);
}
const organizationMatcher = new OrganizationMatcher(options.organizationSyncOptions);
const handshakeService = new HandshakeService(
authenticateContext,
{ organizationSyncOptions: options.organizationSyncOptions },
organizationMatcher,
);
async function refreshToken(
authenticateContext: AuthenticateContext,
): Promise<{ data: string[]; error: null } | { data: null; error: any }> {
// To perform a token refresh, apiClient must be defined.
if (!options.apiClient) {
return {
data: null,
error: {
message: 'An apiClient is needed to perform token refresh.',
cause: { reason: RefreshTokenErrorReason.MissingApiClient },
},
};
}
const { sessionToken: expiredSessionToken, refreshTokenInCookie: refreshToken } = authenticateContext;
if (!expiredSessionToken) {
return {
data: null,
error: {
message: 'Session token must be provided.',
cause: { reason: RefreshTokenErrorReason.MissingSessionToken },
},
};
}
if (!refreshToken) {
return {
data: null,
error: {
message: 'Refresh token must be provided.',
cause: { reason: RefreshTokenErrorReason.MissingRefreshToken },
},
};
}
// The token refresh endpoint requires a sessionId, so we decode that from the expired token.
const { data: decodeResult, errors: decodedErrors } = decodeJwt(expiredSessionToken);
if (!decodeResult || decodedErrors) {
return {
data: null,
error: {
message: 'Unable to decode the expired session token.',
cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenDecodeFailed, errors: decodedErrors },
},
};
}
if (!decodeResult?.payload?.sid) {
return {
data: null,
error: {
message: 'Expired session token is missing the `sid` claim.',
cause: { reason: RefreshTokenErrorReason.ExpiredSessionTokenMissingSidClaim },
},
};
}
try {
// Perform the actual token refresh.
const response = await options.apiClient.sessions.refreshSession(decodeResult.payload.sid, {
format: 'cookie',
suffixed_cookies: authenticateContext.usesSuffixedCookies(),
expired_token: expiredSessionToken || '',
refresh_token: refreshToken || '',
request_origin: authenticateContext.clerkUrl.origin,
// The refresh endpoint expects headers as Record<string, string[]>, so we need to transform it.
request_headers: Object.fromEntries(Array.from(request.headers.entries()).map(([k, v]) => [k, [v]])),
});
return { data: response.cookies, error: null };
} catch (err: any) {
if (err?.errors?.length) {
if (err.errors[0].code === 'unexpected_error') {
return {
data: null,
error: {
message: `Fetch unexpected error`,
cause: { reason: RefreshTokenErrorReason.FetchError, errors: err.errors },
},
};
}
return {
data: null,
error: {
message: err.errors[0].code,
cause: { reason: err.errors[0].code, errors: err.errors },
},
};
} else {
return {
data: null,
error: {
message: `Unexpected Server/BAPI error`,
cause: { reason: RefreshTokenErrorReason.UnexpectedBAPIError, errors: [err] },
},
};
}
}
}
async function attemptRefresh(
authenticateContext: AuthenticateContext,
): Promise<
| { data: { jwtPayload: JwtPayload; sessionToken: string; headers: Headers }; error: null }
| { data: null; error: any }
> {
const { data: cookiesToSet, error } = await refreshToken(authenticateContext);
if (!cookiesToSet || cookiesToSet.length === 0) {
return { data: null, error };
}
const headers = new Headers();
let sessionToken = '';
cookiesToSet.forEach((x: string) => {
headers.append('Set-Cookie', x);
if (getCookieName(x).startsWith(constants.Cookies.Session)) {
sessionToken = getCookieValue(x);
}
});
// Since we're going to return a signedIn response, we need to decode the data from the new sessionToken.
const { data: jwtPayload, errors } = await verifyToken(sessionToken, authenticateContext);
if (errors) {
return {
data: null,
error: {
message: `Clerk: unable to verify refreshed session token.`,
cause: { reason: RefreshTokenErrorReason.InvalidSessionToken, errors },
},
};
}
return { data: { jwtPayload, sessionToken, headers }, error: null };
}
function handleMaybeHandshakeStatus(
authenticateContext: AuthenticateContext,
reason: string,
message: string,
headers?: Headers,
): SignedInState | SignedOutState | HandshakeState {
if (!handshakeService.isRequestEligibleForHandshake()) {
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason,
message,
});
}
// Right now the only usage of passing in different headers is for multi-domain sync, which redirects somewhere else.
// In the future if we want to decorate the handshake redirect with additional headers per call we need to tweak this logic.
const handshakeHeaders = headers ?? handshakeService.buildRedirectToHandshake(reason);
// Chrome aggressively caches inactive tabs. If we don't set the header here,
// all 307 redirects will be cached and the handshake will end up in an infinite loop.
if (handshakeHeaders.get(constants.Headers.Location)) {
handshakeHeaders.set(constants.Headers.CacheControl, 'no-store');
}
// Introduce the mechanism to protect for infinite handshake redirect loops
// using a cookie and returning true if it's infinite redirect loop or false if we can
// proceed with triggering handshake.
const isRedirectLoop = handshakeService.checkAndTrackRedirectLoop(handshakeHeaders);
if (isRedirectLoop) {
const msg = `Clerk: Refreshing the session token resulted in an infinite redirect loop. This usually means that your Clerk instance keys do not match - make sure to copy the correct publishable and secret keys from the Clerk dashboard.`;
console.log(msg);
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason,
message,
});
}
return handshake(authenticateContext, reason, message, handshakeHeaders);
}
/**
* Determines if a handshake must occur to resolve a mismatch between the organization as specified
* by the URL (according to the options) and the actual active organization on the session.
*
* @returns {HandshakeState | SignedOutState | null} - The function can return the following:
* - {HandshakeState}: If a handshake is needed to resolve the mismatched organization.
* - {SignedOutState}: If a handshake is required but cannot be performed.
* - {null}: If no action is required.
*/
function handleMaybeOrganizationSyncHandshake(
authenticateContext: AuthenticateContext,
auth: SignedInAuthObject,
): HandshakeState | SignedOutState | null {
const organizationSyncTarget = organizationMatcher.findTarget(authenticateContext.clerkUrl);
if (!organizationSyncTarget) {
return null;
}
let mustActivate = false;
if (organizationSyncTarget.type === 'organization') {
// Activate an org by slug?
if (organizationSyncTarget.organizationSlug && organizationSyncTarget.organizationSlug !== auth.orgSlug) {
mustActivate = true;
}
// Activate an org by ID?
if (organizationSyncTarget.organizationId && organizationSyncTarget.organizationId !== auth.orgId) {
mustActivate = true;
}
}
// Activate the personal account?
if (organizationSyncTarget.type === 'personalAccount' && auth.orgId) {
mustActivate = true;
}
if (!mustActivate) {
return null;
}
if (authenticateContext.handshakeRedirectLoopCounter >= 3) {
// We have an organization that needs to be activated, but this isn't our first time redirecting.
// This is because we attempted to activate the organization previously, but the organization
// must not have been valid (either not found, or not valid for this user), and gave us back
// a null organization. We won't re-try the handshake, and leave it to the server component to handle.
console.warn(
'Clerk: Organization activation handshake loop detected. This is likely due to an invalid organization ID or slug. Skipping organization activation.',
);
return null;
}
const handshakeState = handleMaybeHandshakeStatus(
authenticateContext,
AuthErrorReason.ActiveOrganizationMismatch,
'',
);
if (handshakeState.status !== 'handshake') {
// Currently, this is only possible if we're in a redirect loop, but the above check should guard against that.
return null;
}
return handshakeState;
}
async function authenticateRequestWithTokenInHeader() {
const { tokenInHeader } = authenticateContext;
// Reject machine JWTs (OAuth or M2M) that may appear in headers when expecting session tokens.
// These are valid Clerk-signed JWTs and will pass verify() verification,
// but should not be accepted as session tokens.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (isMachineJwt(tokenInHeader!)) {
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason: AuthErrorReason.TokenTypeMismatch,
message: '',
});
}
try {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { data, errors } = await verifyToken(tokenInHeader!, authenticateContext);
if (errors) {
throw errors[0];
}
// use `await` to force this try/catch handle the signedIn invocation
return signedIn({
tokenType: TokenType.SessionToken,
authenticateContext,
sessionClaims: data,
headers: new Headers(),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
token: tokenInHeader!,
});
} catch (err) {
return handleSessionTokenError(err, 'header');
}
}
async function authenticateRequestWithTokenInCookie() {
const hasActiveClient = authenticateContext.clientUat;
const hasSessionToken = !!authenticateContext.sessionTokenInCookie;
const hasDevBrowserToken = !!authenticateContext.devBrowserToken;
/**
* If we have a handshakeToken, resolve the handshake and attempt to return a definitive signed in or signed out state.
*/
if (authenticateContext.handshakeNonce || authenticateContext.handshakeToken) {
try {
return await handshakeService.resolveHandshake();
} catch (error) {
// In production, the handshake token is being transferred as a cookie, so there is a possibility of collision
// with a handshake token of another app running on the same etld+1 domain.
// For example, if one app is running on sub1.clerk.com and another on sub2.clerk.com, the handshake token
// cookie for both apps will be set on etld+1 (clerk.com) so there's a possibility that one app will accidentally
// use the handshake token of a different app during the handshake flow.
// In this scenario, verification will fail with TokenInvalidSignature. In contrast to the development case,
// we need to allow the flow to continue so the app eventually retries another handshake with the correct token.
// We need to make sure, however, that we don't allow the flow to continue indefinitely, so we throw an error after X
// retries to avoid an infinite loop. An infinite loop can happen if the customer switched Clerk keys for their prod app.
// Check the handleTokenVerificationErrorInDevelopment method for the development case.
if (error instanceof TokenVerificationError && authenticateContext.instanceType === 'development') {
handshakeService.handleTokenVerificationErrorInDevelopment(error);
} else {
console.error('Clerk: unable to resolve handshake:', error);
}
}
}
const isRequestEligibleForMultiDomainSync =
authenticateContext.isSatellite &&
authenticateContext.secFetchDest === 'document' &&
authenticateContext.method === 'GET';
/**
* Begin multi-domain sync flows
*
* Sync status values (__clerk_synced query param):
* - 'false' (NeedsSync): Trigger sync - satellite returning from primary sign-in
* - 'true' (Completed): Sync done - prevents re-sync loop
*
* With satelliteAutoSync=false or unset (Core 3 default):
* - Skip handshake on first visit if no cookies exist (return signedOut immediately)
* - Trigger handshake when __clerk_synced=false is present (post sign-in redirect)
* - Allow normal token verification flow when cookies exist (enables refresh)
*/
// Check sync status param (__clerk_synced=false triggers sync, __clerk_synced=true means completed)
const syncedParam = authenticateContext.clerkUrl.searchParams.get(constants.QueryParameters.ClerkSynced);
const needsSync = syncedParam === constants.ClerkSyncStatus.NeedsSync;
const syncCompleted = syncedParam === constants.ClerkSyncStatus.Completed;
// Check if cookies exist (session token or active client UAT)
const hasCookies = hasSessionToken || hasActiveClient;
// Determine if we should skip handshake for satellites with no cookies
// satelliteAutoSync defaults to false (Core 3), so we skip unless explicitly set to true
const shouldSkipSatelliteHandshake = authenticateContext.satelliteAutoSync !== true && !hasCookies && !needsSync;
if (authenticateContext.instanceType === 'production' && isRequestEligibleForMultiDomainSync && !syncCompleted) {
// With satelliteAutoSync=false: skip handshake if no cookies and no sync trigger
if (shouldSkipSatelliteHandshake) {
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason: AuthErrorReason.SessionTokenAndUATMissing,
});
}
// If cookies exist, fall through to normal token verification flow (enables refresh)
// Only trigger handshake if no cookies exist (or sync was explicitly requested)
if (!hasCookies || needsSync) {
return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SatelliteCookieNeedsSyncing, '');
}
// Fall through to normal token verification flow when cookies exist
}
// Multi-domain development sync flow
if (authenticateContext.instanceType === 'development' && isRequestEligibleForMultiDomainSync && !syncCompleted) {
// With satelliteAutoSync=false: skip sync if no cookies and no sync trigger
if (shouldSkipSatelliteHandshake) {
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason: AuthErrorReason.SessionTokenAndUATMissing,
});
}
// If cookies exist, fall through to normal flow (enables refresh)
if (!hasCookies || needsSync) {
// initiate MD sync
// signInUrl exists, checked at the top of `authenticateRequest`
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const redirectURL = new URL(authenticateContext.signInUrl!);
redirectURL.searchParams.append(
constants.QueryParameters.ClerkRedirectUrl,
authenticateContext.clerkUrl.toString(),
);
const headers = new Headers({ [constants.Headers.Location]: redirectURL.toString() });
return handleMaybeHandshakeStatus(
authenticateContext,
AuthErrorReason.SatelliteCookieNeedsSyncing,
'',
headers,
);
}
// Fall through to normal token verification flow when cookies exist
}
// Multi-domain development sync flow - primary responds to syncing
// IMPORTANT: This must come BEFORE dev-browser-sync check to avoid the root domain
// triggering its own handshakes when it's in the middle of handling a satellite sync request
const redirectUrl = new URL(authenticateContext.clerkUrl).searchParams.get(
constants.QueryParameters.ClerkRedirectUrl,
);
if (authenticateContext.instanceType === 'development' && !authenticateContext.isSatellite && redirectUrl) {
// Dev MD sync from primary, redirect back to satellite w/ dev browser query param
const redirectBackToSatelliteUrl = new URL(redirectUrl);
if (authenticateContext.devBrowserToken) {
redirectBackToSatelliteUrl.searchParams.append(
constants.QueryParameters.DevBrowser,
authenticateContext.devBrowserToken,
);
}
// Use set (not append) to ensure completion status overwrites any existing NeedsSync value
// This prevents sync loops when the redirect URL already contains __clerk_synced=false
redirectBackToSatelliteUrl.searchParams.set(
constants.QueryParameters.ClerkSynced,
constants.ClerkSyncStatus.Completed,
);
const headers = new Headers({ [constants.Headers.Location]: redirectBackToSatelliteUrl.toString() });
return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.PrimaryRespondsToSyncing, '', headers);
}
/**
* End multi-domain sync flows
*/
/**
* Otherwise, check for "known unknown" auth states that we can resolve with a handshake.
*/
if (
authenticateContext.instanceType === 'development' &&
authenticateContext.clerkUrl.searchParams.has(constants.QueryParameters.DevBrowser)
) {
return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserSync, '');
}
if (authenticateContext.instanceType === 'development' && !hasDevBrowserToken) {
return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.DevBrowserMissing, '');
}
if (!hasActiveClient && !hasSessionToken) {
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason: AuthErrorReason.SessionTokenAndUATMissing,
});
}
// This can eagerly run handshake since client_uat is SameSite=Strict in dev
if (!hasActiveClient && hasSessionToken) {
return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenWithoutClientUAT, '');
}
if (hasActiveClient && !hasSessionToken) {
return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.ClientUATWithoutSessionToken, '');
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { data: decodeResult, errors: decodedErrors } = decodeJwt(authenticateContext.sessionTokenInCookie!);
if (decodedErrors) {
return handleSessionTokenError(decodedErrors[0], 'cookie');
}
if (decodeResult.payload.iat < authenticateContext.clientUat) {
return handleMaybeHandshakeStatus(authenticateContext, AuthErrorReason.SessionTokenIATBeforeClientUAT, '');
}
try {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { data, errors } = await verifyToken(authenticateContext.sessionTokenInCookie!, authenticateContext);
if (errors) {
throw errors[0];
}
if (!data.azp) {
console.warn(
'Clerk: Session token from cookie is missing the azp claim. In a future version of Clerk, this token will be considered invalid. Please contact Clerk support if you see this warning.',
);
}
const signedInRequestState = signedIn({
tokenType: TokenType.SessionToken,
authenticateContext,
sessionClaims: data,
headers: new Headers(),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
token: authenticateContext.sessionTokenInCookie!,
});
// Check for cross-origin requests from satellite domains to primary domain
const shouldForceHandshakeForCrossDomain =
!authenticateContext.isSatellite && // We're on primary
authenticateContext.method === 'GET' && // Only GET navigations (POST form submissions set sec-fetch-dest: document too)
authenticateContext.secFetchDest === 'document' && // Document navigation
authenticateContext.isCrossOriginReferrer() && // Came from different domain
!authenticateContext.isKnownClerkReferrer() && // Not from Clerk accounts portal or FAPI
authenticateContext.handshakeRedirectLoopCounter === 0; // Not in a redirect loop
if (shouldForceHandshakeForCrossDomain) {
return handleMaybeHandshakeStatus(
authenticateContext,
AuthErrorReason.PrimaryDomainCrossOriginSync,
'Cross-origin request from satellite domain requires handshake',
);
}
const authObject = signedInRequestState.toAuth();
// Org sync if necessary
if (authObject.userId) {
const handshakeRequestState = handleMaybeOrganizationSyncHandshake(authenticateContext, authObject);
if (handshakeRequestState) {
return handshakeRequestState;
}
}
return signedInRequestState;
} catch (err) {
return handleSessionTokenError(err, 'cookie');
}
// Unreachable
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason: AuthErrorReason.UnexpectedError,
});
}
async function handleSessionTokenError(
err: unknown,
tokenCarrier: TokenCarrier,
): Promise<SignedInState | SignedOutState | HandshakeState> {
if (!(err instanceof TokenVerificationError)) {
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason: AuthErrorReason.UnexpectedError,
});
}
let refreshError: string | null;
if (isRequestEligibleForRefresh(err, authenticateContext, request)) {
const { data, error } = await attemptRefresh(authenticateContext);
if (data) {
return signedIn({
tokenType: TokenType.SessionToken,
authenticateContext,
sessionClaims: data.jwtPayload,
headers: data.headers,
token: data.sessionToken,
});
}
// If there's any error, simply fallback to the handshake flow including the reason as a query parameter.
if (error?.cause?.reason) {
refreshError = error.cause.reason;
} else {
refreshError = RefreshTokenErrorReason.UnexpectedSDKError;
}
} else {
if (request.method !== 'GET') {
refreshError = RefreshTokenErrorReason.NonEligibleNonGet;
} else if (!authenticateContext.refreshTokenInCookie) {
refreshError = RefreshTokenErrorReason.NonEligibleNoCookie;
} else {
//refresh error is not applicable if token verification error is not 'session-token-expired'
refreshError = null;
}
}
err.tokenCarrier = tokenCarrier;
const reasonToHandshake = [
TokenVerificationErrorReason.TokenExpired,
TokenVerificationErrorReason.TokenNotActiveYet,
TokenVerificationErrorReason.TokenIatInTheFuture,
].includes(err.reason);
if (reasonToHandshake) {
return handleMaybeHandshakeStatus(
authenticateContext,
convertTokenVerificationErrorReasonToAuthErrorReason({ tokenError: err.reason, refreshError }),
err.getFullMessage(),
);
}
return signedOut({
tokenType: TokenType.SessionToken,
authenticateContext,
reason: err.reason,
message: err.getFullMessage(),
});
}
function handleMachineError(tokenType: MachineTokenType, err: unknown): UnauthenticatedState<MachineTokenType> {
if (!(err instanceof MachineTokenVerificationError)) {
return signedOut({
tokenType,
authenticateContext,
reason: AuthErrorReason.UnexpectedError,
});
}
return signedOut({
tokenType,
authenticateContext,
reason: err.code,
message: err.getFullMessage(),
});
}
async function authenticateMachineRequestWithTokenInHeader() {
const { tokenInHeader } = authenticateContext;
// Use session token error handling if no token in header (default behavior)
if (!tokenInHeader) {
return handleSessionTokenError(new Error('Missing token in header'), 'header');
}
// Handle case where tokenType is any and the token is not a machine token
if (!isMachineToken(tokenInHeader)) {
return signedOut({
tokenType: acceptsToken as TokenType,
authenticateContext,
reason: AuthErrorReason.TokenTypeMismatch,
message: '',
});
}
const parsedTokenType = getMachineTokenType(tokenInHeader);
const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);
if (mismatchState) {
return mismatchState;
}
if (isMachineTokenByPrefix(tokenInHeader) && !checkMachineTokenRateLimit(extractCallerIp(request))) {
return signedOut({
tokenType: parsedTokenType,
authenticateContext,
reason: AuthErrorReason.MachineTokenRateLimit,
message: '',
});
}
const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);
if (errors) {
return handleMachineError(tokenType, errors[0]);
}
return signedIn({
tokenType,
authenticateContext,
machineData: data,
token: tokenInHeader,
});
}
async function authenticateAnyRequestWithTokenInHeader() {
const { tokenInHeader } = authenticateContext;
// Use session token error handling if no token in header (default behavior)
if (!tokenInHeader) {
return handleSessionTokenError(new Error('Missing token in header'), 'header');
}
// Handle as a machine token
if (isMachineToken(tokenInHeader)) {
const parsedTokenType = getMachineTokenType(tokenInHeader);
const mismatchState = checkTokenTypeMismatch(parsedTokenType, acceptsToken, authenticateContext);
if (mismatchState) {
return mismatchState;
}
if (isMachineTokenByPrefix(tokenInHeader) && !checkMachineTokenRateLimit(extractCallerIp(request))) {
return signedOut({
tokenType: parsedTokenType,
authenticateContext,
reason: AuthErrorReason.MachineTokenRateLimit,
message: '',
});
}
const { data, tokenType, errors } = await verifyMachineAuthToken(tokenInHeader, authenticateContext);
if (errors) {
return handleMachineError(tokenType, errors[0]);
}
return signedIn({
tokenType,
authenticateContext,
machineData: data,
token: tokenInHeader,
});
}
// Handle as a regular session token
const { data, errors } = await verifyToken(tokenInHeader, authenticateContext);
if (errors) {
return handleSessionTokenError(errors[0], 'header');
}
return signedIn({
tokenType: TokenType.SessionToken,
authenticateContext,
sessionClaims: data,
token: tokenInHeader,
});
}
// If acceptsToken is an array, early check if the token is in the accepted array
// to avoid unnecessary verification calls
if (Array.isArray(acceptsToken)) {
if (!isTokenTypeInAcceptedArray(acceptsToken, authenticateContext)) {
return signedOutInvalidToken();
}
}
if (authenticateContext.tokenInHeader) {
if (acceptsToken === 'any' || Array.isArray(acceptsToken)) {
return authenticateAnyRequestWithTokenInHeader();
}
if (acceptsToken === TokenType.SessionToken) {
return authenticateRequestWithTokenInHeader();
}
return authenticateMachineRequestWithTokenInHeader();
}
// Machine requests cannot have the token in the cookie, it must be in header.
if (
acceptsToken === TokenType.OAuthToken ||
acceptsToken === TokenType.ApiKey ||
acceptsToken === TokenType.M2MToken
) {
return signedOut({
tokenType: acceptsToken,
authenticateContext,
reason: 'No token in header',
});
}
return authenticateRequestWithTokenInCookie();
}) as AuthenticateRequest;
/**
* @internal
*/
export const debugRequestState = (params: RequestState) => {
const { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain } = params;
return { isSignedIn, isAuthenticated, proxyUrl, reason, message, publishableKey, isSatellite, domain };
};
const convertTokenVerificationErrorReasonToAuthErrorReason = ({
tokenError,
refreshError,
}: {
tokenError: TokenVerificationErrorReason;
refreshError: string | null;
}): string => {
switch (tokenError) {
case TokenVerificationErrorReason.TokenExpired:
return `${AuthErrorReason.SessionTokenExpired}-refresh-${refreshError}`;
case TokenVerificationErrorReason.TokenNotActiveYet:
return AuthErrorReason.SessionTokenNBF;
case TokenVerificationErrorReason.TokenIatInTheFuture:
return AuthErrorReason.SessionTokenIatInTheFuture;
default:
return AuthErrorReason.UnexpectedError;
}
};