From dfd544a8f73e9993f81c11944f9dec44530658fa Mon Sep 17 00:00:00 2001 From: KJH Date: Fri, 2 Oct 2026 20:57:14 +0800 Subject: [PATCH 1/2] fix(client): stop resending a rejected refresh token after invalid_grant auth() treats invalid_grant as recoverable: it warns, calls the optional provider.invalidateCredentials('tokens') and retries authInternal. When a provider does not implement invalidateCredentials, tokens() still returns the refresh token the authorization server just rejected, so the retry refreshes with it again, gets invalid_grant again, and that second error reaches the caller. The warning says it is retrying authorization, but authorization is never reached. Pass forceReauthorization on that retry so it skips the refresh branch and starts a new authorization request, which is what the warning and the v2 migration guide already describe. Providers that implement invalidateCredentials see no change. Refs #2915 Co-Authored-By: Claude Fable 5.1 --- .changeset/invalid-grant-retry-skips-refresh.md | 5 +++++ packages/client/src/client/auth.ts | 6 ++++-- packages/client/test/client/auth.test.ts | 15 +++++++-------- packages/client/test/client/sse.test.ts | 5 ++++- 4 files changed, 20 insertions(+), 11 deletions(-) create mode 100644 .changeset/invalid-grant-retry-skips-refresh.md diff --git a/.changeset/invalid-grant-retry-skips-refresh.md b/.changeset/invalid-grant-retry-skips-refresh.md new file mode 100644 index 0000000000..9d8c9e750b --- /dev/null +++ b/.changeset/invalid-grant-retry-skips-refresh.md @@ -0,0 +1,5 @@ +--- +'@modelcontextprotocol/client': patch +--- + +When a refresh fails with `invalid_grant` or `invalid_dpop_proof`, `auth()` now retries with a new authorization request instead of sending the rejected refresh token again. Before this change, a provider that does not implement `invalidateCredentials()` still returned the rejected refresh token from `tokens()`, so the retry refreshed with it a second time and `auth()` threw the authorization server's error instead of returning `'REDIRECT'`. Providers that implement `invalidateCredentials()` behave as before. diff --git a/packages/client/src/client/auth.ts b/packages/client/src/client/auth.ts index 53a5b7e62e..85c6fe7458 100644 --- a/packages/client/src/client/auth.ts +++ b/packages/client/src/client/auth.ts @@ -1118,10 +1118,12 @@ export async function auth(provider: OAuthClientProvider, options: AuthOptions): // invalid_dpop_proof on refresh typically means the stored refresh token is bound // (RFC 9449 §5) to a DPoP key this process no longer holds — e.g. a non-extractable // key regenerated across a restart. Like invalid_grant, the token set is unusable; - // drop it and fall through to a fresh authorization. + // drop it and fall through to a fresh authorization. forceReauthorization keeps the + // retry from sending the rejected refresh token again: a provider without + // invalidateCredentials() still returns it from tokens(). warnCredentialInvalidation(provider, error, 'tokens'); await provider.invalidateCredentials?.('tokens'); - return await authInternal(provider, options); + return await authInternal(provider, { ...options, forceReauthorization: true }); } } diff --git a/packages/client/test/client/auth.test.ts b/packages/client/test/client/auth.test.ts index 56f4134e89..5ec47cda6d 100644 --- a/packages/client/test/client/auth.test.ts +++ b/packages/client/test/client/auth.test.ts @@ -3312,7 +3312,7 @@ describe('OAuth Authorization', () => { expect(warn).toHaveBeenCalled(); }); - it('warns, and cannot recover, when invalid_grant hits a provider with no invalidateCredentials (#2034)', async () => { + it('warns, and starts a fresh authorization, when invalid_grant hits a provider with no invalidateCredentials (#2915)', async () => { let tokenPosts = 0; mockDiscoveryWithTokenEndpoint(() => { tokenPosts++; @@ -3327,18 +3327,17 @@ describe('OAuth Authorization', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); // invalid_grant is rethrown out of the refresh block into auth()'s outer catch, - // which retries authInternal. Nothing was invalidated, so the retry replays the - // same dead refresh token and the second failure propagates to the caller. - await expect(auth(mockProvider, { serverUrl: 'https://api.example.com/mcp-server' })).rejects.toThrow('Refresh token expired'); + // which retries authInternal. The retry must not replay the refresh token the + // authorization server just rejected, so it goes straight to a new authorization. + await expect(auth(mockProvider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); expect(warn).toHaveBeenCalledWith(expect.stringContaining('OAuth "invalid_grant"')); expect(warn).toHaveBeenCalledWith(expect.stringContaining('Refresh token expired')); // The warn must not claim a discard that never happened. expect(warn).toHaveBeenCalledWith(expect.stringContaining('without discarding the stored tokens')); - // The retry is futile for this provider shape: the dead refresh token goes to the - // token endpoint a second time and no authorization is ever started. - expect(tokenPosts).toBe(2); - expect(mockProvider.redirectToAuthorization).not.toHaveBeenCalled(); + // The dead refresh token goes to the token endpoint once, not twice. + expect(tokenPosts).toBe(1); + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledTimes(1); warn.mockRestore(); }); diff --git a/packages/client/test/client/sse.test.ts b/packages/client/test/client/sse.test.ts index c9ceb23c3d..e0b89a403e 100644 --- a/packages/client/test/client/sse.test.ts +++ b/packages/client/test/client/sse.test.ts @@ -1321,8 +1321,11 @@ describe('SSEClientTransport', () => { authProvider: mockAuthProvider }); - await expect(() => transport.start()).rejects.toMatchObject(expectedError); + // The retry does not send the rejected refresh token again (this mock's + // invalidateCredentials() clears nothing): it starts a new authorization. + await expect(() => transport.start()).rejects.toThrow(UnauthorizedError); expect(mockAuthProvider.invalidateCredentials).toHaveBeenCalledWith('tokens'); + expect(mockAuthProvider.redirectToAuthorization).toHaveBeenCalledTimes(1); }); }); From 186481f5d6d5579c9b7b5b044a598af8a076d58e Mon Sep 17 00:00:00 2001 From: KJH Date: Sun, 8 Nov 2026 15:05:40 +0800 Subject: [PATCH 2/2] fix(client): remember a rejected refresh token across auth() calls Record the refresh token an authorization server rejected with invalid_grant or invalid_dpop_proof, per provider, and skip the refresh branch while tokens() still returns it. This covers later auth() calls as well as the immediate retry, so the forceReauthorization flag on the retry is no longer needed. A different stored refresh token is refreshed as usual. --- .../invalid-grant-retry-skips-refresh.md | 2 +- packages/client/src/client/auth.ts | 27 +++++++--- packages/client/test/client/auth.test.ts | 51 ++++++++++++++++++- 3 files changed, 71 insertions(+), 9 deletions(-) diff --git a/.changeset/invalid-grant-retry-skips-refresh.md b/.changeset/invalid-grant-retry-skips-refresh.md index 9d8c9e750b..cb2e1b93a4 100644 --- a/.changeset/invalid-grant-retry-skips-refresh.md +++ b/.changeset/invalid-grant-retry-skips-refresh.md @@ -2,4 +2,4 @@ '@modelcontextprotocol/client': patch --- -When a refresh fails with `invalid_grant` or `invalid_dpop_proof`, `auth()` now retries with a new authorization request instead of sending the rejected refresh token again. Before this change, a provider that does not implement `invalidateCredentials()` still returned the rejected refresh token from `tokens()`, so the retry refreshed with it a second time and `auth()` threw the authorization server's error instead of returning `'REDIRECT'`. Providers that implement `invalidateCredentials()` behave as before. +`auth()` no longer sends a refresh token to the token endpoint again after the authorization server rejected it with `invalid_grant` or `invalid_dpop_proof`. It remembers the rejected token per provider and goes straight to a new authorization, both in the immediate retry and in later `auth()` calls, until a different refresh token is stored. Before this change, a provider that does not implement `invalidateCredentials()` kept returning the rejected token from `tokens()`, so the retry refreshed with it a second time and `auth()` threw the authorization server's error instead of returning `'REDIRECT'`. Providers that implement `invalidateCredentials()` behave as before. diff --git a/packages/client/src/client/auth.ts b/packages/client/src/client/auth.ts index 85c6fe7458..d21f98c150 100644 --- a/packages/client/src/client/auth.ts +++ b/packages/client/src/client/auth.ts @@ -1080,8 +1080,8 @@ export interface AuthOptions { */ function warnCredentialInvalidation(provider: OAuthClientProvider, error: OAuthError, invalidated: string): void { // `invalidateCredentials` is optional. When a provider omits it nothing is actually - // discarded, so do not claim otherwise — the stale credential is still in storage and - // will be replayed on the next call, which is the thing worth telling the operator. + // discarded, so do not claim otherwise — the stale credential is still in storage, which is + // the thing worth telling the operator. const action = provider.invalidateCredentials === undefined ? `retrying authorization without discarding the stored ${invalidated} (provider implements no invalidateCredentials())` @@ -1094,6 +1094,14 @@ function warnCredentialInvalidation(provider: OAuthClientProvider, error: OAuthE ); } +/** + * The last refresh token each provider had rejected with `invalid_grant` or `invalid_dpop_proof`. + * `invalidateCredentials()` is optional, so a provider may keep returning a rejected token from + * `tokens()` until a new authorization saves a different one. Sending it again cannot succeed + * (RFC 6749 §5.2), so the refresh branch skips it, in the retry and in every later call. + */ +const rejectedRefreshTokens = new WeakMap(); + /** * Orchestrates the full auth flow with a server. * @@ -1118,12 +1126,10 @@ export async function auth(provider: OAuthClientProvider, options: AuthOptions): // invalid_dpop_proof on refresh typically means the stored refresh token is bound // (RFC 9449 §5) to a DPoP key this process no longer holds — e.g. a non-extractable // key regenerated across a restart. Like invalid_grant, the token set is unusable; - // drop it and fall through to a fresh authorization. forceReauthorization keeps the - // retry from sending the rejected refresh token again: a provider without - // invalidateCredentials() still returns it from tokens(). + // drop it and fall through to a fresh authorization. warnCredentialInvalidation(provider, error, 'tokens'); await provider.invalidateCredentials?.('tokens'); - return await authInternal(provider, { ...options, forceReauthorization: true }); + return await authInternal(provider, options); } } @@ -1428,7 +1434,8 @@ async function authInternal( // `forceReauthorization` when the requested scope strictly exceeds the // current token's granted scope — refreshing would not widen it (RFC 6749 // §6), so skip straight to a fresh authorization request. - if (tokens?.refresh_token && !forceReauthorization) { + const refreshTokenRejected = tokens?.refresh_token !== undefined && rejectedRefreshTokens.get(provider) === tokens.refresh_token; + if (tokens?.refresh_token && !forceReauthorization && !refreshTokenRejected) { const refreshScope = await provider.scopeForRefresh?.(tokens); let newTokens: OAuthTokens | undefined; try { @@ -1450,6 +1457,12 @@ async function authInternal( if (error instanceof InsecureTokenEndpointError) { throw error; } + if ( + error instanceof OAuthError && + (error.code === OAuthErrorCode.InvalidGrant || error.code === OAuthErrorCode.InvalidDpopProof) + ) { + rejectedRefreshTokens.set(provider, tokens.refresh_token); + } // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. if (!(error instanceof OAuthError) || error.code === OAuthErrorCode.ServerError) { // Could not refresh OAuth tokens. The fallthrough to a fresh authorization diff --git a/packages/client/test/client/auth.test.ts b/packages/client/test/client/auth.test.ts index 5ec47cda6d..995240f76a 100644 --- a/packages/client/test/client/auth.test.ts +++ b/packages/client/test/client/auth.test.ts @@ -3313,6 +3313,8 @@ describe('OAuth Authorization', () => { }); it('warns, and starts a fresh authorization, when invalid_grant hits a provider with no invalidateCredentials (#2915)', async () => { + // Its own provider object: auth() remembers rejected refresh tokens per provider. + const provider: OAuthClientProvider = { ...mockProvider }; let tokenPosts = 0; mockDiscoveryWithTokenEndpoint(() => { tokenPosts++; @@ -3329,7 +3331,7 @@ describe('OAuth Authorization', () => { // invalid_grant is rethrown out of the refresh block into auth()'s outer catch, // which retries authInternal. The retry must not replay the refresh token the // authorization server just rejected, so it goes straight to a new authorization. - await expect(auth(mockProvider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); expect(warn).toHaveBeenCalledWith(expect.stringContaining('OAuth "invalid_grant"')); expect(warn).toHaveBeenCalledWith(expect.stringContaining('Refresh token expired')); @@ -3341,6 +3343,53 @@ describe('OAuth Authorization', () => { warn.mockRestore(); }); + it('does not resend a rejected refresh token on a later auth() call either (#2915)', async () => { + // Its own provider object: auth() remembers rejected refresh tokens per provider. + const provider: OAuthClientProvider = { ...mockProvider }; + let tokenPosts = 0; + mockDiscoveryWithTokenEndpoint(() => { + tokenPosts++; + return oauthErrorResponse(OAuthErrorCode.InvalidGrant, 'Refresh token expired'); + }); + (mockProvider.clientInformation as Mock).mockResolvedValue({ client_id: 'test-client', client_secret: 'test-secret' }); + // No invalidateCredentials(): every read returns the same dead refresh token. + (mockProvider.tokens as Mock).mockResolvedValue({ ...storedTokens, refresh_token: 'rejected-later-call' }); + (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); + // A second call before a new authorization has replaced the stored tokens. + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); + + expect(tokenPosts).toBe(1); + expect(mockProvider.redirectToAuthorization).toHaveBeenCalledTimes(2); + warn.mockRestore(); + }); + + it('refreshes again once a different refresh token is stored after a rejection (#2915)', async () => { + // Its own provider object: auth() remembers rejected refresh tokens per provider. + const provider: OAuthClientProvider = { ...mockProvider }; + const posted: string[] = []; + mockDiscoveryWithTokenEndpoint(() => { + const body = String(mockFetch.mock.calls.at(-1)![1].body); + posted.push(new URLSearchParams(body).get('refresh_token') ?? ''); + return posted.length === 1 + ? oauthErrorResponse(OAuthErrorCode.InvalidGrant, 'Refresh token expired') + : refreshedWithoutScope(); + }); + (mockProvider.clientInformation as Mock).mockResolvedValue({ client_id: 'test-client' }); + (mockProvider.tokens as Mock).mockResolvedValue({ ...storedTokens, refresh_token: 'rejected-then-replaced' }); + (mockProvider.saveTokens as Mock).mockResolvedValue(undefined); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('REDIRECT'); + (mockProvider.tokens as Mock).mockResolvedValue({ ...storedTokens, refresh_token: 'fresh-refresh' }); + await expect(auth(provider, { serverUrl: 'https://api.example.com/mcp-server' })).resolves.toBe('AUTHORIZED'); + + expect(posted).toEqual(['rejected-then-replaced', 'fresh-refresh']); + warn.mockRestore(); + }); + // A local provider — adding invalidateCredentials to the shared mockProvider would // leak into every later test in this describe. const providerWithInvalidation = (invalidateCredentials: Mock): OAuthClientProvider => ({