Skip to content

Commit d525c64

Browse files
committed
Measure SessionTokenCache age on the device clock.
createdAt was taken from JWT iat, so a client whose clock ran behind kept serving session tokens after they had expired on the server.
1 parent 141916c commit d525c64

3 files changed

Lines changed: 38 additions & 12 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/clerk-js': patch
3+
---
4+
5+
SessionTokenCache measures token age on the device clock, so a slow client clock no longer keeps serving a session token after it expired on the server.

‎packages/clerk-js/src/core/__tests__/tokenCache.test.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ describe('SessionTokenCache', () => {
277277
await broadcastListener(olderEvent);
278278
const resultAfterOlder = SessionTokenCache.get({ tokenId: 'session_123' });
279279
expect(resultAfterOlder).toBeDefined();
280-
expect(resultAfterOlder?.entry.createdAt).toBe(1666648190);
280+
expect(resultAfterOlder?.entry.createdAt).toBe(1666648260);
281281

282282
const newerEvent: MessageEvent<SessionTokenEvent> = {
283283
data: {
@@ -294,7 +294,7 @@ describe('SessionTokenCache', () => {
294294

295295
const resultAfterNewer = SessionTokenCache.get({ tokenId: 'session_123' });
296296
expect(resultAfterNewer).toBeDefined();
297-
expect(resultAfterNewer?.entry.createdAt).toBe(1666648250);
297+
expect(resultAfterNewer?.entry.createdAt).toBe(1666648260);
298298
});
299299

300300
it('ignores a broadcast staler than the reconciled resolvedToken even when the resolver is staler', async () => {
@@ -555,9 +555,8 @@ describe('SessionTokenCache', () => {
555555

556556
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
557557

558-
// createdAt reflects high's iat (1666648250), not low's (1666648190): the slot's TTL is stamped
559-
// from the published winner. A slot stamped with low's earlier iat would already be evicted at
560-
// this point; one stamped with high's iat is still comfortably within its 120s TTL.
558+
// TTL is the winner's lifetime (exp - iat) measured from cache time on the
559+
// device clock, so 50s later the 120s token is still served.
561560
vi.advanceTimersByTime(50 * 1000);
562561
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
563562
});
@@ -714,6 +713,29 @@ describe('SessionTokenCache', () => {
714713
expect(result?.entry.tokenId).toBe('soon_expired_token');
715714
});
716715

716+
it('does not serve a server-expired token when the device clock is behind', async () => {
717+
const serverNow = 1_700_000_000;
718+
const deviceLag = 40;
719+
vi.setSystemTime(new Date((serverNow - deviceLag) * 1000));
720+
721+
const iat = serverNow;
722+
const exp = serverNow + 60;
723+
const jwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ iat, exp }))}.signature`;
724+
const tokenResolver = Promise.resolve({
725+
getRawString: () => jwt,
726+
jwt: { claims: { exp, iat } },
727+
} as any);
728+
729+
SessionTokenCache.set({ tokenId: 'skew_token', tokenResolver });
730+
await tokenResolver;
731+
732+
vi.advanceTimersByTime(50 * 1000);
733+
expect(SessionTokenCache.get({ tokenId: 'skew_token' })).toBeDefined();
734+
735+
vi.advanceTimersByTime(20 * 1000);
736+
expect(SessionTokenCache.get({ tokenId: 'skew_token' })).toBeUndefined();
737+
});
738+
717739
it('returns token when expiresAt is undefined (promise not yet resolved)', () => {
718740
// Create a promise that never resolves
719741
const pendingTokenResolver = new Promise<any>(() => {});

‎packages/clerk-js/src/core/tokenCache.ts‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,6 @@ const MemoryTokenCache = (prefix?: string): TokenCache => {
292292

293293
setInternal(
294294
{
295-
createdAt: iat,
296295
tokenId: data.tokenId,
297296
tokenResolver: Promise.resolve(token),
298297
},
@@ -328,6 +327,7 @@ const MemoryTokenCache = (prefix?: string): TokenCache => {
328327

329328
const nowSeconds = Math.floor(Date.now() / 1000);
330329
const createdAt = entry.createdAt ?? nowSeconds;
330+
entry.createdAt = createdAt;
331331
const value: TokenCacheValue = { createdAt, entry, expiresIn: undefined };
332332

333333
// Chain the freshest known token across replacements. This never touches
@@ -402,13 +402,12 @@ const MemoryTokenCache = (prefix?: string): TokenCache => {
402402
const expiresAt = winnerClaims.exp;
403403
const issuedAt = winnerClaims.iat;
404404
const expiresIn: Seconds = expiresAt - issuedAt;
405-
// Timers run relative to now, while createdAt/expiresIn describe the token's
406-
// real validity window for get(). An aged winner (alive for part of its
407-
// lifetime already) must be evicted and refreshed by its real expiry, not a
408-
// full lifetime from now.
409-
const remainingTtl: Seconds = expiresAt - Math.floor(Date.now() / 1000);
405+
// Measure elapsed time on the device clock from when we cached the
406+
// entry (`live.createdAt`), not from JWT `iat`. Mixing server `iat`
407+
// with `Date.now()` serves expired tokens when the device runs behind.
408+
const nowSeconds = Math.floor(Date.now() / 1000);
409+
const remainingTtl: Seconds = expiresIn - (nowSeconds - live.createdAt);
410410

411-
live.createdAt = issuedAt;
412411
live.expiresIn = expiresIn;
413412

414413
if (remainingTtl <= 0) {

0 commit comments

Comments
 (0)