Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix: Refactor the temp API keys creation for oAuth Server apps (#40849)

Ivan Vasilovd33fdcb4f2e6
diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx
index ba69df9be79..65d9d406209 100644
--- a/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx
+++ b/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx
@@ -12,10 +12,11 @@ import { toast } from 'sonner'
import * as z from 'zod'
import { useParams } from 'common'
+import Panel from 'components/ui/Panel'
+import { useProjectEndpointQuery } from 'data/config/project-endpoint-query'
import { useOAuthServerAppCreateMutation } from 'data/oauth-server-apps/oauth-server-app-create-mutation'
import { useOAuthServerAppRegenerateSecretMutation } from 'data/oauth-server-apps/oauth-server-app-regenerate-secret-mutation'
import { useOAuthServerAppUpdateMutation } from 'data/oauth-server-apps/oauth-server-app-update-mutation'
-import { useSupabaseClientQuery } from 'hooks/use-supabase-client-query'
import {
Button,
FormControl_Shadcn_,
@@ -37,10 +38,9 @@ import {
Switch,
cn,
} from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { Input } from 'ui-patterns/DataInputs/Input'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import Panel from 'components/ui/Panel'
interface CreateOrUpdateOAuthAppSheetProps {
visible: boolean
@@ -109,26 +109,21 @@ export const CreateOrUpdateOAuthAppSheet = ({
control: form.control,
})
- const { data: supabaseClientData } = useSupabaseClientQuery({ projectRef })
- const { mutateAsync: createOAuthApp, isPending: isCreating } = useOAuthServerAppCreateMutation({
+ const { data: endpointData } = useProjectEndpointQuery({ projectRef })
+
+ const { mutate: createOAuthApp, isPending: isCreating } = useOAuthServerAppCreateMutation({
onSuccess: (data) => {
toast.success(`Successfully created OAuth app "${data.client_name}"`)
onSuccess(data)
},
- onError: (error) => {
- toast.error(error.message)
- },
})
- const { mutateAsync: updateOAuthApp, isPending: isUpdating } = useOAuthServerAppUpdateMutation({
+ const { mutate: updateOAuthApp, isPending: isUpdating } = useOAuthServerAppUpdateMutation({
onSuccess: (data) => {
toast.success(`Successfully updated OAuth app "${data.client_name}"`)
onSuccess(data)
},
- onError: (error) => {
- toast.error(error.message)
- },
})
- const { mutateAsync: regenerateSecret, isPending: isRegenerating } =
+ const { mutate: regenerateSecret, isPending: isRegenerating } =
useOAuthServerAppRegenerateSecretMutation({
onSuccess: (data) => {
if (data) {
@@ -137,9 +132,6 @@ export const CreateOrUpdateOAuthAppSheet = ({
setShowRegenerateDialog(false)
}
},
- onError: (error) => {
- toast.error(error.message)
- },
})
useEffect(() => {
@@ -207,8 +199,8 @@ export const CreateOrUpdateOAuthAppSheet = ({
updateOAuthApp({
projectRef,
- supabaseClient: supabaseClientData?.supabaseClient,
clientId: appToEdit.client_id,
+ clientEndpoint: endpointData?.endpoint,
...payload,
})
} else {
@@ -222,7 +214,7 @@ export const CreateOrUpdateOAuthAppSheet = ({
createOAuthApp({
projectRef,
- supabaseClient: supabaseClientData?.supabaseClient,
+ clientEndpoint: endpointData?.endpoint,
...payload,
})
}
@@ -238,13 +230,11 @@ export const CreateOrUpdateOAuthAppSheet = ({
}
const handleConfirmRegenerate = () => {
- if (appToEdit?.client_id) {
- regenerateSecret({
- projectRef,
- supabaseClient: supabaseClientData?.supabaseClient,
- clientId: appToEdit.client_id,
- })
- }
+ regenerateSecret({
+ projectRef,
+ clientId: appToEdit?.client_id,
+ clientEndpoint: endpointData?.endpoint,
+ })
}
const handleUploadLogo = () => uploadButtonRef.current?.click()
diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/DeleteOAuthAppModal.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/DeleteOAuthAppModal.tsx
index acd888f8aee..5b228d8ed8b 100644
--- a/apps/studio/components/interfaces/Auth/OAuthApps/DeleteOAuthAppModal.tsx
+++ b/apps/studio/components/interfaces/Auth/OAuthApps/DeleteOAuthAppModal.tsx
@@ -1,8 +1,8 @@
import type { OAuthClient } from '@supabase/supabase-js'
import { useParams } from 'common'
-import type { OAuthServerAppDeleteVariables } from 'data/oauth-server-apps/oauth-server-app-delete-mutation'
-import { useSupabaseClientQuery } from 'hooks/use-supabase-client-query'
+import { useProjectEndpointQuery } from 'data/config/project-endpoint-query'
+import type { OAuthServerAppDeleteVariables } from 'data/oauth-server-apps/oauth-server-app-delete-mutation'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
interface DeleteOAuthAppModalProps {
@@ -22,15 +22,12 @@ export const DeleteOAuthAppModal = ({
}: DeleteOAuthAppModalProps) => {
const { ref: projectRef } = useParams()
- const { data: supabaseClientData } = useSupabaseClientQuery({ projectRef })
-
+ const { data: endpointData } = useProjectEndpointQuery({ projectRef })
const onConfirmDeleteApp = () => {
- if (!selectedApp) return
-
onDelete({
projectRef,
- supabaseClient: supabaseClientData?.supabaseClient,
- clientId: selectedApp.client_id,
+ clientId: selectedApp?.client_id,
+ clientEndpoint: endpointData?.endpoint,
})
}
diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsx
index 037fa676d61..ef134e54851 100644
--- a/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsx
+++ b/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsx
@@ -1,8 +1,8 @@
import type { OAuthClient } from '@supabase/supabase-js'
-import { MoreVertical, Edit, Plus, RotateCw, Search, Trash, X } from 'lucide-react'
+import { Edit, MoreVertical, Plus, RotateCw, Search, Trash, X } from 'lucide-react'
import Link from 'next/link'
-import { useRef, useState } from 'react'
import { parseAsBoolean, useQueryState } from 'nuqs'
+import { useRef, useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
@@ -11,11 +11,11 @@ import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { FilterPopover } from 'components/ui/FilterPopover'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useAuthConfigQuery } from 'data/auth/auth-config-query'
+import { useProjectEndpointQuery } from 'data/config/project-endpoint-query'
import { useOAuthServerAppDeleteMutation } from 'data/oauth-server-apps/oauth-server-app-delete-mutation'
import { useOAuthServerAppRegenerateSecretMutation } from 'data/oauth-server-apps/oauth-server-app-regenerate-secret-mutation'
import { useOAuthServerAppsQuery } from 'data/oauth-server-apps/oauth-server-apps-query'
-import { useSupabaseClientQuery } from 'hooks/use-supabase-client-query'
-import { useQueryStateWithSelect, handleErrorOnDelete } from 'hooks/misc/useQueryStateWithSelect'
+import { handleErrorOnDelete, useQueryStateWithSelect } from 'hooks/misc/useQueryStateWithSelect'
import {
Badge,
Button,
@@ -55,12 +55,8 @@ export const OAuthAppsList = () => {
const [filteredClientTypes, setFilteredClientTypes] = useState<string[]>([])
const deletingOAuthAppIdRef = useRef<string | null>(null)
- const { data: supabaseClientData } = useSupabaseClientQuery({ projectRef })
const { data, isLoading, isError, error } = useOAuthServerAppsQuery(
- {
- projectRef,
- supabaseClient: supabaseClientData?.supabaseClient,
- },
+ { projectRef },
{ enabled: isOAuthServerEnabled }
)
@@ -73,6 +69,8 @@ export const OAuthAppsList = () => {
},
})
+ const { data: endpointData } = useProjectEndpointQuery({ projectRef })
+
const oAuthApps = data?.clients || []
const [showCreateSheet, setShowCreateSheet] = useQueryState(
@@ -108,9 +106,6 @@ export const OAuthAppsList = () => {
},
})
- const handleEditClick = (app: OAuthClient) => setSelectedAppToEdit(app.client_id)
- const handleDeleteClick = (app: OAuthClient) => setSelectedAppToDelete(app.client_id)
-
const [filterString, setFilterString] = useState<string>('')
const filteredOAuthApps = filterOAuthApps({
@@ -259,7 +254,7 @@ export const OAuthAppsList = () => {
<Button
type="text"
className="text-link-table-cell text-sm p-0 hover:bg-transparent title [&>span]:!w-full"
- onClick={() => handleEditClick(app)}
+ onClick={() => setSelectedAppToEdit(app.client_id)}
title={app.client_name}
>
{app.client_name}
@@ -287,7 +282,7 @@ export const OAuthAppsList = () => {
<DropdownMenuItem
className="space-x-2"
onClick={() => {
- handleEditClick(app)
+ setSelectedAppToEdit(app.client_id)
}}
>
<Edit size={12} />
@@ -307,7 +302,7 @@ export const OAuthAppsList = () => {
)}
<DropdownMenuItem
className="space-x-2"
- onClick={() => handleDeleteClick(app)}
+ onClick={() => setSelectedAppToDelete(app.client_id)}
>
<Trash size={12} />
<p>Delete</p>
@@ -363,13 +358,11 @@ export const OAuthAppsList = () => {
confirmLabel="Confirm"
onCancel={() => setShowRegenerateDialog(false)}
onConfirm={() => {
- if (selectedApp?.client_id) {
- regenerateSecret({
- projectRef,
- supabaseClient: supabaseClientData?.supabaseClient,
- clientId: selectedApp.client_id,
- })
- }
+ regenerateSecret({
+ projectRef,
+ clientId: selectedApp?.client_id,
+ clientEndpoint: endpointData?.endpoint,
+ })
setShowRegenerateDialog(false)
}}
>
diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/OAuthServerSettingsForm.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/OAuthServerSettingsForm.tsx
index 611eeef749a..05f7c0b7aa0 100644
--- a/apps/studio/components/interfaces/Auth/OAuthApps/OAuthServerSettingsForm.tsx
+++ b/apps/studio/components/interfaces/Auth/OAuthApps/OAuthServerSettingsForm.tsx
@@ -18,7 +18,6 @@ import { useAuthConfigQuery } from 'data/auth/auth-config-query'
import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
import { useOAuthServerAppsQuery } from 'data/oauth-server-apps/oauth-server-apps-query'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSupabaseClientQuery } from 'hooks/use-supabase-client-query'
import {
Button,
Card,
@@ -100,12 +99,7 @@ export const OAuthServerSettingsForm = () => {
isSuccess: isPermissionsLoaded,
} = useAsyncCheckPermissions(PermissionAction.READ, 'custom_config_gotrue')
- const { data: supabaseClientData } = useSupabaseClientQuery({ projectRef })
-
- const { data: oAuthAppsData } = useOAuthServerAppsQuery({
- projectRef,
- supabaseClient: supabaseClientData?.supabaseClient,
- })
+ const { data: oAuthAppsData } = useOAuthServerAppsQuery({ projectRef })
const oauthApps = oAuthAppsData?.clients || []
diff --git a/apps/studio/data/api-keys/temp-api-keys-query.ts b/apps/studio/data/api-keys/temp-api-keys-query.ts
index 44e821a62e6..0f4de86ef2f 100644
--- a/apps/studio/data/api-keys/temp-api-keys-query.ts
+++ b/apps/studio/data/api-keys/temp-api-keys-query.ts
@@ -1,8 +1,4 @@
-import { useQuery } from '@tanstack/react-query'
-
import { handleError, post } from 'data/fetchers'
-import type { ResponseError, UseCustomQueryOptions } from 'types'
-import { apiKeysKeys } from './keys'
interface getTemporaryAPIKeyVariables {
projectRef?: string
@@ -31,23 +27,3 @@ export async function getTemporaryAPIKey(
if (error) handleError(error)
return data
}
-
-export type TemporaryAPIKeyData = Awaited<ReturnType<typeof getTemporaryAPIKey>>
-
-export const useTemporaryAPIKeyQuery = <TData = TemporaryAPIKeyData>(
- { projectRef }: { projectRef?: string },
- {
- enabled = true,
- ...options
- }: UseCustomQueryOptions<TemporaryAPIKeyData, ResponseError, TData> = {}
-) => {
- // The expiry time is set to 60 seconds in the API.
- const expiry = 60
- return useQuery<TemporaryAPIKeyData, ResponseError, TData>({
- queryKey: apiKeysKeys.temporary(projectRef),
- queryFn: ({ signal }) => getTemporaryAPIKey({ projectRef, expiry }, signal),
- enabled: enabled && typeof projectRef !== 'undefined',
- refetchInterval: expiry * 1000, // convert to ms
- ...options,
- })
-}
diff --git a/apps/studio/data/config/project-endpoint-query.ts b/apps/studio/data/config/project-endpoint-query.ts
new file mode 100644
index 00000000000..3407df5995a
--- /dev/null
+++ b/apps/studio/data/config/project-endpoint-query.ts
@@ -0,0 +1,17 @@
+import { IS_PLATFORM } from 'common'
+import { ProjectSettingsVariables, useProjectSettingsV2Query } from './project-settings-v2-query'
+
+export const useProjectEndpointQuery = ({ projectRef }: ProjectSettingsVariables) => {
+ return useProjectSettingsV2Query(
+ { projectRef },
+ {
+ select: (data) => {
+ const protocol = data?.app_config?.protocol ?? 'https'
+ const endpoint = data?.app_config?.endpoint
+ const clientEndpoint = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}`
+
+ return { endpoint: clientEndpoint }
+ },
+ }
+ )
+}
diff --git a/apps/studio/data/config/project-settings-v2-query.ts b/apps/studio/data/config/project-settings-v2-query.ts
index 4bced094db3..c86950615f7 100644
--- a/apps/studio/data/config/project-settings-v2-query.ts
+++ b/apps/studio/data/config/project-settings-v2-query.ts
@@ -53,8 +53,8 @@ export const useProjectSettingsV2Query = <TData = ProjectSettingsData>(
queryKey: configKeys.settingsV2(projectRef),
queryFn: ({ signal }) => getProjectSettings({ projectRef }, signal),
enabled: enabled && typeof projectRef !== 'undefined',
- refetchInterval(_data) {
- const data = _data as ProjectSettingsData | undefined
+ refetchInterval: (_, query) => {
+ const data = query.state.data
const apiKeys = data?.service_api_keys ?? []
const interval =
canReadAPIKeys && data?.status !== 'INACTIVE' && apiKeys.length === 0 ? 2000 : 0
diff --git a/apps/studio/data/oauth-server-apps/keys.ts b/apps/studio/data/oauth-server-apps/keys.ts
index 34df6f8cca1..d84544f1d2e 100644
--- a/apps/studio/data/oauth-server-apps/keys.ts
+++ b/apps/studio/data/oauth-server-apps/keys.ts
@@ -1,4 +1,5 @@
export const oauthServerAppKeys = {
// temporaryApiKey has to be added to reset the query when it changes
- list: (projectRef: string | undefined) => ['projects', projectRef, 'oauth-server-apps'] as const,
+ list: (projectRef: string | undefined, clientEndpoint: string | undefined) =>
+ ['projects', projectRef, 'oauth-server-apps', clientEndpoint] as const,
}
diff --git a/apps/studio/data/oauth-server-apps/oauth-server-app-create-mutation.ts b/apps/studio/data/oauth-server-apps/oauth-server-app-create-mutation.ts
index 231e5887748..e3b1fc0dffa 100644
--- a/apps/studio/data/oauth-server-apps/oauth-server-app-create-mutation.ts
+++ b/apps/studio/data/oauth-server-apps/oauth-server-app-create-mutation.ts
@@ -1,24 +1,26 @@
-import { CreateOAuthClientParams, SupabaseClient } from '@supabase/supabase-js'
+import { CreateOAuthClientParams } from '@supabase/supabase-js'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { handleError } from 'data/fetchers'
+import { createProjectSupabaseClient } from 'lib/project-supabase-client'
import type { ResponseError, UseCustomMutationOptions } from 'types'
import { oauthServerAppKeys } from './keys'
export type OAuthServerAppCreateVariables = CreateOAuthClientParams & {
- projectRef?: string
- supabaseClient?: SupabaseClient<any>
+ projectRef: string | undefined
+ clientEndpoint: string | undefined
}
export async function createOAuthServerApp({
projectRef,
- supabaseClient,
+ clientEndpoint,
...params
}: OAuthServerAppCreateVariables) {
if (!projectRef) throw new Error('Project reference is required')
- if (!supabaseClient) throw new Error('Supabase client is required')
+ if (!clientEndpoint) throw new Error('Client endpoint is required')
+ const supabaseClient = await createProjectSupabaseClient(projectRef, clientEndpoint)
const { data, error } = await supabaseClient.auth.admin.oauth.createClient(params)
if (error) return handleError(error)
@@ -40,9 +42,9 @@ export const useOAuthServerAppCreateMutation = ({
return useMutation<OAuthAppCreateData, ResponseError, OAuthServerAppCreateVariables>({
mutationFn: (vars) => createOAuthServerApp(vars),
onSuccess: async (data, variables, context) => {
- const { projectRef } = variables
+ const { projectRef, clientEndpoint } = variables
await queryClient.invalidateQueries({
- queryKey: oauthServerAppKeys.list(projectRef),
+ queryKey: oauthServerAppKeys.list(projectRef, clientEndpoint),
})
await onSuccess?.(data, variables, context)
},
diff --git a/apps/studio/data/oauth-server-apps/oauth-server-app-delete-mutation.ts b/apps/studio/data/oauth-server-apps/oauth-server-app-delete-mutation.ts
index c76af7b7621..ec82f0b146c 100644
--- a/apps/studio/data/oauth-server-apps/oauth-server-app-delete-mutation.ts
+++ b/apps/studio/data/oauth-server-apps/oauth-server-app-delete-mutation.ts
@@ -1,28 +1,29 @@
-import { SupabaseClient } from '@supabase/supabase-js'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { handleError } from 'data/fetchers'
+import { createProjectSupabaseClient } from 'lib/project-supabase-client'
import type { ResponseError, UseCustomMutationOptions } from 'types'
import { oauthServerAppKeys } from './keys'
export type OAuthServerAppDeleteVariables = {
- clientId?: string
- projectRef?: string
- supabaseClient?: SupabaseClient<any>
+ clientId: string | undefined
+ projectRef: string | undefined
+ clientEndpoint: string | undefined
}
export async function deleteOAuthServerApp({
projectRef,
- supabaseClient,
+ clientEndpoint,
clientId,
}: OAuthServerAppDeleteVariables) {
if (!projectRef) throw new Error('Project reference is required')
- if (!supabaseClient) throw new Error('Supabase client is required')
+ if (!clientEndpoint) throw new Error('Client endpoint is required')
if (!clientId) throw new Error('Client ID is required')
+ const supabaseClient = await createProjectSupabaseClient(projectRef, clientEndpoint)
const { data, error } = await supabaseClient.auth.admin.oauth.deleteClient(clientId)
- console.log(data, error)
+
if (error) return handleError(error)
return null
}
@@ -42,9 +43,9 @@ export const useOAuthServerAppDeleteMutation = ({
return useMutation<OAuthAppDeleteData, ResponseError, OAuthServerAppDeleteVariables>({
mutationFn: (vars) => deleteOAuthServerApp(vars),
onSuccess: async (data, variables, context) => {
- const { projectRef } = variables
+ const { projectRef, clientEndpoint } = variables
await queryClient.invalidateQueries({
- queryKey: oauthServerAppKeys.list(projectRef),
+ queryKey: oauthServerAppKeys.list(projectRef, clientEndpoint),
})
await onSuccess?.(data, variables, context)
},
diff --git a/apps/studio/data/oauth-server-apps/oauth-server-app-regenerate-secret-mutation.ts b/apps/studio/data/oauth-server-apps/oauth-server-app-regenerate-secret-mutation.ts
index 3409aad8793..62f5a2e2647 100644
--- a/apps/studio/data/oauth-server-apps/oauth-server-app-regenerate-secret-mutation.ts
+++ b/apps/studio/data/oauth-server-apps/oauth-server-app-regenerate-secret-mutation.ts
@@ -1,26 +1,27 @@
-import { SupabaseClient } from '@supabase/supabase-js'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { handleError } from 'data/fetchers'
+import { createProjectSupabaseClient } from 'lib/project-supabase-client'
import type { ResponseError, UseCustomMutationOptions } from 'types'
import { oauthServerAppKeys } from './keys'
export type OAuthServerAppRegenerateSecretVariables = {
- projectRef?: string
- supabaseClient?: SupabaseClient<any>
- clientId: string
+ projectRef: string | undefined
+ clientId: string | undefined
+ clientEndpoint: string | undefined
}
export async function regenerateSecret({
projectRef,
- supabaseClient,
+ clientEndpoint,
clientId,
}: OAuthServerAppRegenerateSecretVariables) {
if (!projectRef) throw new Error('Project reference is required')
- if (!supabaseClient) throw new Error('Supabase client is required')
+ if (!clientEndpoint) throw new Error('Client endpoint is required')
if (!clientId) throw new Error('Oauth app client id is required')
+ const supabaseClient = await createProjectSupabaseClient(projectRef, clientEndpoint)
const { data, error } = await supabaseClient.auth.admin.oauth.regenerateClientSecret(clientId)
if (error) handleError(error)
@@ -50,9 +51,9 @@ export const useOAuthServerAppRegenerateSecretMutation = ({
>({
mutationFn: (vars) => regenerateSecret(vars),
onSuccess: async (data, variables, context) => {
- const { projectRef } = variables
+ const { projectRef, clientEndpoint } = variables
await queryClient.invalidateQueries({
- queryKey: oauthServerAppKeys.list(projectRef),
+ queryKey: oauthServerAppKeys.list(projectRef, clientEndpoint),
})
await onSuccess?.(data, variables, context)
},
diff --git a/apps/studio/data/oauth-server-apps/oauth-server-app-update-mutation.ts b/apps/studio/data/oauth-server-apps/oauth-server-app-update-mutation.ts
index e3d6b7bd41e..282205d7eb6 100644
--- a/apps/studio/data/oauth-server-apps/oauth-server-app-update-mutation.ts
+++ b/apps/studio/data/oauth-server-apps/oauth-server-app-update-mutation.ts
@@ -1,26 +1,29 @@
-import { UpdateOAuthClientParams, SupabaseClient } from '@supabase/supabase-js'
+import { UpdateOAuthClientParams } from '@supabase/supabase-js'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { handleError } from 'data/fetchers'
+import { createProjectSupabaseClient } from 'lib/project-supabase-client'
import type { ResponseError, UseCustomMutationOptions } from 'types'
import { oauthServerAppKeys } from './keys'
export type OAuthServerAppUpdateVariables = UpdateOAuthClientParams & {
- clientId: string
- projectRef?: string
- supabaseClient?: SupabaseClient<any>
+ clientId: string | undefined
+ projectRef: string | undefined
+ clientEndpoint: string | undefined
}
export async function updateOAuthServerApp({
clientId,
projectRef,
- supabaseClient,
+ clientEndpoint,
...params
}: OAuthServerAppUpdateVariables) {
if (!projectRef) throw new Error('Project reference is required')
- if (!supabaseClient) throw new Error('Supabase client is required')
+ if (!clientEndpoint) throw new Error('Client endpoint is required')
+ if (!clientId) throw new Error('Client ID is required')
+ const supabaseClient = await createProjectSupabaseClient(projectRef, clientEndpoint)
const { data, error } = await supabaseClient.auth.admin.oauth.updateClient(clientId, params)
if (error) return handleError(error)
@@ -42,9 +45,9 @@ export const useOAuthServerAppUpdateMutation = ({
return useMutation<OAuthAppUpdateData, ResponseError, OAuthServerAppUpdateVariables>({
mutationFn: (vars) => updateOAuthServerApp(vars),
onSuccess: async (data, variables, context) => {
- const { projectRef } = variables
+ const { projectRef, clientEndpoint } = variables
await queryClient.invalidateQueries({
- queryKey: oauthServerAppKeys.list(projectRef),
+ queryKey: oauthServerAppKeys.list(projectRef, clientEndpoint),
})
await onSuccess?.(data, variables, context)
},
diff --git a/apps/studio/data/oauth-server-apps/oauth-server-apps-query.ts b/apps/studio/data/oauth-server-apps/oauth-server-apps-query.ts
index 9e8348da037..4fc560c0037 100644
--- a/apps/studio/data/oauth-server-apps/oauth-server-apps-query.ts
+++ b/apps/studio/data/oauth-server-apps/oauth-server-apps-query.ts
@@ -1,14 +1,14 @@
-import { SupabaseClient } from '@supabase/supabase-js'
import { useQuery } from '@tanstack/react-query'
import { components } from 'api-types'
+import { useProjectEndpointQuery } from 'data/config/project-endpoint-query'
import { handleError } from 'data/fetchers'
+import { createProjectSupabaseClient } from 'lib/project-supabase-client'
import type { ResponseError, UseCustomQueryOptions } from 'types'
import { oauthServerAppKeys } from './keys'
export type OAuthServerAppsVariables = {
- projectRef?: string
- supabaseClient?: SupabaseClient<any>
+ projectRef: string | undefined
page?: number
}
@@ -18,11 +18,13 @@ export type OAuthApp = components['schemas']['OAuthAppResponse']
export async function getOAuthServerApps({
projectRef,
- supabaseClient,
+ clientEndpoint,
page = 1,
-}: OAuthServerAppsVariables) {
+}: OAuthServerAppsVariables & { clientEndpoint: string | undefined }) {
if (!projectRef) throw new Error('Project reference is required')
- if (!supabaseClient) throw new Error('Supabase client is required')
+ if (!clientEndpoint) throw new Error('Client endpoint is required')
+
+ const supabaseClient = await createProjectSupabaseClient(projectRef, clientEndpoint)
const { data, error } = await supabaseClient.auth.admin.oauth.listClients({
page,
@@ -37,16 +39,21 @@ export type OAuthServerAppsData = Awaited<ReturnType<typeof getOAuthServerApps>>
export type OAuthServerAppsError = ResponseError
export const useOAuthServerAppsQuery = <TData = OAuthServerAppsData>(
- { projectRef, supabaseClient }: OAuthServerAppsVariables,
+ { projectRef }: OAuthServerAppsVariables,
{
enabled = true,
...options
}: UseCustomQueryOptions<OAuthServerAppsData, OAuthServerAppsError, TData> = {}
) => {
+ const { data: endpointData } = useProjectEndpointQuery({
+ projectRef,
+ })
+ const clientEndpoint = endpointData?.endpoint
+
return useQuery<OAuthServerAppsData, OAuthServerAppsError, TData>({
- queryKey: oauthServerAppKeys.list(projectRef),
- queryFn: () => getOAuthServerApps({ projectRef, supabaseClient }),
- enabled: enabled && typeof projectRef !== 'undefined' && !!supabaseClient,
+ queryKey: oauthServerAppKeys.list(projectRef, clientEndpoint),
+ queryFn: () => getOAuthServerApps({ projectRef, clientEndpoint }),
+ enabled: enabled && typeof projectRef !== 'undefined' && !!clientEndpoint,
...options,
})
}
diff --git a/apps/studio/hooks/use-supabase-client-query.ts b/apps/studio/hooks/use-supabase-client-query.ts
deleted file mode 100644
index 032214560bc..00000000000
--- a/apps/studio/hooks/use-supabase-client-query.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { createClient } from '@supabase/supabase-js'
-import { useQuery } from '@tanstack/react-query'
-
-import { useTemporaryAPIKeyQuery } from 'data/api-keys/temp-api-keys-query'
-import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
-
-const getSupabaseClient = ({
- projectRef,
- endpoint,
- temporaryApiKey,
-}: {
- projectRef?: string
- endpoint?: string
- temporaryApiKey?: string
-}) => {
- if (!projectRef) {
- return undefined
- }
- if (!endpoint) {
- return undefined
- }
-
- if (temporaryApiKey === undefined) {
- return undefined
- }
-
- const supabaseClient = createClient(endpoint, temporaryApiKey)
-
- return { supabaseClient }
-}
-
-/**
- * The client uses a temporary API key to authenticate requests. The API key expires after one hour which may cause
- * 401 errors for all requests made with the client. It's easily fixable by refreshing the page.
- */
-export const useSupabaseClientQuery = (
- { projectRef }: { projectRef?: string },
- { enabled = true, ...options } = {}
-) => {
- const { data: settings } = useProjectSettingsV2Query({ projectRef })
- const { data: temporaryApiKeyData } = useTemporaryAPIKeyQuery({ projectRef })
-
- const endpoint = settings
- ? `${settings?.app_config?.protocol ?? 'https'}://${settings?.app_config?.endpoint}`
- : undefined
- const temporaryApiKey = temporaryApiKeyData?.api_key
-
- return useQuery({
- queryKey: [projectRef, 'supabase-client', endpoint, temporaryApiKey],
- queryFn: () => getSupabaseClient({ projectRef, endpoint, temporaryApiKey }),
- enabled: enabled && typeof projectRef !== 'undefined' && !!endpoint && !!temporaryApiKey,
- ...options,
- })
-}
diff --git a/apps/studio/lib/project-supabase-client.ts b/apps/studio/lib/project-supabase-client.ts
new file mode 100644
index 00000000000..7031cb4c6f2
--- /dev/null
+++ b/apps/studio/lib/project-supabase-client.ts
@@ -0,0 +1,28 @@
+import { createClient } from '@supabase/supabase-js'
+import { getOrRefreshTemporaryApiKey } from 'data/api-keys/temp-api-keys-utils'
+
+/**
+ * Creates a Supabase client bound to a specific project. It uses temporary API key.
+ */
+export async function createProjectSupabaseClient(projectRef: string, clientEndpoint: string) {
+ try {
+ const { apiKey } = await getOrRefreshTemporaryApiKey(projectRef)
+
+ return createClient(clientEndpoint, apiKey, {
+ auth: {
+ persistSession: false,
+ autoRefreshToken: false,
+ detectSessionInUrl: false,
+ storage: {
+ getItem: (key) => {
+ return null
+ },
+ setItem: (key, value) => {},
+ removeItem: (key) => {},
+ },
+ },
+ })
+ } catch (error) {
+ throw error
+ }
+}
diff --git a/apps/studio/state/storage-explorer.tsx b/apps/studio/state/storage-explorer.tsx
index b0374992a6e..43e30e45029 100644
--- a/apps/studio/state/storage-explorer.tsx
+++ b/apps/studio/state/storage-explorer.tsx
@@ -1,3 +1,4 @@
+import { BlobReader, BlobWriter, ZipWriter } from '@zip.js/zip.js'
import { capitalize, chunk, compact, find, findIndex, has, isObject, uniq, uniqBy } from 'lodash'
import { createContext, PropsWithChildren, useContext, useEffect, useState } from 'react'
import { useLatest } from 'react-use'
@@ -5,8 +6,6 @@ import { toast } from 'sonner'
import * as tus from 'tus-js-client'
import { proxy, useSnapshot } from 'valtio'
-import { createClient } from '@supabase/supabase-js'
-import { BlobReader, BlobWriter, ZipWriter } from '@zip.js/zip.js'
import { LOCAL_STORAGE_KEYS } from 'common'
import {
inverseValidObjectKeyRegex,
@@ -37,7 +36,7 @@ import { convertFromBytes } from 'components/interfaces/Storage/StorageSettings/
import { InlineLink } from 'components/ui/InlineLink'
import { getOrRefreshTemporaryApiKey } from 'data/api-keys/temp-api-keys-utils'
import { configKeys } from 'data/config/keys'
-import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { useProjectEndpointQuery } from 'data/config/project-endpoint-query'
import { ProjectStorageConfigResponse } from 'data/config/project-storage-config-query'
import { getQueryClient } from 'data/query-client'
import { deleteBucketObject } from 'data/storage/bucket-object-delete-mutation'
@@ -49,6 +48,7 @@ import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'
import { tryParseJson } from 'lib/helpers'
import { lookupMime } from 'lib/mime'
+import { createProjectSupabaseClient } from 'lib/project-supabase-client'
import { Button, SONNER_DEFAULT_DURATION, SonnerProgress } from 'ui'
type UploadProgress = {
@@ -76,29 +76,6 @@ if (typeof window !== 'undefined') {
abortController = new AbortController()
}
-async function createSupabaseClient(projectRef: string, clientEndpoint: string) {
- try {
- const { apiKey } = await getOrRefreshTemporaryApiKey(projectRef)
-
- return createClient(clientEndpoint, apiKey, {
- auth: {
- persistSession: false,
- autoRefreshToken: false,
- detectSessionInUrl: false,
- storage: {
- getItem: (key) => {
- return null
- },
- setItem: (key, value) => {},
- removeItem: (key) => {},
- },
- },
- })
- } catch (error) {
- throw error
- }
-}
-
function createStorageExplorerState({
projectRef,
connectionString,
@@ -345,7 +322,7 @@ function createStorageExplorerState({
const formattedPathToEmptyPlaceholderFile =
pathToFolder.length > 0 ? `${pathToFolder}/${emptyPlaceholderFile}` : emptyPlaceholderFile
- const client = await createSupabaseClient(state.projectRef, clientEndpoint)
+ const client = await createProjectSupabaseClient(state.projectRef, clientEndpoint)
await client.storage
.from(state.selectedBucket.name)
.upload(
@@ -596,7 +573,7 @@ function createStorageExplorerState({
if (data.length === 0) {
const prefixToPlaceholder = `${parentFolderPrefix}/${EMPTY_FOLDER_PLACEHOLDER_FILE_NAME}`
- const client = await createSupabaseClient(state.projectRef, clientEndpoint)
+ const client = await createProjectSupabaseClient(state.projectRef, clientEndpoint)
await client.storage
.from(state.selectedBucket.name)
.upload(prefixToPlaceholder, new File([], EMPTY_FOLDER_PLACEHOLDER_FILE_NAME))
@@ -831,11 +808,8 @@ function createStorageExplorerState({
>(async (resolve) => {
try {
// Get authenticated Supabase client for Storage API access
- const client = await createSupabaseClient(state.projectRef, clientEndpoint)
+ const client = await createProjectSupabaseClient(state.projectRef, clientEndpoint)
- if (!client) {
- throw new Error('Supabase client not available')
- }
// Use Storage API directly instead of Management API to avoid throttling
const { data, error } = await client.storage
.from(state.selectedBucket.id)
@@ -1517,10 +1491,7 @@ function createStorageExplorerState({
const toastId = showToast ? toast.loading(`Retrieving ${fileName}...`) : undefined
try {
- const client = await createSupabaseClient(state.projectRef, clientEndpoint)
- if (!client) {
- throw new Error('Supabase client not available')
- }
+ const client = await createProjectSupabaseClient(state.projectRef, clientEndpoint)
// Use Storage API directly instead of Management API to avoid throttling
const { data, error } = await client.storage
@@ -1564,10 +1535,7 @@ function createStorageExplorerState({
if (!file.path) return false
try {
- const client = await createSupabaseClient(state.projectRef, clientEndpoint)
- if (!client) {
- throw new Error('Supabase client not available')
- }
+ const client = await createProjectSupabaseClient(state.projectRef, clientEndpoint)
const { data, error } = await client.storage
.from(state.selectedBucket.id)
@@ -1902,15 +1870,10 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
const [state, setState] = useState(() => createStorageExplorerState(DEFAULT_STATE_CONFIG))
const stateRef = useLatest(state)
- const { data: settings, isSuccess: isSuccessSettings } = useProjectSettingsV2Query({
+ const { data: endpointData, isSuccess: isSuccessSettings } = useProjectEndpointQuery({
projectRef: project?.ref,
})
- const protocol = settings?.app_config?.protocol ?? 'https'
- const endpoint = settings?.app_config?.endpoint
- const resumableUploadUrl = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}/storage/v1/upload/resumable`
- const clientEndpoint = `${IS_PLATFORM ? 'https' : protocol}://${endpoint}`
-
// [Joshen] JFYI opting with the useEffect here as the storage explorer state was being loaded
// before the project details were ready, hence the store kept returning project ref as undefined
// Can be verified when we're saving the storage explorer preferences into local storage, that ref is undefined
@@ -1921,6 +1884,8 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
const storeAlreadyLoaded = state.projectRef === project?.ref
if (!isPaused && hasDataReady && !storeAlreadyLoaded && isSuccessSettings) {
+ const clientEndpoint = endpointData.endpoint
+ const resumableUploadUrl = `${clientEndpoint}/storage/v1/upload/resumable`
setState(
createStorageExplorerState({
projectRef: project?.ref ?? '',
@@ -1936,9 +1901,7 @@ export const StorageExplorerStateContextProvider = ({ children }: PropsWithChild
project?.connectionString,
stateRef,
isPaused,
- resumableUploadUrl,
- protocol,
- endpoint,
+ endpointData?.endpoint,
isSuccessSettings,
])