import { useQuery } from '@tanstack/react-query' import { useAuthConfigQuery } from '../auth/auth-config-query' import { oauthServerAppKeys } from './keys' import { useProjectApiUrl } from '@/data/config/project-endpoint-query' import { handleError } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomQueryOptions } from '@/types' export type OpenIDConfigurationVariables = { projectRef: string | undefined } /** * OpenID Connect Discovery response * @see https://openid.net/specs/openid-connect-discovery-1_0.html */ export type OpenIDConfiguration = { issuer: string authorization_endpoint: string token_endpoint: string userinfo_endpoint?: string jwks_uri: string registration_endpoint?: string scopes_supported?: string[] response_types_supported?: string[] grant_types_supported?: string[] subject_types_supported?: string[] id_token_signing_alg_values_supported?: string[] token_endpoint_auth_methods_supported?: string[] code_challenge_methods_supported?: string[] } export async function getOpenIDConfiguration({ endpoint, }: { endpoint: string | undefined }): Promise { if (!endpoint) throw new Error('Client endpoint is required') const response = await fetch(`${endpoint}/auth/v1/.well-known/openid-configuration`) if (!response.ok) { handleError({ message: `Failed to fetch OpenID configuration: ${response.statusText}` }) } return response.json() } export type OpenIDConfigurationData = Awaited> export type OpenIDConfigurationError = StudioError export const useOpenIDConfigurationQuery = ( { projectRef }: OpenIDConfigurationVariables, { enabled = true, ...options }: UseCustomQueryOptions = {} ) => { const { hostEndpoint, isPending: isEndpointLoading } = useProjectApiUrl({ projectRef, }) const { data: authConfig, isSuccess: isSuccessConfig, isLoading: isAuthConfigLoading, } = useAuthConfigQuery({ projectRef }) const isOAuthServerEnabled = !!authConfig?.OAUTH_SERVER_ENABLED const isQueryEnabled = enabled && typeof projectRef !== 'undefined' && !!hostEndpoint && isSuccessConfig && isOAuthServerEnabled const query = useQuery({ queryKey: oauthServerAppKeys.openidConfiguration(projectRef), queryFn: () => getOpenIDConfiguration({ endpoint: hostEndpoint }), enabled: isQueryEnabled, ...options, }) // Include loading states from dependencies const isLoading = query.isLoading || isEndpointLoading || isAuthConfigLoading return { ...query, isLoading, } }