-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathauthStatus.ts
More file actions
359 lines (323 loc) · 11.2 KB
/
Copy pathauthStatus.ts
File metadata and controls
359 lines (323 loc) · 11.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
import type { JwtPayload, PendingSessionOptions } from '@clerk/shared/types';
import { constants } from '../constants';
import type { TokenVerificationErrorReason } from '../errors';
import type { AuthenticateContext } from './authenticateContext';
import type {
AuthenticatedMachineObject,
InvalidTokenAuthObject,
SignedInAuthObject,
SignedOutAuthObject,
UnauthenticatedMachineObject,
} from './authObjects';
import {
authenticatedMachineObject,
invalidTokenAuthObject,
signedInAuthObject,
signedOutAuthObject,
unauthenticatedMachineObject,
} from './authObjects';
import type { MachineTokenType, SessionTokenType } from './tokenTypes';
import { TokenType } from './tokenTypes';
import type { MachineAuthType } from './types';
export const AuthStatus = {
SignedIn: 'signed-in',
SignedOut: 'signed-out',
Handshake: 'handshake',
} as const;
export type AuthStatus = (typeof AuthStatus)[keyof typeof AuthStatus];
type ToAuth<T extends TokenType | null, Authenticated extends boolean> = T extends null
? () => InvalidTokenAuthObject
: T extends SessionTokenType
? Authenticated extends true
? (opts?: PendingSessionOptions) => SignedInAuthObject
: () => SignedOutAuthObject
: Authenticated extends true
? () => AuthenticatedMachineObject<Exclude<T, SessionTokenType | null>>
: () => UnauthenticatedMachineObject<Exclude<T, SessionTokenType | null>>;
export type AuthenticatedState<T extends TokenType = SessionTokenType> = {
status: typeof AuthStatus.SignedIn;
reason: null;
message: null;
proxyUrl?: string;
publishableKey: string;
isSatellite: boolean;
domain: string;
signInUrl: string;
signUpUrl: string;
afterSignInUrl: string;
afterSignUpUrl: string;
/**
* @deprecated Use `isAuthenticated` instead.
*/
isSignedIn: true;
isAuthenticated: true;
headers: Headers;
token: string;
tokenType: T;
toAuth: ToAuth<T, true>;
};
export type UnauthenticatedState<T extends TokenType | null = SessionTokenType> = {
status: typeof AuthStatus.SignedOut;
reason: AuthReason;
message: string;
proxyUrl?: string;
publishableKey: string;
isSatellite: boolean;
domain: string;
signInUrl: string;
signUpUrl: string;
afterSignInUrl: string;
afterSignUpUrl: string;
/**
* @deprecated Use `isAuthenticated` instead.
*/
isSignedIn: false;
isAuthenticated: false;
tokenType: T;
headers: Headers;
token: null;
toAuth: ToAuth<T, false>;
};
export type HandshakeState = Omit<UnauthenticatedState<SessionTokenType>, 'status' | 'toAuth' | 'tokenType'> & {
tokenType: SessionTokenType;
status: typeof AuthStatus.Handshake;
headers: Headers;
toAuth: () => null;
};
/**
* @deprecated Use AuthenticatedState instead
*/
export type SignedInState = AuthenticatedState<SessionTokenType>;
/**
* @deprecated Use UnauthenticatedState instead
*/
export type SignedOutState = UnauthenticatedState<SessionTokenType>;
export const AuthErrorReason = {
ClientUATWithoutSessionToken: 'client-uat-but-no-session-token',
DevBrowserMissing: 'dev-browser-missing',
DevBrowserSync: 'dev-browser-sync',
PrimaryRespondsToSyncing: 'primary-responds-to-syncing',
PrimaryDomainCrossOriginSync: 'primary-domain-cross-origin-sync',
SatelliteCookieNeedsSyncing: 'satellite-needs-syncing',
SessionTokenAndUATMissing: 'session-token-and-uat-missing',
SessionTokenMissing: 'session-token-missing',
SessionTokenExpired: 'session-token-expired',
SessionTokenIATBeforeClientUAT: 'session-token-iat-before-client-uat',
SessionTokenNBF: 'session-token-nbf',
SessionTokenIatInTheFuture: 'session-token-iat-in-the-future',
SessionTokenWithoutClientUAT: 'session-token-but-no-client-uat',
ActiveOrganizationMismatch: 'active-organization-mismatch',
TokenTypeMismatch: 'token-type-mismatch',
MachineTokenRateLimit: 'machine-token-rate-limit',
UnexpectedError: 'unexpected-error',
} as const;
export type AuthErrorReason = (typeof AuthErrorReason)[keyof typeof AuthErrorReason];
export type AuthReason = AuthErrorReason | TokenVerificationErrorReason;
export type RequestState<T extends TokenType | null = SessionTokenType> =
| AuthenticatedState<T extends null ? never : T>
| UnauthenticatedState<T>
| (T extends SessionTokenType ? HandshakeState : never);
type BaseSignedInParams = {
authenticateContext: AuthenticateContext;
headers?: Headers;
token: string;
tokenType: TokenType;
};
type SignedInParams =
| (BaseSignedInParams & { tokenType: SessionTokenType; sessionClaims: JwtPayload })
| (BaseSignedInParams & { tokenType: MachineTokenType; machineData: MachineAuthType });
export function signedIn<T extends TokenType>(params: SignedInParams & { tokenType: T }): AuthenticatedState<T> {
const { authenticateContext, headers = new Headers(), token } = params;
const toAuth = (({ treatPendingAsSignedOut = true } = {}) => {
if (params.tokenType === TokenType.SessionToken) {
const { sessionClaims } = params as { sessionClaims: JwtPayload };
const authObject = signedInAuthObject(authenticateContext, token, sessionClaims);
if (treatPendingAsSignedOut && authObject.sessionStatus === 'pending') {
return signedOutAuthObject(undefined, authObject.sessionStatus);
}
return authObject;
}
const { machineData } = params as { machineData: MachineAuthType };
return authenticatedMachineObject(params.tokenType, token, machineData, authenticateContext);
}) as ToAuth<T, true>;
return {
status: AuthStatus.SignedIn,
reason: null,
message: null,
proxyUrl: authenticateContext.proxyUrl || '',
publishableKey: authenticateContext.publishableKey || '',
isSatellite: authenticateContext.isSatellite || false,
domain: authenticateContext.domain || '',
signInUrl: authenticateContext.signInUrl || '',
signUpUrl: authenticateContext.signUpUrl || '',
afterSignInUrl: authenticateContext.afterSignInUrl || '',
afterSignUpUrl: authenticateContext.afterSignUpUrl || '',
isSignedIn: true,
isAuthenticated: true,
tokenType: params.tokenType,
toAuth,
headers,
token,
};
}
type SignedOutParams = Omit<BaseSignedInParams, 'token'> & {
reason: AuthReason;
message?: string;
};
export function signedOut<T extends TokenType>(params: SignedOutParams & { tokenType: T }): UnauthenticatedState<T> {
const { authenticateContext, headers = new Headers(), reason, message = '', tokenType } = params;
const toAuth = (() => {
if (tokenType === TokenType.SessionToken) {
return signedOutAuthObject({ ...authenticateContext, status: AuthStatus.SignedOut, reason, message });
}
return unauthenticatedMachineObject(tokenType, { reason, message, headers });
}) as ToAuth<T, false>;
return withDebugHeaders({
status: AuthStatus.SignedOut,
reason,
message,
proxyUrl: authenticateContext.proxyUrl || '',
publishableKey: authenticateContext.publishableKey || '',
isSatellite: authenticateContext.isSatellite || false,
domain: authenticateContext.domain || '',
signInUrl: authenticateContext.signInUrl || '',
signUpUrl: authenticateContext.signUpUrl || '',
afterSignInUrl: authenticateContext.afterSignInUrl || '',
afterSignUpUrl: authenticateContext.afterSignUpUrl || '',
isSignedIn: false,
isAuthenticated: false,
tokenType,
toAuth,
headers,
token: null,
});
}
export function handshake(
authenticateContext: AuthenticateContext,
reason: AuthReason,
message = '',
headers: Headers,
): HandshakeState {
return withDebugHeaders({
status: AuthStatus.Handshake,
reason,
message,
publishableKey: authenticateContext.publishableKey || '',
isSatellite: authenticateContext.isSatellite || false,
domain: authenticateContext.domain || '',
proxyUrl: authenticateContext.proxyUrl || '',
signInUrl: authenticateContext.signInUrl || '',
signUpUrl: authenticateContext.signUpUrl || '',
afterSignInUrl: authenticateContext.afterSignInUrl || '',
afterSignUpUrl: authenticateContext.afterSignUpUrl || '',
isSignedIn: false,
isAuthenticated: false,
tokenType: TokenType.SessionToken,
toAuth: () => null,
headers,
token: null,
});
}
export function signedOutInvalidToken(): UnauthenticatedState<null> {
const authObject = invalidTokenAuthObject();
return withDebugHeaders({
status: AuthStatus.SignedOut,
reason: AuthErrorReason.TokenTypeMismatch,
message: '',
proxyUrl: '',
publishableKey: '',
isSatellite: false,
domain: '',
signInUrl: '',
signUpUrl: '',
afterSignInUrl: '',
afterSignUpUrl: '',
isSignedIn: false,
isAuthenticated: false,
tokenType: null,
toAuth: () => authObject,
headers: new Headers(),
token: null,
});
}
type BootstrapSignedOutParams = {
signInUrl?: string;
signUpUrl?: string;
isSatellite?: boolean;
domain?: string;
proxyUrl?: string;
reason?: AuthReason;
message?: string;
headers?: Headers;
};
/**
* Returns a synthetic `UnauthenticatedState` without requiring a publishable key or an
* `AuthenticateContext`. Intended for framework integrations that need to run
* authorization logic for a request that arrived before real Clerk keys are available
* (e.g. the Next.js keyless bootstrap window). The returned state has
* `status: 'signed-out'` and `toAuth()` returns a standard signed-out session auth object.
*
* `signInUrl` / `signUpUrl` are carried through so that `redirectToSignIn` /
* `redirectToSignUp` can resolve to the application's own routes during bootstrap.
* `isSatellite` / `domain` / `proxyUrl` are carried through so that cross-origin
* satellite redirects produced by `createRedirect` include the `__clerk_status=needs-sync`
* marker required for the return-trip handshake.
*/
export function createBootstrapSignedOutState({
signInUrl = '',
signUpUrl = '',
isSatellite = false,
domain = '',
proxyUrl = '',
reason = AuthErrorReason.SessionTokenAndUATMissing,
message = '',
headers = new Headers(),
}: BootstrapSignedOutParams = {}): UnauthenticatedState<SessionTokenType> {
return withDebugHeaders({
status: AuthStatus.SignedOut,
reason,
message,
proxyUrl,
publishableKey: '',
isSatellite,
domain,
signInUrl,
signUpUrl,
afterSignInUrl: '',
afterSignUpUrl: '',
isSignedIn: false,
isAuthenticated: false,
tokenType: TokenType.SessionToken,
toAuth: () => signedOutAuthObject({ status: AuthStatus.SignedOut, reason, message }),
headers,
token: null,
});
}
const withDebugHeaders = <T extends { headers: Headers; message?: string; reason?: AuthReason; status?: AuthStatus }>(
requestState: T,
): T => {
const headers = new Headers(requestState.headers || {});
if (requestState.message) {
try {
headers.set(constants.Headers.AuthMessage, requestState.message);
} catch {
// headers.set can throw if unicode strings are passed to it. In this case, simply do nothing
}
}
if (requestState.reason) {
try {
headers.set(constants.Headers.AuthReason, requestState.reason);
} catch {
/* empty */
}
}
if (requestState.status) {
try {
headers.set(constants.Headers.AuthStatus, requestState.status);
} catch {
/* empty */
}
}
requestState.headers = headers;
return requestState;
};