Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/token-cache-iat-core2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Fix token cache stale-while-revalidate timing to use the JWT issued-at time, keeping refresh thresholds accurate when tokens are cached after issuance.
4 changes: 2 additions & 2 deletions packages/clerk-js/src/core/__tests__/tokenCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ describe('SessionTokenCache', () => {

it('removes token when it expires within the leeway threshold', async () => {
const nowSeconds = Math.floor(Date.now() / 1000);
const iat = nowSeconds;
const iat = nowSeconds - 13;
const exp = iat + 20;
const soonJwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.${btoa(JSON.stringify({ iat, exp }))}.signature`;

Expand All @@ -419,7 +419,7 @@ describe('SessionTokenCache', () => {
jwt: { claims: { exp, iat } },
} as any);

SessionTokenCache.set({ createdAt: nowSeconds - 13, tokenId: 'soon_expired_token', tokenResolver });
SessionTokenCache.set({ createdAt: nowSeconds, tokenId: 'soon_expired_token', tokenResolver });

await tokenResolver;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ describe('Session', () => {
beforeEach(() => {
// Mock Date.now() to make the test tokens appear valid
// mockJwt has iat: 1666648250, exp: 1666648310
// Set current time to 1666648260 (10 seconds after iat, 50 seconds before exp)
// Set current time to iat so token appears freshly issued (60 seconds before exp)
vi.useFakeTimers();
vi.setSystemTime(new Date(1666648260 * 1000));
vi.setSystemTime(new Date(1666648250 * 1000));
});

afterEach(() => {
Expand Down
1 change: 1 addition & 0 deletions packages/clerk-js/src/core/tokenCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ const MemoryTokenCache = (prefix = KEY_PREFIX): TokenCache => {
const issuedAt = claims.iat;
const expiresIn: Seconds = expiresAt - issuedAt;

value.createdAt = issuedAt;
value.expiresIn = expiresIn;

const timeoutId = setTimeout(deleteKey, expiresIn * 1000);
Expand Down