diff --git a/src/core/AuthKitCore.spec.ts b/src/core/AuthKitCore.spec.ts index 378dce8..202fd42 100644 --- a/src/core/AuthKitCore.spec.ts +++ b/src/core/AuthKitCore.spec.ts @@ -469,6 +469,43 @@ describe('AuthKitCore', () => { vi.useRealTimers(); }); + it('recovers when a shared refresh dies with the request that started it', async () => { + vi.useFakeTimers(); + const { client, getCallCount } = makeCountingClient(); + const testCore = new AuthKitCore( + mockConfig as any, + client as any, + mockEncryption as any, + ); + // What Cloudflare Workers gives other requests awaiting a promise whose + // creating request has ended. Its cleanup never runs, so it stays in the map. + const inflight = (testCore as any).inflightRefreshes as Map< + string, + Promise + >; + inflight.set( + 'rt-1\0', + Promise.reject(new Error('created by a request that has since ended')), + ); + + const session = makeExpiredSession(); + const pending = Promise.all([ + testCore.validateAndRefresh(session), + testCore.validateAndRefresh(session), + ]); + await vi.advanceTimersByTimeAsync(50); + const results = await pending; + + // Both waiters drop the dead entry and share one fresh refresh. + expect(getCallCount()).toBe(1); + for (const r of results) { + expect(r.refreshed).toBe(true); + expect(r.session.accessToken).toBe(newJwt); + } + expect(inflight.size).toBe(0); + vi.useRealTimers(); + }); + it('deduplicates separately per organizationId', async () => { vi.useFakeTimers(); const { client, getCallCount } = makeCountingClient(); diff --git a/src/core/AuthKitCore.ts b/src/core/AuthKitCore.ts index a4cdba0..de3293e 100644 --- a/src/core/AuthKitCore.ts +++ b/src/core/AuthKitCore.ts @@ -264,7 +264,18 @@ export class AuthKitCore { ): Promise { const key = `${refreshToken}\0${organizationId ?? ''}`; const existing = this.inflightRefreshes.get(key); - if (existing) return existing; + if (existing) { + return existing.catch(error => { + if (error instanceof TokenRefreshError) throw error; + // Any other rejection means the shared promise died with the request + // that created it (e.g. Cloudflare Workers cancels I/O when a request + // ends), so its cleanup never ran. Drop it and refresh in this request. + if (this.inflightRefreshes.get(key) === existing) { + this.inflightRefreshes.delete(key); + } + return this.refreshTokens(refreshToken, organizationId, context); + }); + } const cleanup = () => { this.inflightRefreshes.delete(key);