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
37 changes: 37 additions & 0 deletions src/core/AuthKitCore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<unknown>
>;
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();
Expand Down
13 changes: 12 additions & 1 deletion src/core/AuthKitCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,18 @@ export class AuthKitCore {
): Promise<RefreshResult> {
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);
Expand Down
Loading