-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathSession.ts
More file actions
606 lines (528 loc) · 21.2 KB
/
Session.ts
File metadata and controls
606 lines (528 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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
import { createCheckAuthorization } from '@clerk/shared/authorization';
import { isBrowserOnline, isValidBrowserOnline } from '@clerk/shared/browser';
import {
ClerkOfflineError,
ClerkRuntimeError,
ClerkWebAuthnError,
is4xxError,
is429Error,
MissingExpiredTokenError,
} from '@clerk/shared/error';
import {
convertJSONToPublicKeyRequestOptions,
serializePublicKeyCredentialAssertion,
webAuthnGetCredential as webAuthnGetCredentialOnWindow,
} from '@clerk/shared/internal/clerk-js/passkeys';
import { retry } from '@clerk/shared/retry';
import type {
ActClaim,
AgentActClaim,
CheckAuthorization,
ClientResource,
EmailCodeConfig,
EnterpriseSSOConfig,
GetToken,
GetTokenOptions,
PhoneCodeConfig,
SessionJSON,
SessionJSONSnapshot,
SessionResource,
SessionStatus,
SessionTask,
SessionVerificationJSON,
SessionVerificationResource,
SessionVerifyAttemptFirstFactorParams,
SessionVerifyAttemptSecondFactorParams,
SessionVerifyCreateParams,
SessionVerifyPrepareFirstFactorParams,
SessionVerifyPrepareSecondFactorParams,
TokenResource,
UserResource,
} from '@clerk/shared/types';
import { isWebAuthnSupported as isWebAuthnSupportedOnWindow } from '@clerk/shared/webauthn';
import { unixEpochToDate } from '@/utils/date';
import { debugLogger } from '@/utils/debug';
import { TokenId } from '@/utils/tokenId';
import { clerkInvalidStrategy, clerkMissingWebAuthnPublicKeyOptions } from '../errors';
import { eventBus, events } from '../events';
import type { FapiResponseJSON } from '../fapiClient';
import { SessionTokenCache } from '../tokenCache';
import { BaseResource, getClientResourceFromPayload, PublicUserData, Token, User } from './internal';
import { SessionVerification } from './SessionVerification';
export class Session extends BaseResource implements SessionResource {
pathRoot = '/client/sessions';
/**
* Tracks token IDs with in-flight background refresh requests.
* Prevents multiple concurrent background refreshes for the same token.
*/
static #backgroundRefreshInProgress = new Set<string>();
id!: string;
status!: SessionStatus;
lastActiveAt!: Date;
lastActiveToken!: TokenResource | null;
lastActiveOrganizationId!: string | null;
actor!: ActClaim | null;
agent!: AgentActClaim | null;
user!: UserResource | null;
publicUserData!: PublicUserData;
factorVerificationAge: [number, number] | null = null;
tasks: Array<SessionTask> | null = null;
expireAt!: Date;
abandonAt!: Date;
createdAt!: Date;
updatedAt!: Date;
static isSessionResource(resource: unknown): resource is Session {
return !!resource && resource instanceof Session;
}
constructor(data: SessionJSON | SessionJSONSnapshot) {
super();
this.fromJSON(data);
this.#hydrateCache(this.lastActiveToken);
}
end = (): Promise<SessionResource> => {
SessionTokenCache.clear();
return this._basePost({
action: 'end',
});
};
remove = (): Promise<SessionResource> => {
SessionTokenCache.clear();
return this._basePost({
action: 'remove',
});
};
private _touchPost = async (
{ skipUpdateClient }: { skipUpdateClient: boolean } = { skipUpdateClient: false },
): Promise<FapiResponseJSON<SessionJSON> | null> => {
const json = await BaseResource._fetch<SessionJSON>(
{
method: 'POST',
path: this.path('touch'),
// any is how we type the body in the BaseMutateParams as well
body: { active_organization_id: this.lastActiveOrganizationId } as any,
},
{ skipUpdateClient },
);
// Update session in-place from response (same as BaseResource._baseMutate)
this.fromJSON((json?.response || json) as SessionJSON);
return json;
};
touch = async (): Promise<SessionResource> => {
await this._touchPost();
// _touchPost() will have updated `this` in-place
// The post has potentially changed the session state, and so we need to ensure we emit the updated token that comes back in the response. This avoids potential issues where the session cookie is out of sync with the current session state.
if (this.lastActiveToken) {
eventBus.emit(events.TokenUpdate, { token: this.lastActiveToken });
}
return this;
};
/**
* Internal method to touch the session without updating the client or explicitly emitting the TokenUpdate event.
*
* Returns the piggybacked client resource if it exists, otherwise undefined.
*
* The caller is responsible for calling updateClient(result), which internally also emits TokenUpdate.
* If updateClient() is not called, the server state and client state will be out of sync.
*
* @internal
*/
__internal_touch = async (): Promise<ClientResource | undefined> => {
const json = await this._touchPost({ skipUpdateClient: true });
return getClientResourceFromPayload(json);
};
clearCache = (): void => {
return SessionTokenCache.clear();
};
getToken: GetToken = async (options?: GetTokenOptions): Promise<string | null> => {
// Retry on transient failures (5xx, network errors, 429 rate limits).
// Do not retry on deterministic client errors (4xx) — they won't resolve on their own.
// For offline state, we use shorter retries (~15s total) before throwing ClerkOfflineError.
// For other errors, we retry up to 8 times over ~3 minutes.
try {
const result = await retry(() => this._getToken(options), {
factor: 1.55,
initialDelay: 3 * 1000,
maxDelayBetweenRetries: 50 * 1_000,
jitter: false,
shouldRetry: (error, iterationsCount) => {
if (is4xxError(error) && !is429Error(error)) {
return false;
}
if (!isValidBrowserOnline()) {
return iterationsCount <= 3;
}
return iterationsCount <= 8;
},
});
// If we're offline and got a null/empty result, this is likely due to
// BaseResource._baseFetch returning null when offline (silent failure mode).
// Throw ClerkOfflineError to make the offline state explicit.
if (!result && !isValidBrowserOnline()) {
throw new ClerkOfflineError('Network request failed while offline. The browser appears to be disconnected.');
}
return result;
} catch (error) {
// If the browser is offline after retries, throw ClerkOfflineError
if (!isValidBrowserOnline()) {
throw new ClerkOfflineError('Network request failed while offline. The browser appears to be disconnected.');
}
throw error;
}
};
checkAuthorization: CheckAuthorization = params => {
const orgMemberships = this.user?.organizationMemberships || [];
const activeMembership = orgMemberships.find(mem => mem.organization.id === this.lastActiveOrganizationId);
return createCheckAuthorization({
userId: this.user?.id,
factorVerificationAge: this.factorVerificationAge,
orgId: activeMembership?.id,
orgRole: activeMembership?.role,
orgPermissions: activeMembership?.permissions,
features: (this.lastActiveToken?.jwt?.claims.fea as string) || '',
plans: (this.lastActiveToken?.jwt?.claims.pla as string) || '',
})(params);
};
#hydrateCache = (token: TokenResource | null) => {
if (token) {
const tokenId = this.#getCacheId();
// Dispatch tokenUpdate for __session tokens with the session's active organization ID
const shouldDispatchTokenUpdate = true;
SessionTokenCache.set({
tokenId,
tokenResolver: Promise.resolve(token),
onRefresh: () =>
this.#refreshTokenInBackground(undefined, this.lastActiveOrganizationId, tokenId, shouldDispatchTokenUpdate),
});
}
};
// If it's a session token, retrieve it with their session id, otherwise it's a jwt template token
// and retrieve it using the session id concatenated with the jwt template name.
// e.g. session id is 'sess_abc12345' and jwt template name is 'haris'
// The session token ID will be 'sess_abc12345' and the jwt template token ID will be 'sess_abc12345-haris'
#getCacheId(template?: string, organizationId?: string | null) {
const resolvedOrganizationId =
typeof organizationId === 'undefined' ? this.lastActiveOrganizationId : organizationId;
return TokenId.build(this.id, template, resolvedOrganizationId);
}
startVerification = async ({ level }: SessionVerifyCreateParams): Promise<SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify`,
body: {
level,
} as any,
})
)?.response as unknown as SessionVerificationJSON;
return new SessionVerification(json);
};
prepareFirstFactorVerification = async (
factor: SessionVerifyPrepareFirstFactorParams,
): Promise<SessionVerificationResource> => {
let config;
switch (factor.strategy) {
case 'email_code':
config = { emailAddressId: factor.emailAddressId } as EmailCodeConfig;
break;
case 'phone_code':
config = {
phoneNumberId: factor.phoneNumberId,
default: factor.default,
} as PhoneCodeConfig;
break;
case 'passkey':
config = {};
break;
case 'enterprise_sso':
config = {
emailAddressId: factor.emailAddressId,
enterpriseConnectionId: factor.enterpriseConnectionId,
redirectUrl: factor.redirectUrl,
} as EnterpriseSSOConfig;
break;
default:
clerkInvalidStrategy('Session.prepareFirstFactorVerification', (factor as any).strategy);
}
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/prepare_first_factor`,
body: {
...config,
strategy: factor.strategy,
} as any,
})
)?.response as unknown as SessionVerificationJSON;
return new SessionVerification(json);
};
attemptFirstFactorVerification = async (
attemptFactor: SessionVerifyAttemptFirstFactorParams,
): Promise<SessionVerificationResource> => {
let config;
switch (attemptFactor.strategy) {
case 'passkey': {
config = {
publicKeyCredential: JSON.stringify(serializePublicKeyCredentialAssertion(attemptFactor.publicKeyCredential)),
};
break;
}
default:
config = { ...attemptFactor };
}
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/attempt_first_factor`,
body: { ...config, strategy: attemptFactor.strategy } as any,
})
)?.response as unknown as SessionVerificationJSON;
return new SessionVerification(json);
};
verifyWithPasskey = async (): Promise<SessionVerificationResource> => {
const prepareResponse = await this.prepareFirstFactorVerification({ strategy: 'passkey' });
const { nonce = null } = prepareResponse.firstFactorVerification;
/**
* The UI should always prevent from this method being called if WebAuthn is not supported.
* As a precaution we need to check if WebAuthn is supported.
*/
const isWebAuthnSupported = Session.clerk.__internal_isWebAuthnSupported || isWebAuthnSupportedOnWindow;
const webAuthnGetCredential = Session.clerk.__internal_getPublicCredentials || webAuthnGetCredentialOnWindow;
if (!isWebAuthnSupported()) {
throw new ClerkWebAuthnError('Passkeys are not supported', {
code: 'passkey_not_supported',
});
}
const publicKeyOptions = nonce ? convertJSONToPublicKeyRequestOptions(JSON.parse(nonce)) : null;
if (!publicKeyOptions) {
clerkMissingWebAuthnPublicKeyOptions('get');
}
const { publicKeyCredential, error } = await webAuthnGetCredential({
publicKeyOptions,
conditionalUI: false,
});
if (!publicKeyCredential) {
throw error;
}
return this.attemptFirstFactorVerification({
strategy: 'passkey',
publicKeyCredential,
});
};
prepareSecondFactorVerification = async (
params: SessionVerifyPrepareSecondFactorParams,
): Promise<SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/prepare_second_factor`,
body: params as any,
})
)?.response as unknown as SessionVerificationJSON;
return new SessionVerification(json);
};
attemptSecondFactorVerification = async (
attemptFactor: SessionVerifyAttemptSecondFactorParams,
): Promise<SessionVerificationResource> => {
const json = (
await BaseResource._fetch({
method: 'POST',
path: `/client/sessions/${this.id}/verify/attempt_second_factor`,
body: attemptFactor as any,
})
)?.response as unknown as SessionVerificationJSON;
return new SessionVerification(json);
};
protected fromJSON(data: SessionJSON | SessionJSONSnapshot | null): this {
if (!data) {
return this;
}
this.id = data.id;
this.status = data.status;
this.expireAt = unixEpochToDate(data.expire_at);
this.abandonAt = unixEpochToDate(data.abandon_at);
this.factorVerificationAge = data.factor_verification_age;
this.lastActiveAt = unixEpochToDate(data.last_active_at || undefined);
this.lastActiveOrganizationId = data.last_active_organization_id;
this.actor = data.actor || null;
this.agent = data.actor?.type === 'agent' ? (data.actor as AgentActClaim) : null;
this.createdAt = unixEpochToDate(data.created_at);
this.updatedAt = unixEpochToDate(data.updated_at);
this.user = new User(data.user);
this.tasks = data.tasks || null;
if (data.public_user_data) {
this.publicUserData = new PublicUserData(data.public_user_data);
}
this.lastActiveToken = data.last_active_token ? new Token(data.last_active_token) : null;
return this;
}
public __internal_toSnapshot(): SessionJSONSnapshot {
return {
object: 'session',
id: this.id,
status: this.status,
expire_at: this.expireAt.getTime(),
abandon_at: this.abandonAt.getTime(),
factor_verification_age: this.factorVerificationAge,
last_active_at: this.lastActiveAt.getTime(),
last_active_organization_id: this.lastActiveOrganizationId,
actor: this.actor,
tasks: this.tasks,
user: this.user?.__internal_toSnapshot() || null,
public_user_data: this.publicUserData.__internal_toSnapshot(),
last_active_token: this.lastActiveToken?.__internal_toSnapshot() || null,
created_at: this.createdAt.getTime(),
updated_at: this.updatedAt.getTime(),
};
}
private async _getToken(options?: GetTokenOptions): Promise<string | null> {
if (!this.user) {
return null;
}
const { skipCache = false, template } = options || {};
// If no organization ID is provided, default to the selected organization in memory
// Note: this explicitly allows passing `null` or `""`, which should select the personal workspace.
const organizationId =
typeof options?.organizationId === 'undefined' ? this.lastActiveOrganizationId : options?.organizationId;
const tokenId = this.#getCacheId(template, organizationId);
const cacheResult = skipCache ? undefined : SessionTokenCache.get({ tokenId });
// Dispatch tokenUpdate only for __session tokens with the session's active organization ID, and not JWT templates
const shouldDispatchTokenUpdate = !template && organizationId === this.lastActiveOrganizationId;
let result: string | null;
if (cacheResult) {
// Proactive refresh is handled by timers scheduled in the cache
// Prefer synchronous read to avoid microtask overhead when token is already resolved
const cachedToken = cacheResult.entry.resolvedToken ?? (await cacheResult.entry.tokenResolver);
// Only emit token updates when we have an actual token — emitting with an empty
// token causes AuthCookieService to remove the __session cookie (looks like sign-out).
if (shouldDispatchTokenUpdate && cachedToken.getRawString()) {
eventBus.emit(events.TokenUpdate, { token: cachedToken });
}
result = cachedToken.getRawString() || null;
} else if (!isBrowserOnline()) {
throw new ClerkRuntimeError('Browser is offline, skipping token fetch', { code: 'network_error' });
} else {
result = await this.#fetchToken(template, organizationId, tokenId, shouldDispatchTokenUpdate, skipCache);
}
// Throw when offline and no token so retry() in getToken() can fire.
// Without this, _getToken returns null (success) and retry() never calls shouldRetry.
if (result === null && !isValidBrowserOnline()) {
throw new ClerkRuntimeError('Network request failed while offline', { code: 'network_error' });
}
return result;
}
#createTokenResolver(
template: string | undefined,
organizationId: string | undefined | null,
skipCache: boolean,
): Promise<TokenResource> {
const path = template ? `${this.path()}/tokens/${template}` : `${this.path()}/tokens`;
// TODO: update template endpoint to accept organizationId
const params: Record<string, string | null> = template
? {}
: {
organizationId: organizationId ?? null,
...(this.lastActiveToken ? { token: this.lastActiveToken.getRawString() } : {}),
};
const lastActiveToken = this.lastActiveToken?.getRawString();
const tokenResolver = Token.create(
path,
params,
skipCache ? { debug: 'skip_cache', force_origin: 'true' } : undefined,
).catch(e => {
if (MissingExpiredTokenError.is(e) && lastActiveToken) {
return Token.create(path, { ...params }, { expired_token: lastActiveToken });
}
throw e;
});
return tokenResolver;
}
#dispatchTokenEvents(token: TokenResource, shouldDispatch: boolean): void {
if (!shouldDispatch) {
return;
}
// Never dispatch empty tokens — this would cause AuthCookieService to remove
// the __session cookie even though the user is still authenticated.
if (!token.getRawString()) {
return;
}
eventBus.emit(events.TokenUpdate, { token });
if (token.jwt) {
this.lastActiveToken = token;
eventBus.emit(events.SessionTokenResolved, null);
}
}
#fetchToken(
template: string | undefined,
organizationId: string | undefined | null,
tokenId: string,
shouldDispatchTokenUpdate: boolean,
skipCache: boolean,
): Promise<string | null> {
debugLogger.info('Fetching new token from API', { organizationId, template, tokenId }, 'session');
const tokenResolver = this.#createTokenResolver(template, organizationId, skipCache);
SessionTokenCache.set({
tokenId,
tokenResolver,
onRefresh: () => this.#refreshTokenInBackground(template, organizationId, tokenId, shouldDispatchTokenUpdate),
});
return tokenResolver.then(token => {
const rawString = token.getRawString();
if (!rawString) {
// Throw so retry logic in getToken() can handle it,
// rather than silently returning null (which callers interpret as "signed out").
throw new ClerkRuntimeError('Token fetch returned empty response', { code: 'network_error' });
}
this.#dispatchTokenEvents(token, shouldDispatchTokenUpdate);
return rawString;
});
}
/**
* Triggers a background token refresh without caching the pending promise.
* This allows concurrent getToken() calls to continue returning the stale cached token
* while the refresh is in progress. The cache is only updated after the refresh succeeds.
*
* Uses a static Set to prevent multiple concurrent background refreshes for the same token.
*/
#refreshTokenInBackground(
template: string | undefined,
organizationId: string | undefined | null,
tokenId: string,
shouldDispatchTokenUpdate: boolean,
): void {
// Prevent multiple concurrent background refreshes for the same token
if (Session.#backgroundRefreshInProgress.has(tokenId)) {
return;
}
Session.#backgroundRefreshInProgress.add(tokenId);
const tokenResolver = this.#createTokenResolver(template, organizationId, false);
// Don't cache the promise immediately - only update cache on success
// This allows concurrent calls to continue using the stale token
tokenResolver
.then(token => {
// Never cache or dispatch empty tokens — preserve the stale-but-valid
// token in cache instead of replacing it with an empty one.
if (!token.getRawString()) {
return;
}
// Cache the resolved token for future calls
// Re-register onRefresh to handle the next refresh cycle when this token approaches expiration
SessionTokenCache.set({
tokenId,
tokenResolver: Promise.resolve(token),
onRefresh: () => this.#refreshTokenInBackground(template, organizationId, tokenId, shouldDispatchTokenUpdate),
});
this.#dispatchTokenEvents(token, shouldDispatchTokenUpdate);
})
.catch(error => {
// Log but don't propagate - callers already have stale token
debugLogger.warn('Background token refresh failed', { error, tokenId }, 'session');
})
.finally(() => {
Session.#backgroundRefreshInProgress.delete(tokenId);
});
}
get currentTask() {
const [task] = this.tasks ?? [];
return task;
}
}