diff --git a/packages/client/src/client/auth.ts b/packages/client/src/client/auth.ts index 5f55fb7a08..3ff6686c36 100644 --- a/packages/client/src/client/auth.ts +++ b/packages/client/src/client/auth.ts @@ -1262,10 +1262,15 @@ export async function discoverAuthorizationServerMetadata( ); } - // Parse and validate based on type - return type === 'oauth' - ? OAuthMetadataSchema.parse(await response.json()) - : OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + let json: unknown; + try { + json = await response.json(); + } catch { + await response.body?.cancel().catch(() => {}); + continue; + } + + return type === 'oauth' ? OAuthMetadataSchema.parse(json) : OpenIdProviderDiscoveryMetadataSchema.parse(json); } return undefined; diff --git a/packages/client/test/client/auth.test.ts b/packages/client/test/client/auth.test.ts index 04d7f4a3fb..0137557aa1 100644 --- a/packages/client/test/client/auth.test.ts +++ b/packages/client/test/client/auth.test.ts @@ -924,6 +924,34 @@ describe('OAuth Authorization', () => { expect(metadata).toEqual(validOpenIdMetadata); }); + it('continues when a successful response is not JSON', async () => { + const cancelBody = vi.fn().mockResolvedValue(undefined); + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => { + throw new SyntaxError('Unexpected token < in JSON'); + }, + body: { + cancel: cancelBody + } + }); + + mockFetch.mockResolvedValueOnce({ + ok: true, + status: 200, + json: async () => validOpenIdMetadata + }); + + const metadata = await discoverAuthorizationServerMetadata('https://auth.example.com/tenant1'); + + expect(metadata).toEqual(validOpenIdMetadata); + expect(mockFetch).toHaveBeenCalledTimes(2); + expect(mockFetch.mock.calls[0]![0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/tenant1'); + expect(mockFetch.mock.calls[1]![0].toString()).toBe('https://auth.example.com/.well-known/openid-configuration/tenant1'); + expect(cancelBody).toHaveBeenCalledTimes(1); + }); + it('continues on 502 and tries next URL', async () => { // First URL (OAuth) returns 502 (reverse proxy with no route) mockFetch.mockResolvedValueOnce({