-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathtokenCache.ts
More file actions
486 lines (419 loc) · 14.8 KB
/
tokenCache.ts
File metadata and controls
486 lines (419 loc) · 14.8 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
import type { TokenResource } from '@clerk/shared/types';
import { debugLogger } from '@/utils/debug';
import { TokenId } from '@/utils/tokenId';
import { POLLER_INTERVAL_IN_MS } from './auth/SessionCookiePoller';
import { Token } from './resources/internal';
import { shouldRejectToken } from './tokenFreshness';
/**
* Identifies a cached token entry by tokenId and optional audience.
*/
interface TokenCacheKeyJSON {
audience?: string;
tokenId: string;
}
/**
* Cache entry containing token metadata and resolver.
* Extends TokenCacheKeyJSON with additional properties for expiration tracking and token retrieval.
*/
interface TokenCacheEntry extends TokenCacheKeyJSON {
/**
* Timestamp in seconds since UNIX epoch when the entry was created.
* Used for expiration and cleanup scheduling.
*/
createdAt?: Seconds;
/**
* Callback to refresh this token before it expires.
* Called by the proactive refresh timer to trigger background refresh.
* If not provided, no refresh timer will be scheduled (e.g., for broadcast-received tokens).
*/
onRefresh?: () => void;
/**
* The resolved token value for synchronous reads.
* Populated after tokenResolver resolves. Check this first to avoid microtask overhead.
*/
resolvedToken?: TokenResource;
/**
* Promise that resolves to the TokenResource.
* May be pending and should be awaited before accessing token data.
*/
tokenResolver: Promise<TokenResource>;
}
type Seconds = number;
/**
* Internal cache value containing the entry, expiration metadata, and timers.
*/
interface TokenCacheValue {
createdAt: Seconds;
entry: TokenCacheEntry;
expiresIn?: Seconds;
/** Timer for automatic cache cleanup when token expires */
timeoutId?: ReturnType<typeof setTimeout>;
/** Timer for proactive refresh before token enters leeway period */
refreshTimeoutId?: ReturnType<typeof setTimeout>;
}
/**
* Result from cache lookup containing the entry.
*/
export interface TokenCacheGetResult {
entry: TokenCacheEntry;
}
export interface TokenCache {
/**
* Removes all cached entries and clears associated timeouts.
* Side effects: Clears all scheduled expiration timers and empties the cache.
*/
clear(): void;
/**
* Closes the BroadcastChannel connection and releases resources.
* Side effects: Disconnects from multi-tab synchronization channel.
*/
close(): void;
/**
* Retrieves a cached token entry if it exists and is safe to use.
* Forces synchronous refresh if token has less than one poller interval remaining.
* Proactive refresh is handled by timers scheduled when tokens are cached.
*
* @param cacheKeyJSON - Object containing tokenId and optional audience to identify the cached entry
* @returns Result with entry, or undefined if token is missing/expired/too close to expiration
*/
get(cacheKeyJSON: TokenCacheKeyJSON): TokenCacheGetResult | undefined;
/**
* Stores a token entry in the cache and broadcasts to other tabs when the token resolves.
*
* @param entry - TokenCacheEntry containing tokenId, tokenResolver, and optional audience
* Side effects: Schedules automatic expiration cleanup, broadcasts to other tabs when token resolves
*/
set(entry: TokenCacheEntry): void;
/**
* Returns the current number of cached entries.
*
* @returns The count of entries currently stored in the cache
*/
size(): number;
}
const KEY_PREFIX = 'clerk';
const DELIMITER = '::';
/**
* Default seconds before token expiration to trigger background refresh.
* This threshold accounts for timer jitter, SafeLock contention (~5s), network latency,
* and tolerance for missed poller ticks.
*
* Users can customize this value:
* - Lower values (min: 5s) delay background refresh until closer to expiration
* - Higher values trigger earlier background refresh but may cause more frequent requests
*/
const BACKGROUND_REFRESH_THRESHOLD_IN_SECONDS = 15;
const BROADCAST = { broadcast: true };
const NO_BROADCAST = { broadcast: false };
/**
* Converts between cache key objects and string representations.
* Format: `prefix::tokenId::audience`
*/
export class TokenCacheKey {
/**
* Parses a cache key string into a TokenCacheKey instance.
*/
static fromKey(key: string): TokenCacheKey {
const [prefix, tokenId, audience = ''] = key.split(DELIMITER);
return new TokenCacheKey(prefix, { audience, tokenId });
}
constructor(
public prefix: string,
public data: TokenCacheKeyJSON,
) {
this.prefix = prefix;
this.data = data;
}
/**
* Converts the key to its string representation for Map storage.
*/
toKey(): string {
const { tokenId, audience } = this.data;
return [this.prefix, tokenId, audience || ''].join(DELIMITER);
}
}
/**
* Message format for BroadcastChannel token synchronization between tabs.
*/
interface SessionTokenEvent {
organizationId?: string | null;
sessionId: string;
template?: string;
tokenId: string;
tokenRaw: string;
traceId: string;
}
const generateTabId = (): string => {
return Math.random().toString(36).slice(2);
};
/**
* Creates an in-memory token cache with optional BroadcastChannel synchronization across tabs.
* Automatically manages token expiration and cleanup via scheduled timeouts.
* BroadcastChannel support is enabled whenever the environment provides it.
*/
const MemoryTokenCache = (prefix = KEY_PREFIX): TokenCache => {
const cache = new Map<string, TokenCacheValue>();
const tabId = generateTabId();
let broadcastChannel: BroadcastChannel | null = null;
const ensureBroadcastChannel = (): BroadcastChannel | null => {
if (broadcastChannel) {
return broadcastChannel;
}
if (typeof BroadcastChannel === 'undefined') {
return null;
}
broadcastChannel = new BroadcastChannel('clerk:session_token');
broadcastChannel.addEventListener('message', (e: MessageEvent<SessionTokenEvent>) => {
void handleBroadcastMessage(e);
});
return broadcastChannel;
};
ensureBroadcastChannel();
const clear = () => {
cache.forEach(value => {
if (value.timeoutId !== undefined) {
clearTimeout(value.timeoutId);
}
if (value.refreshTimeoutId !== undefined) {
clearTimeout(value.refreshTimeoutId);
}
});
cache.clear();
};
const get = (cacheKeyJSON: TokenCacheKeyJSON): TokenCacheGetResult | undefined => {
ensureBroadcastChannel();
const cacheKey = new TokenCacheKey(prefix, cacheKeyJSON);
const value = cache.get(cacheKey.toKey());
if (!value) {
return;
}
const nowSeconds = Math.floor(Date.now() / 1000);
const elapsed = nowSeconds - value.createdAt;
const remainingTtl = (value.expiresIn ?? Infinity) - elapsed;
// Token expired or dangerously close to expiration - force synchronous refresh
// Uses poller interval as threshold since the poller might not get to it in time
if (remainingTtl <= POLLER_INTERVAL_IN_MS / 1000) {
if (value.timeoutId !== undefined) {
clearTimeout(value.timeoutId);
}
if (value.refreshTimeoutId !== undefined) {
clearTimeout(value.refreshTimeoutId);
}
cache.delete(cacheKey.toKey());
return;
}
// Proactive refresh is handled by timers scheduled in setInternal()
return { entry: value.entry };
};
/**
* Processes token updates from other tabs via BroadcastChannel.
* Validates token ID, parses JWT, and updates cache if token is newer than existing entry.
*/
const handleBroadcastMessage = async ({ data }: MessageEvent<SessionTokenEvent>) => {
const expectedTokenId = TokenId.build(data.sessionId, data.template, data.organizationId);
if (data.tokenId !== expectedTokenId) {
debugLogger.warn(
'Ignoring token broadcast with mismatched tokenId',
{
expectedTokenId,
organizationId: data.organizationId,
receivedTokenId: data.tokenId,
tabId,
template: data.template,
traceId: data.traceId,
},
'tokenCache',
);
return;
}
let token: Token;
try {
token = new Token({ id: data.tokenId, jwt: data.tokenRaw, object: 'token' });
} catch (error) {
debugLogger.warn(
'Failed to parse token from broadcast, skipping cache update',
{ error, tabId, tokenId: data.tokenId, traceId: data.traceId },
'tokenCache',
);
return;
}
const iat = token.jwt?.claims?.iat;
const exp = token.jwt?.claims?.exp;
if (!iat || !exp) {
debugLogger.warn(
'Token missing iat/exp claim, skipping cache update',
{ tabId, tokenId: data.tokenId, traceId: data.traceId },
'tokenCache',
);
return;
}
try {
const result = get({ tokenId: data.tokenId });
if (result) {
const existingToken = await result.entry.tokenResolver;
if (shouldRejectToken(existingToken, token)) {
debugLogger.debug(
'Ignoring staler token broadcast',
{ tokenId: data.tokenId, traceId: data.traceId },
'tokenCache',
);
return;
}
}
} catch (error) {
debugLogger.warn(
'Existing entry compare failed; proceeding with broadcast update',
{ error, tabId, tokenId: data.tokenId, traceId: data.traceId },
'tokenCache',
);
}
debugLogger.info(
'Updating token cache from broadcast',
{
iat,
organizationId: data.organizationId,
tabId,
template: data.template,
tokenId: data.tokenId,
traceId: data.traceId,
},
'tokenCache',
);
setInternal(
{
createdAt: iat,
tokenId: data.tokenId,
tokenResolver: Promise.resolve(token),
},
NO_BROADCAST,
);
};
const set = (entry: TokenCacheEntry) => {
ensureBroadcastChannel();
setInternal(entry, BROADCAST);
};
/**
* Internal cache setter that stores an entry and schedules expiration cleanup.
* Resolves the token promise to extract expiration claims and set a deletion timeout.
*
* @param entry - The token cache entry to store
* @param options - Configuration for cache behavior; broadcast controls whether to notify other tabs
*/
const setInternal = (entry: TokenCacheEntry, options: { broadcast: boolean } = BROADCAST) => {
const cacheKey = new TokenCacheKey(prefix, {
audience: entry.audience,
tokenId: entry.tokenId,
});
const key = cacheKey.toKey();
const nowSeconds = Math.floor(Date.now() / 1000);
const createdAt = entry.createdAt ?? nowSeconds;
const value: TokenCacheValue = { createdAt, entry, expiresIn: undefined };
const deleteKey = () => {
const cachedValue = cache.get(key);
if (cachedValue === value) {
if (cachedValue.timeoutId !== undefined) {
clearTimeout(cachedValue.timeoutId);
}
if (cachedValue.refreshTimeoutId !== undefined) {
clearTimeout(cachedValue.refreshTimeoutId);
}
cache.delete(key);
}
};
entry.tokenResolver
.then(newToken => {
// Compare-and-swap: if another concurrent resolve already committed
// a fresher token for this key, don't overwrite it.
const currentValue = cache.get(key);
if (currentValue?.entry?.resolvedToken && newToken) {
if (shouldRejectToken(currentValue.entry.resolvedToken, newToken)) {
return;
}
}
// Store resolved token for synchronous reads
entry.resolvedToken = newToken;
const claims = newToken.jwt?.claims;
if (!claims || typeof claims.exp !== 'number' || typeof claims.iat !== 'number') {
return deleteKey();
}
const expiresAt = claims.exp;
const issuedAt = claims.iat;
const expiresIn: Seconds = expiresAt - issuedAt;
value.createdAt = issuedAt;
value.expiresIn = expiresIn;
const timeoutId = setTimeout(deleteKey, expiresIn * 1000);
value.timeoutId = timeoutId;
// Teach ClerkJS not to block the exit of the event loop when used in Node environments.
// More info at https://nodejs.org/api/timers.html#timeoutunref
if (typeof (timeoutId as any).unref === 'function') {
(timeoutId as any).unref();
}
// Schedule proactive refresh timer to fire before token enters leeway period
// This ensures new tokens are ready before the old one expires
// refreshLeadTime: 2s buffer before leeway starts. Token fetches typically complete in ~100ms,
// so 2s provides ample margin for the refresh to complete before the token enters the leeway period.
const refreshLeadTime = 2;
const minLeeway = POLLER_INTERVAL_IN_MS / 1000; // Minimum is poller interval (5s)
const leeway = Math.max(BACKGROUND_REFRESH_THRESHOLD_IN_SECONDS, minLeeway);
const refreshFireTime = expiresIn - leeway - refreshLeadTime;
if (refreshFireTime > 0 && entry.onRefresh) {
const refreshTimeoutId = setTimeout(() => {
entry.onRefresh?.();
}, refreshFireTime * 1000);
value.refreshTimeoutId = refreshTimeoutId;
if (typeof (refreshTimeoutId as any).unref === 'function') {
(refreshTimeoutId as any).unref();
}
}
const channel = broadcastChannel;
if (channel && options.broadcast) {
const tokenRaw = newToken.getRawString();
if (tokenRaw && claims.sid) {
const sessionId = claims.sid;
const organizationId = claims.org_id || (claims.o as any)?.id;
const template = TokenId.extractTemplate(entry.tokenId, sessionId, organizationId);
const expectedTokenId = TokenId.build(sessionId, template, organizationId);
if (entry.tokenId === expectedTokenId) {
const traceId = `bc_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
debugLogger.info(
'Broadcasting token update to other tabs',
{
organizationId,
sessionId,
tabId,
template,
tokenId: entry.tokenId,
traceId,
},
'tokenCache',
);
const message: SessionTokenEvent = {
organizationId,
sessionId,
template,
tokenId: entry.tokenId,
tokenRaw,
traceId,
};
channel.postMessage(message);
}
}
}
})
.catch(() => {
deleteKey();
});
cache.set(key, value);
};
const close = () => {
if (broadcastChannel) {
broadcastChannel.close();
broadcastChannel = null;
}
};
const size = () => {
return cache.size;
};
return { clear, close, get, set, size };
};
export const SessionTokenCache = MemoryTokenCache();