Skip to content

Commit 98d0fcc

Browse files
committed
fix(clerk-js): apply session tokens monotonically by oiat on a single tab
A stale edge-minted session token (older oiat header) could overwrite a fresher one on the same tab. The only freshness guard ran solely in the cross-tab broadcast receiver, so the __session cookie, Session.lastActiveToken, and the token cache each accepted whatever token arrived last, letting a slow or out-of-order edge read revert a newer token. Reuse pickFreshestJwt across all three stores: - tokenCache.setInternal keeps the live entry's resolvedToken monotonic regardless of which resolver owns the slot, carries the prior token and its expiry forward, and derives expiry/refresh timers from the winner. - Session.#fetchToken and #refreshTokenInBackground resolve to the freshest of the fetched token and the live cache entry, so coalesced waiters and the dispatch receive the winner; lastActiveToken never regresses to a strictly-staler token. - Session.fromJSON reconciles an incoming last_active_token against the active cache slot, never adopting a strictly-staler or wrong-org token nor polluting the slot getToken reads. - AuthCookieService.updateSessionCookie drops tokens for a different active session/org or strictly staler than the same-context cookie, failing open for tokens without oiat. Freshness is decided by oiat then iat; drops happen only when both tokens carry oiat and the incoming is strictly older, so a missing oiat or a different context always lets the token through.
1 parent 9e1d849 commit 98d0fcc

9 files changed

Lines changed: 1059 additions & 45 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+
Apply session tokens monotonically by origin-issued-at on a single tab, so a stale edge-minted token can no longer overwrite a fresher one in the `__session` cookie, the session's last active token, or the token cache.

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

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -819,6 +819,152 @@ describe('Clerk singleton', () => {
819819
);
820820
});
821821

822+
describe('updateSessionCookie monotonic backstop', () => {
823+
const sessionId = 'sess_active';
824+
825+
const createJwtWithOiat = (
826+
iat: number,
827+
oiat: number | undefined,
828+
opts: { sid?: string; org?: string; ttl?: number } = {},
829+
): string => {
830+
const { sid = sessionId, org, ttl = 60 } = opts;
831+
const header: Record<string, unknown> = { alg: 'HS256', typ: 'JWT' };
832+
if (oiat !== undefined) {
833+
header.oiat = oiat;
834+
}
835+
const payload: Record<string, unknown> = { sid, iat, exp: iat + ttl };
836+
if (org) {
837+
payload.org_id = org;
838+
}
839+
const b64 = (o: object) => btoa(JSON.stringify(o)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
840+
return `${b64(header)}.${b64(payload)}.test-signature`;
841+
};
842+
843+
const loadClerkWithSession = async () => {
844+
const mockSession = {
845+
id: sessionId,
846+
status: 'active',
847+
user: {},
848+
getToken: vi.fn(),
849+
lastActiveToken: { getRawString: () => mockJwt },
850+
};
851+
mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] }));
852+
const sut = new Clerk(productionPublishableKey);
853+
await sut.load();
854+
return sut;
855+
};
856+
857+
const emitToken = (raw: string | null) => {
858+
eventBus.emit(events.TokenUpdate, {
859+
token: raw === null ? null : ({ jwt: {}, getRawString: () => raw } as any),
860+
});
861+
};
862+
863+
it('drops a strictly-staler same-context token and keeps the fresher cookie', async () => {
864+
await loadClerkWithSession();
865+
866+
const fresh = createJwtWithOiat(1000, 200);
867+
emitToken(fresh);
868+
expect(document.cookie).toContain(fresh);
869+
870+
const stale = createJwtWithOiat(900, 100);
871+
emitToken(stale);
872+
expect(document.cookie).not.toContain(stale);
873+
expect(document.cookie).toContain(fresh);
874+
});
875+
876+
it('applies a fresher same-context token', async () => {
877+
await loadClerkWithSession();
878+
879+
const older = createJwtWithOiat(1000, 100);
880+
emitToken(older);
881+
expect(document.cookie).toContain(older);
882+
883+
const newer = createJwtWithOiat(1100, 200);
884+
emitToken(newer);
885+
expect(document.cookie).toContain(newer);
886+
});
887+
888+
it('applies a token with equal oiat and iat (publish on tie)', async () => {
889+
await loadClerkWithSession();
890+
891+
const first = createJwtWithOiat(1000, 100, { ttl: 60 });
892+
emitToken(first);
893+
expect(document.cookie).toContain(first);
894+
895+
const second = createJwtWithOiat(1000, 100, { ttl: 120 });
896+
emitToken(second);
897+
expect(document.cookie).toContain(second);
898+
});
899+
900+
it('drops a token for a different session', async () => {
901+
await loadClerkWithSession();
902+
903+
const wrongSession = createJwtWithOiat(1000, 200, { sid: 'sess_other' });
904+
emitToken(wrongSession);
905+
expect(document.cookie).not.toContain(wrongSession);
906+
});
907+
908+
it('drops a token for a different organization', async () => {
909+
await loadClerkWithSession();
910+
911+
const wrongOrg = createJwtWithOiat(1000, 200, { org: 'org_other' });
912+
emitToken(wrongOrg);
913+
expect(document.cookie).not.toContain(wrongOrg);
914+
});
915+
916+
it('applies a personal-workspace token (no org) for the active personal workspace', async () => {
917+
await loadClerkWithSession();
918+
919+
const personal = createJwtWithOiat(1000, 200);
920+
emitToken(personal);
921+
expect(document.cookie).toContain(personal);
922+
});
923+
924+
it('applies an active-context token even when the current cookie is a different session with higher oiat', async () => {
925+
const sut = await loadClerkWithSession();
926+
927+
// Plant a different-session, higher-oiat cookie by temporarily making it the active context.
928+
(sut.session as any).id = 'sess_other';
929+
const otherContext = createJwtWithOiat(2000, 999, { sid: 'sess_other' });
930+
emitToken(otherContext);
931+
expect(document.cookie).toContain(otherContext);
932+
933+
// Restore the active session; a lower-oiat active-context token must still apply,
934+
// because the different-session cookie is not a valid freshness baseline.
935+
(sut.session as any).id = sessionId;
936+
const active = createJwtWithOiat(1000, 100, { sid: sessionId });
937+
emitToken(active);
938+
expect(document.cookie).toContain(active);
939+
});
940+
941+
it('applies a token without an oiat header (fail open)', async () => {
942+
await loadClerkWithSession();
943+
944+
const noOiat = createJwtWithOiat(1000, undefined);
945+
emitToken(noOiat);
946+
expect(document.cookie).toContain(noOiat);
947+
});
948+
949+
it('applies a malformed token (fail open)', async () => {
950+
await loadClerkWithSession();
951+
952+
emitToken('garbage.token');
953+
expect(document.cookie).toContain('garbage.token');
954+
});
955+
956+
it('removes the cookie when the token is null', async () => {
957+
await loadClerkWithSession();
958+
959+
const fresh = createJwtWithOiat(1000, 200);
960+
emitToken(fresh);
961+
expect(document.cookie).toContain(fresh);
962+
963+
emitToken(null);
964+
expect(document.cookie).not.toContain(fresh);
965+
});
966+
});
967+
822968
describe('.signOut()', () => {
823969
const mockClientDestroy = vi.fn();
824970
const mockClientRemoveSessions = vi.fn();

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

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,58 @@ describe('SessionTokenCache', () => {
285285
expect(resultAfterNewer?.entry.createdAt).toBe(1666648250);
286286
});
287287

288+
it('ignores a broadcast staler than a carried-forward resolvedToken even when the resolver is staler', async () => {
289+
// resolvedToken carry-forward can leave the live entry's resolvedToken FRESHER than
290+
// the token its tokenResolver resolves to. The broadcast guard must compare against
291+
// resolvedToken (the freshest known), not the staler resolver, otherwise a broadcast
292+
// that is staler than resolvedToken slips past the guard and runs setInternal, which
293+
// clears the refresh timer without reinstalling one.
294+
const tokenId = 'session_123';
295+
const tick = async () => {
296+
await Promise.resolve();
297+
await Promise.resolve();
298+
};
299+
const makeToken = (raw: string) => new Token({ id: tokenId, jwt: raw, object: 'token' }) as TokenResource;
300+
301+
const highRaw = createJwtWithOiat(1666648250, 1666648250, 120);
302+
const lowRaw = createJwtWithOiat(1666648190, 1666648190, 120);
303+
304+
// Cache the high-oiat token and let it resolve so resolvedToken = high.
305+
SessionTokenCache.set({ tokenId, tokenResolver: Promise.resolve(makeToken(highRaw)) });
306+
await tick();
307+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
308+
309+
// Overwrite with a resolver that resolves to a LOWER-oiat token. Carry-forward keeps the
310+
// live entry's resolvedToken = high while its tokenResolver resolves to low.
311+
SessionTokenCache.set({ tokenId, tokenResolver: Promise.resolve(makeToken(lowRaw)) });
312+
await tick();
313+
const beforeEntry = SessionTokenCache.get({ tokenId })?.entry;
314+
expect(beforeEntry?.resolvedToken?.getRawString()).toBe(highRaw);
315+
const beforeCreatedAt = beforeEntry?.createdAt;
316+
317+
// Broadcast a token staler than high (but fresher than low, so the staler resolver would
318+
// have let it through under the bug).
319+
const stalerRaw = createJwtWithOiat(1666648220, 1666648220, 120);
320+
const stalerEvent: MessageEvent<SessionTokenEvent> = {
321+
data: {
322+
organizationId: null,
323+
sessionId: 'session_123',
324+
template: undefined,
325+
tokenId,
326+
tokenRaw: stalerRaw,
327+
traceId: 'test_trace_carry_forward',
328+
},
329+
} as MessageEvent<SessionTokenEvent>;
330+
331+
await broadcastListener(stalerEvent);
332+
333+
const afterEntry = SessionTokenCache.get({ tokenId })?.entry;
334+
expect(afterEntry?.resolvedToken?.getRawString()).toBe(highRaw);
335+
// createdAt unchanged proves the broadcast was dropped before setInternal ran; the bug
336+
// would have replaced the entry, stamping it with the broadcast's iat (1666648220).
337+
expect(afterEntry?.createdAt).toBe(beforeCreatedAt);
338+
});
339+
288340
it('successfully updates cache with valid token', () => {
289341
const event: MessageEvent<SessionTokenEvent> = {
290342
data: {
@@ -368,6 +420,161 @@ describe('SessionTokenCache', () => {
368420
});
369421
});
370422

423+
describe('same-tab monotonic resolve', () => {
424+
const tokenId = 'session_123';
425+
426+
// Flush enough microtasks for setInternal's tokenResolver.then handler to run.
427+
const tick = async () => {
428+
await Promise.resolve();
429+
await Promise.resolve();
430+
};
431+
432+
const deferred = () => {
433+
let resolve!: (token: TokenResource) => void;
434+
const promise = new Promise<TokenResource>(r => {
435+
resolve = r;
436+
});
437+
return { promise, resolve };
438+
};
439+
440+
const makeToken = (raw: string) => new Token({ id: tokenId, jwt: raw, object: 'token' }) as TokenResource;
441+
442+
it('keeps the fresher token when a staler set overwrites it, resolving high then low', async () => {
443+
const highRaw = createJwtWithOiat(1666648250, 1666648250, 120);
444+
const lowRaw = createJwtWithOiat(1666648190, 1666648190, 120);
445+
446+
const high = deferred();
447+
SessionTokenCache.set({ tokenId, tokenResolver: high.promise, onRefresh: undefined });
448+
449+
const low = deferred();
450+
SessionTokenCache.set({ tokenId, tokenResolver: low.promise, onRefresh: undefined });
451+
452+
high.resolve(makeToken(highRaw));
453+
await tick();
454+
low.resolve(makeToken(lowRaw));
455+
await tick();
456+
457+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
458+
});
459+
460+
it('keeps the fresher token when a staler set overwrites it, resolving low then high', async () => {
461+
const highRaw = createJwtWithOiat(1666648250, 1666648250, 120);
462+
const lowRaw = createJwtWithOiat(1666648190, 1666648190, 120);
463+
464+
const high = deferred();
465+
SessionTokenCache.set({ tokenId, tokenResolver: high.promise, onRefresh: undefined });
466+
467+
const low = deferred();
468+
SessionTokenCache.set({ tokenId, tokenResolver: low.promise, onRefresh: undefined });
469+
470+
low.resolve(makeToken(lowRaw));
471+
await tick();
472+
high.resolve(makeToken(highRaw));
473+
await tick();
474+
475+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
476+
});
477+
478+
it('publishes the later token on a full oiat+iat tie with different raw payloads', async () => {
479+
const b64 = (o: object) => btoa(JSON.stringify(o)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
480+
const header = { alg: 'HS256', typ: 'JWT', oiat: 1666648250 };
481+
const firstRaw = `${b64(header)}.${b64({ sid: tokenId, sub: 'user_A', exp: 1666648370, iat: 1666648250 })}.sig`;
482+
const laterRaw = `${b64(header)}.${b64({ sid: tokenId, sub: 'user_B', exp: 1666648370, iat: 1666648250 })}.sig`;
483+
484+
const first = deferred();
485+
SessionTokenCache.set({ tokenId, tokenResolver: first.promise, onRefresh: undefined });
486+
487+
const later = deferred();
488+
SessionTokenCache.set({ tokenId, tokenResolver: later.promise, onRefresh: undefined });
489+
490+
first.resolve(makeToken(firstRaw));
491+
await tick();
492+
later.resolve(makeToken(laterRaw));
493+
await tick();
494+
495+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(laterRaw);
496+
});
497+
498+
it('carries the prior resolved token forward into a new pending entry', async () => {
499+
const highRaw = createJwtWithOiat(1666648250, 1666648250, 120);
500+
501+
const high = deferred();
502+
SessionTokenCache.set({ tokenId, tokenResolver: high.promise, onRefresh: undefined });
503+
high.resolve(makeToken(highRaw));
504+
await tick();
505+
506+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
507+
508+
const pending = deferred();
509+
SessionTokenCache.set({ tokenId, tokenResolver: pending.promise, onRefresh: undefined });
510+
511+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
512+
});
513+
514+
it('does not resurrect a cleared key when its pending resolver settles', async () => {
515+
const raw = createJwtWithOiat(1666648250, 1666648250, 120);
516+
517+
const pending = deferred();
518+
SessionTokenCache.set({ tokenId, tokenResolver: pending.promise, onRefresh: undefined });
519+
520+
SessionTokenCache.clear();
521+
522+
pending.resolve(makeToken(raw));
523+
await tick();
524+
525+
expect(SessionTokenCache.get({ tokenId })).toBeUndefined();
526+
});
527+
528+
it('derives the deletion timer from the winner, not from a later staler resolve', async () => {
529+
// high: longer ttl AND fresher oiat; low: short ttl AND staler oiat.
530+
const highRaw = createJwtWithOiat(1666648250, 1666648260, 300);
531+
const lowRaw = createJwtWithOiat(1666648255, 1666648250, 60);
532+
533+
const high = deferred();
534+
SessionTokenCache.set({ tokenId, tokenResolver: high.promise, onRefresh: undefined });
535+
536+
const low = deferred();
537+
SessionTokenCache.set({ tokenId, tokenResolver: low.promise, onRefresh: undefined });
538+
539+
// Winner resolves first, staler resolves second: the staler resolve must not
540+
// replace the winner's deletion timer with its own short-ttl timer.
541+
high.resolve(makeToken(highRaw));
542+
await tick();
543+
low.resolve(makeToken(lowRaw));
544+
await tick();
545+
546+
// Past low's 60s ttl but well before high's 300s ttl.
547+
vi.advanceTimersByTime(120 * 1000);
548+
549+
const result = SessionTokenCache.get({ tokenId });
550+
expect(result).toBeDefined();
551+
expect(result?.entry.resolvedToken?.getRawString()).toBe(highRaw);
552+
});
553+
554+
it('expires the carried token by its real ttl while the replacement resolver stays pending', async () => {
555+
const highRaw = createJwtWithOiat(1666648250, 1666648250, 120);
556+
557+
const high = deferred();
558+
SessionTokenCache.set({ tokenId, tokenResolver: high.promise, onRefresh: undefined });
559+
high.resolve(makeToken(highRaw));
560+
await tick();
561+
562+
// Cache holds high with its real 120s ttl (iat 1666648250, now 1666648260).
563+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
564+
565+
// Replacement resolver never settles; high is carried forward into the pending entry.
566+
const neverSettles = new Promise<TokenResource>(() => {});
567+
SessionTokenCache.set({ tokenId, tokenResolver: neverSettles, onRefresh: undefined });
568+
569+
// The carry still serves high synchronously while the replacement is pending.
570+
expect(SessionTokenCache.get({ tokenId })?.entry.resolvedToken?.getRawString()).toBe(highRaw);
571+
572+
// Past high's real 120s ttl: get() must evict the carried token, not serve it forever.
573+
vi.advanceTimersByTime(130 * 1000);
574+
expect(SessionTokenCache.get({ tokenId })).toBeUndefined();
575+
});
576+
});
577+
371578
describe('token expiration with absolute time', () => {
372579
it('returns token when expiresAt is far in the future', async () => {
373580
const futureExp = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now

0 commit comments

Comments
 (0)