The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: oauth apps update (#40776)
Francesco Sansalvadore5ae4a2f8cb70
diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/CreateOAuthAppSheet.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/CreateOAuthAppSheet.tsxdeleted file mode 100644index 3eae0ae5c5b..00000000000--- a/apps/studio/components/interfaces/Auth/OAuthApps/CreateOAuthAppSheet.tsx+++ /dev/null@@ -1,306 +0,0 @@-import { zodResolver } from '@hookform/resolvers/zod'-import type { CreateOAuthClientParams, OAuthClient } from '@supabase/supabase-js'-import { Plus, Trash2, X } from 'lucide-react'-import Link from 'next/link'-import { useEffect } from 'react'-import { useFieldArray, useForm } from 'react-hook-form'-import { toast } from 'sonner'-import * as z from 'zod'--import { useParams } from 'common'-import { useOAuthServerAppCreateMutation } from 'data/oauth-server-apps/oauth-server-app-create-mutation'-import { useSupabaseClientQuery } from 'hooks/use-supabase-client-query'-import {- Button,- FormControl_Shadcn_,- FormDescription_Shadcn_,- FormField_Shadcn_,- FormItem_Shadcn_,- FormLabel_Shadcn_,- FormMessage_Shadcn_,- Form_Shadcn_,- Input_Shadcn_,- Separator,- Sheet,- SheetClose,- SheetContent,- SheetFooter,- SheetHeader,- SheetSection,- SheetTitle,- Switch,- cn,-} from 'ui'-import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'--interface CreateOAuthAppSheetProps {- visible: boolean- onSuccess: (app: OAuthClient) => void- onCancel: () => void-}--const FormSchema = z.object({- name: z- .string()- .min(1, 'Please provide a name for your OAuth app')- .max(100, 'Name must be less than 100 characters'),- type: z.enum(['manual', 'dynamic']).default('manual'),- // scope: z.string().min(1, 'Please select a scope'),- redirect_uris: z- .object({- value: z.string().trim().url('Please provide a valid URL'),- })- .array()- .min(1, 'At least one redirect URI is required'),- is_public: z.boolean().default(false),-})--const FORM_ID = 'create-or-update-oauth-app-form'--const initialValues = {- name: '',- type: 'manual' as const,- // scope: 'email',- redirect_uris: [{ value: '' }],- is_public: false,-}--export const CreateOAuthAppSheet = ({ visible, onSuccess, onCancel }: CreateOAuthAppSheetProps) => {- const { ref: projectRef } = useParams()-- const form = useForm<z.infer<typeof FormSchema>>({- resolver: zodResolver(FormSchema),- defaultValues: initialValues,- })-- const {- fields: redirectUriFields,- append: appendRedirectUri,- remove: removeRedirectUri,- } = useFieldArray({- name: 'redirect_uris',- control: form.control,- })-- const { data: supabaseClientData } = useSupabaseClientQuery({ projectRef })-- const { mutateAsync: createOAuthApp, isPending: isCreating } = useOAuthServerAppCreateMutation({- onSuccess: (data) => {- toast.success(`Successfully created OAuth app "${data.client_name}"`)- onSuccess(data)- },- onError: (error) => {- toast.error(error.message)- },- })-- useEffect(() => {- if (visible) {- form.reset(initialValues)- }- }, [visible])-- const onSubmit = async (data: z.infer<typeof FormSchema>) => {- // Filter out empty redirect URIs- const validRedirectUris = data.redirect_uris- .map((uri) => uri.value.trim())- .filter((uri) => uri !== '')-- const payload: CreateOAuthClientParams = {- client_name: data.name,- client_uri: '',- // scope: data.scope,- redirect_uris: validRedirectUris,- }-- createOAuthApp({- projectRef,- supabaseClient: supabaseClientData?.supabaseClient,- ...payload,- })- }-- const onClose = () => {- form.reset(initialValues)- onCancel()- }-- return (- <>- <Sheet open={visible} onOpenChange={() => onCancel()}>- <SheetContent- size="default"- showClose={false}- className="flex flex-col gap-0"- tabIndex={undefined}- >- <SheetHeader>- <div className="flex flex-row gap-3 items-center">- <SheetClose- className={cn(- 'text-muted hover:text ring-offset-background transition-opacity hover:opacity-100',- 'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',- 'disabled:pointer-events-none data-[state=open]:bg-secondary',- 'transition'- )}- >- <X className="h-3 w-3" />- <span className="sr-only">Close</span>- </SheetClose>- <SheetTitle className="truncate">Create a new OAuth app</SheetTitle>- </div>- </SheetHeader>- <SheetSection className="overflow-auto flex-grow px-0">- <Form_Shadcn_ {...form}>- <form className="space-y-6" onSubmit={form.handleSubmit(onSubmit)} id={FORM_ID}>- <FormField_Shadcn_- control={form.control}- name="name"- render={({ field }) => (- <FormItemLayout label="Name" className={'px-5'}>- <FormControl_Shadcn_>- <Input_Shadcn_ {...field} placeholder="My OAuth App" />- </FormControl_Shadcn_>- </FormItemLayout>- )}- />-- {/* <FormField_Shadcn_- control={form.control}- name="scope"- rules={{ required: true }}- render={({ field }) => (- <FormItemLayout- label="Scope"- layout="vertical"- description={- <>- Select the permissions your app will request from users.{' '}- <Link- href="https://supabase.com/docs/guides/auth/oauth/oauth-apps#scope"- target="_blank"- rel="noreferrer"- className="text-foreground-light underline hover:text-foreground transition"- >- Learn more- </Link>- </>- }- className={'px-5'}- >- <FormControl_Shadcn_>- <Select_Shadcn_ value={field.value} onValueChange={field.onChange}>- <SelectTrigger_Shadcn_ className="w-full">- <SelectValue_Shadcn_ placeholder="Select scope..." />- </SelectTrigger_Shadcn_>- <SelectContent_Shadcn_>- {OAUTH_APP_SCOPE_OPTIONS.map((scope) => (- <SelectItem_Shadcn_ key={scope.value} value={scope.value}>- {scope.name}- </SelectItem_Shadcn_>- ))}- </SelectContent_Shadcn_>- </Select_Shadcn_>- </FormControl_Shadcn_>- </FormItemLayout>- )}- /> */}-- <div className="px-5 gap-2 flex flex-col">- <FormLabel_Shadcn_ className="text-foreground">Redirect URIs</FormLabel_Shadcn_>-- <div className="space-y-2">- {redirectUriFields.map((fieldItem, index) => (- <FormField_Shadcn_- control={form.control}- key={fieldItem.id}- name={`redirect_uris.${index}.value`}- render={({ field: inputField }) => (- <FormItem_Shadcn_>- <div className="flex flex-row gap-2">- <FormControl_Shadcn_>- <Input_Shadcn_- {...inputField}- placeholder={'https://example.com/callback'}- onChange={(e) => {- inputField.onChange(e)- }}- />- </FormControl_Shadcn_>- {redirectUriFields.length > 1 && (- <Button- type="default"- size="tiny"- className="h-[34px]"- icon={<Trash2 size={14} />}- onClick={() => removeRedirectUri(index)}- />- )}- </div>- <FormMessage_Shadcn_ />- </FormItem_Shadcn_>- )}- />- ))}- </div>- <div>- <Button- type="default"- icon={<Plus strokeWidth={1.5} />}- onClick={() => appendRedirectUri({ value: '' })}- >- Add redirect URI- </Button>- </div>- <FormDescription_Shadcn_ className="text-foreground-lighter">- URLs where users will be redirected after authentication.- </FormDescription_Shadcn_>- </div>-- <Separator />- <FormField_Shadcn_- control={form.control}- name="is_public"- render={({ field }) => (- <FormItemLayout- label="Public"- layout="flex"- description={- <>- If enabled, the Authorization Code with PKCE (Proof Key for Code Exchange)- flow can be used, particularly beneficial for applications that cannot- securely store Client Secrets, such as native and mobile apps.{' '}- <Link- href="https://supabase.com/docs/guides/auth/oauth/public-oauth-apps"- target="_blank"- rel="noreferrer"- className="text-foreground-light underline hover:text-foreground transition"- >- Learn more- </Link>- </>- }- className={'px-5'}- >- <FormControl_Shadcn_>- <Switch checked={field.value} onCheckedChange={field.onChange} />- </FormControl_Shadcn_>- </FormItemLayout>- )}- />- </form>- </Form_Shadcn_>- </SheetSection>- <SheetFooter>- <Button type="default" disabled={isCreating} onClick={onClose}>- Cancel- </Button>- <Button htmlType="submit" form={FORM_ID} loading={isCreating}>- Create app- </Button>- </SheetFooter>- </SheetContent>- </Sheet>- </>- )-}diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsxnew file mode 100644index 00000000000..ba69df9be79--- /dev/null+++ b/apps/studio/components/interfaces/Auth/OAuthApps/CreateOrUpdateOAuthAppSheet.tsx@@ -0,0 +1,535 @@+import { zodResolver } from '@hookform/resolvers/zod'+import type {+ CreateOAuthClientParams,+ OAuthClient,+ UpdateOAuthClientParams,+} from '@supabase/supabase-js'+import { Plus, Trash2, Upload, X } from 'lucide-react'+import Link from 'next/link'+import { type ChangeEvent, useEffect, useRef, useState } from 'react'+import { useFieldArray, useForm } from 'react-hook-form'+import { toast } from 'sonner'+import * as z from 'zod'++import { useParams } from 'common'+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_,+ FormDescription_Shadcn_,+ FormField_Shadcn_,+ FormItem_Shadcn_,+ FormLabel_Shadcn_,+ FormMessage_Shadcn_,+ Form_Shadcn_,+ Input_Shadcn_,+ Separator,+ Sheet,+ SheetClose,+ SheetContent,+ SheetFooter,+ SheetHeader,+ SheetSection,+ SheetTitle,+ Switch,+ cn,+} from 'ui'+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'+import { Input } from 'ui-patterns/DataInputs/Input'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import Panel from 'components/ui/Panel'++interface CreateOrUpdateOAuthAppSheetProps {+ visible: boolean+ appToEdit?: OAuthClient+ onSuccess: (app: OAuthClient) => void+ onCancel: () => void+}++const FormSchema = z.object({+ name: z+ .string()+ .min(1, 'Please provide a name for your OAuth app')+ .max(100, 'Name must be less than 100 characters'),+ type: z.enum(['manual', 'dynamic']).default('manual'),+ redirect_uris: z+ .object({+ value: z.string().trim().url('Please provide a valid URL'),+ })+ .array()+ .min(1, 'At least one redirect URI is required'),+ client_type: z.enum(['public', 'confidential']).default('confidential'),+ client_id: z.string().optional(),+ client_secret: z.string().optional(),+ logo_uri: z.string().optional(),+})++const FORM_ID = 'create-or-update-oauth-app-form'++const initialValues = {+ name: '',+ type: 'manual' as const,+ redirect_uris: [{ value: '' }],+ client_type: 'confidential' as const,+ client_id: '',+ client_secret: '',+ logo_uri: '',+}++export const CreateOrUpdateOAuthAppSheet = ({+ visible,+ appToEdit,+ onSuccess,+ onCancel,+}: CreateOrUpdateOAuthAppSheetProps) => {+ const { ref: projectRef } = useParams()+ const isEditMode = !!appToEdit+ const [showRegenerateDialog, setShowRegenerateDialog] = useState(false)+ const uploadButtonRef = useRef<HTMLInputElement>(null)+ const [logoFile, setLogoFile] = useState<File>()+ const [logoUrl, setLogoUrl] = useState<string>()+ const [logoRemoved, setLogoRemoved] = useState(false)+ const hasLogo = logoUrl !== undefined+ const isPublicClient = appToEdit?.client_type === 'public'++ const form = useForm<z.infer<typeof FormSchema>>({+ resolver: zodResolver(FormSchema),+ defaultValues: initialValues,+ })++ const {+ fields: redirectUriFields,+ append: appendRedirectUri,+ remove: removeRedirectUri,+ } = useFieldArray({+ name: 'redirect_uris',+ control: form.control,+ })++ const { data: supabaseClientData } = useSupabaseClientQuery({ projectRef })+ const { mutateAsync: 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({+ onSuccess: (data) => {+ toast.success(`Successfully updated OAuth app "${data.client_name}"`)+ onSuccess(data)+ },+ onError: (error) => {+ toast.error(error.message)+ },+ })+ const { mutateAsync: regenerateSecret, isPending: isRegenerating } =+ useOAuthServerAppRegenerateSecretMutation({+ onSuccess: (data) => {+ if (data) {+ toast.success(`Successfully regenerated client secret for "${appToEdit?.client_name}"`)+ onSuccess(data)+ setShowRegenerateDialog(false)+ }+ },+ onError: (error) => {+ toast.error(error.message)+ },+ })++ useEffect(() => {+ if (visible) {+ setLogoFile(undefined)+ setLogoRemoved(false)+ if (appToEdit) {+ form.reset({+ name: appToEdit.client_name,+ type: 'manual' as const,+ redirect_uris:+ appToEdit.redirect_uris && appToEdit.redirect_uris.length > 0+ ? appToEdit.redirect_uris.map((uri) => ({ value: uri }))+ : [{ value: '' }],+ client_type: appToEdit.client_type,+ client_id: appToEdit.client_id,+ client_secret: '****************************************************************',+ logo_uri: appToEdit.logo_uri || undefined,+ })+ setLogoUrl(appToEdit.logo_uri || undefined)+ } else {+ form.reset(initialValues)+ setLogoUrl(undefined)+ }+ }+ }, [visible, appToEdit, form])++ const onFileUpload = async (event: ChangeEvent<HTMLInputElement>) => {+ event.persist()+ const files = event.target.files+ if (files && files.length > 0) {+ const file = files[0]+ setLogoFile(file)+ setLogoUrl(URL.createObjectURL(file))+ setLogoRemoved(false)+ event.target.value = ''+ }+ }++ const onSubmit = async (data: z.infer<typeof FormSchema>) => {+ const validRedirectUris = data.redirect_uris+ .map((uri) => uri.value.trim())+ .filter((uri) => uri !== '')++ let uploadedLogoUri: string | undefined = undefined++ if (logoRemoved) {+ uploadedLogoUri = ''+ } else if (logoFile) {+ const reader = new FileReader()+ uploadedLogoUri = await new Promise<string>((resolve) => {+ reader.onloadend = () => resolve(reader.result as string)+ reader.readAsDataURL(logoFile)+ })+ } else if (logoUrl) {+ uploadedLogoUri = logoUrl+ }++ if (isEditMode && appToEdit) {+ const payload: UpdateOAuthClientParams = {+ client_name: data.name,+ redirect_uris: validRedirectUris,+ logo_uri: uploadedLogoUri,+ }++ updateOAuthApp({+ projectRef,+ supabaseClient: supabaseClientData?.supabaseClient,+ clientId: appToEdit.client_id,+ ...payload,+ })+ } else {+ const payload: CreateOAuthClientParams & { logo_uri?: string; client_type?: string } = {+ client_name: data.name,+ client_uri: '',+ client_type: data.client_type,+ redirect_uris: validRedirectUris,+ logo_uri: uploadedLogoUri || undefined,+ }++ createOAuthApp({+ projectRef,+ supabaseClient: supabaseClientData?.supabaseClient,+ ...payload,+ })+ }+ }++ const onClose = () => {+ form.reset(initialValues)+ onCancel()+ }++ const handleRegenerateSecret = () => {+ setShowRegenerateDialog(true)+ }++ const handleConfirmRegenerate = () => {+ if (appToEdit?.client_id) {+ regenerateSecret({+ projectRef,+ supabaseClient: supabaseClientData?.supabaseClient,+ clientId: appToEdit.client_id,+ })+ }+ }++ const handleUploadLogo = () => uploadButtonRef.current?.click()+ const handleRemoveLogo = () => {+ setLogoFile(undefined)+ setLogoUrl(undefined)+ setLogoRemoved(true)+ }++ return (+ <>+ <Sheet open={visible} onOpenChange={() => onCancel()}>+ <SheetContent+ size="lg"+ showClose={false}+ className="flex flex-col gap-0"+ tabIndex={undefined}+ >+ <SheetHeader>+ <div className="flex flex-row gap-3 items-center">+ <SheetClose+ className={cn(+ 'text-muted hover:text ring-offset-background transition-opacity hover:opacity-100',+ 'focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',+ 'disabled:pointer-events-none data-[state=open]:bg-secondary',+ 'transition'+ )}+ >+ <X className="h-3 w-3" />+ <span className="sr-only">Close</span>+ </SheetClose>+ <SheetTitle className="truncate">+ {isEditMode ? 'Update OAuth app' : 'Create a new OAuth app'}+ </SheetTitle>+ </div>+ </SheetHeader>+ <SheetSection className="overflow-auto flex-grow px-0">+ <Form_Shadcn_ {...form}>+ <form className="space-y-6" onSubmit={form.handleSubmit(onSubmit)} id={FORM_ID}>+ <div className="px-5 flex items-start justify-between gap-4">+ <div className="flex-grow space-y-4">+ <FormField_Shadcn_+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItemLayout label="Name">+ <FormControl_Shadcn_>+ <Input_Shadcn_ {...field} placeholder="My OAuth App" />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ <FormField_Shadcn_+ control={form.control}+ name="logo_uri"+ render={() => (+ <FormItemLayout label="Logo" description="Upload a logo for your OAuth app">+ <FormControl_Shadcn_>+ <div className="flex gap-4 items-center">+ <button+ type="button"+ onClick={handleUploadLogo}+ className={cn(+ 'flex items-center justify-center h-10 w-10 shrink-0 text-foreground-lighter hover:text-foreground-light overflow-hidden rounded-full bg-cover border hover:border-strong'+ )}+ style={{+ backgroundImage: logoUrl ? `url("${logoUrl}")` : 'none',+ }}+ >+ {!hasLogo && <Upload size={14} />}+ </button>+ <div className="flex gap-2 items-center">+ <Button+ type="default"+ size="tiny"+ icon={<Upload size={14} />}+ onClick={handleUploadLogo}+ >+ Upload+ </Button>+ {hasLogo && (+ <Button+ type="default"+ size="tiny"+ icon={<Trash2 size={12} />}+ onClick={handleRemoveLogo}+ />+ )}+ </div>+ <input+ type="file"+ ref={uploadButtonRef}+ className="hidden"+ accept="image/png, image/jpeg"+ onChange={onFileUpload}+ />+ </div>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </div>+ </div>++ {isEditMode && appToEdit && (+ <>+ <Separator />+ <div className="px-5">+ <Panel>+ <Panel.Content className="space-y-2">+ <FormField_Shadcn_+ control={form.control}+ name="client_id"+ render={() => (+ <FormItemLayout label="Client ID">+ <FormControl_Shadcn_>+ <Input+ copy+ readOnly+ className="input-mono"+ value={appToEdit.client_id}+ onChange={() => {}}+ onCopy={() => toast.success('Client ID copied to clipboard')}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ {!isPublicClient && (+ <>+ <FormField_Shadcn_+ control={form.control}+ name="client_secret"+ render={() => (+ <FormItemLayout+ label="Client Secret"+ description="Client secret is hidden for security. Use the regenerate button to create a new one."+ >+ <FormControl_Shadcn_>+ <Input+ readOnly+ type="password"+ className="input-mono"+ value="****************************************************************"+ onChange={() => {}}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />++ <Button+ type="default"+ onClick={handleRegenerateSecret}+ className="w-full"+ disabled={isRegenerating}+ >+ Regenerate Client Secret+ </Button>+ </>+ )}+ </Panel.Content>+ </Panel>+ </div>+ </>+ )}++ <div className="px-5 gap-2 flex flex-col">+ <FormLabel_Shadcn_ className="text-foreground">Redirect URIs</FormLabel_Shadcn_>++ <div className="space-y-2">+ {redirectUriFields.map((fieldItem, index) => (+ <FormField_Shadcn_+ control={form.control}+ key={fieldItem.id}+ name={`redirect_uris.${index}.value`}+ render={({ field: inputField }) => (+ <FormItem_Shadcn_>+ <div className="flex flex-row gap-2">+ <FormControl_Shadcn_>+ <Input_Shadcn_+ {...inputField}+ placeholder={'https://example.com/callback'}+ onChange={(e) => {+ inputField.onChange(e)+ }}+ />+ </FormControl_Shadcn_>+ {redirectUriFields.length > 1 && (+ <Button+ type="default"+ size="tiny"+ className="h-[34px]"+ icon={<Trash2 size={12} />}+ onClick={() => removeRedirectUri(index)}+ />+ )}+ </div>+ <FormMessage_Shadcn_ />+ </FormItem_Shadcn_>+ )}+ />+ ))}+ </div>+ <div>+ <Button+ type="default"+ icon={<Plus strokeWidth={1.5} />}+ onClick={() => appendRedirectUri({ value: '' })}+ >+ Add redirect URI+ </Button>+ </div>+ <FormDescription_Shadcn_ className="text-foreground-lighter">+ URLs where users will be redirected after authentication.+ </FormDescription_Shadcn_>+ </div>++ <Separator />+ <FormField_Shadcn_+ control={form.control}+ name="client_type"+ render={({ field }) => (+ <FormItemLayout+ label="Public Client"+ layout="flex"+ description={+ <>+ If enabled, the Authorization Code with PKCE (Proof Key for Code Exchange)+ flow can be used, particularly beneficial for applications that cannot+ securely store Client Secrets, such as native and mobile apps. This cannot+ be changed after creation.{' '}+ <Link+ href="https://supabase.com/docs/guides/auth/oauth/public-oauth-apps"+ target="_blank"+ rel="noreferrer"+ className="text-foreground-light underline hover:text-foreground transition"+ >+ Learn more+ </Link>+ </>+ }+ className={'px-5'}+ >+ <FormControl_Shadcn_>+ <Switch+ checked={field.value === 'public'}+ onCheckedChange={(checked) =>+ field.onChange(checked ? 'public' : 'confidential')+ }+ disabled={isEditMode}+ />+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ </form>+ </Form_Shadcn_>+ </SheetSection>+ <SheetFooter>+ <Button type="default" disabled={isCreating || isUpdating} onClick={onClose}>+ Cancel+ </Button>+ <Button htmlType="submit" form={FORM_ID} loading={isCreating || isUpdating}>+ {isEditMode ? 'Update app' : 'Create app'}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>++ <ConfirmationModal+ variant="warning"+ visible={showRegenerateDialog}+ loading={isRegenerating}+ title="Confirm regenerating client secret"+ confirmLabel="Confirm"+ onCancel={() => setShowRegenerateDialog(false)}+ onConfirm={handleConfirmRegenerate}+ >+ <p className="text-sm text-foreground-light">+ Are you sure you wish to regenerate the client secret for "{appToEdit?.client_name}"?+ You'll need to update it in all applications that use it. This action cannot be undone.+ </p>+ </ConfirmationModal>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/NewOAuthAppBanner.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/NewOAuthAppBanner.tsxindex 9718ffcc647..15db2542317 100644--- a/apps/studio/components/interfaces/Auth/OAuthApps/NewOAuthAppBanner.tsx+++ b/apps/studio/components/interfaces/Auth/OAuthApps/NewOAuthAppBanner.tsx@@ -23,23 +23,23 @@ export const NewOAuthAppBanner = ({ oauthApp, onClose }: NewOAuthAppBannerProps)Do copy this client id and client secret and store it in a secure place - you will notbe able to see it again.</p>- <div className="max-w-xl">+ <div className=""><InputcopyreadOnlysize="small"- className="max-w-xl input-mono"+ className="input-mono"value={oauthApp?.client_id}onChange={() => {}}onCopy={() => toast.success('Client Id copied to clipboard')}/></div>- <div className="max-w-xl">+ <div className=""><InputcopyreadOnlysize="small"- className="max-w-xl input-mono"+ className=" input-mono"value={oauthApp?.client_secret}onChange={() => {}}onCopy={() => toast.success('Client secret copied to clipboard')}@@ -51,7 +51,7 @@ export const NewOAuthAppBanner = ({ oauthApp, onClose }: NewOAuthAppBannerProps)<Buttontype="text"icon={<X />}- className="w-7 h-7 absolute top-3 right-3"+ className="w-7 h-7 absolute top-0 right-0"onClick={onClose}/></Admonition>diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsx b/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsxindex 39edef0400a..037fa676d61 100644--- a/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsx+++ b/apps/studio/components/interfaces/Auth/OAuthApps/OAuthAppsList.tsx@@ -1,5 +1,5 @@import type { OAuthClient } from '@supabase/supabase-js'-import { MoreVertical, Plus, RotateCw, Search, Trash } from 'lucide-react'+import { MoreVertical, Edit, Plus, RotateCw, Search, Trash, X } from 'lucide-react'import Link from 'next/link'import { useRef, useState } from 'react'import { parseAsBoolean, useQueryState } from 'nuqs'@@ -35,20 +35,14 @@ import {} from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { TimestampInfo } from 'ui-patterns/TimestampInfo'-import { CreateOAuthAppSheet } from './CreateOAuthAppSheet'+import { CreateOrUpdateOAuthAppSheet } from './CreateOrUpdateOAuthAppSheet'import { DeleteOAuthAppModal } from './DeleteOAuthAppModal'import { NewOAuthAppBanner } from './NewOAuthAppBanner'--export const OAUTH_APP_SCOPE_OPTIONS = [- { name: 'email', value: 'email' },- { name: 'profile', value: 'profile' },- { name: 'openid', value: 'openid' },-]--export const OAUTH_APP_TYPE_OPTIONS = [- { name: 'Manual', value: 'manual' },- { name: 'Dynamic', value: 'dynamic' },-]+import {+ filterOAuthApps,+ OAUTH_APP_CLIENT_TYPE_OPTIONS,+ OAUTH_APP_REGISTRATION_TYPE_OPTIONS,+} from './oauthApps.utils'export const OAuthAppsList = () => {const { ref: projectRef } = useParams()@@ -57,12 +51,11 @@ export const OAuthAppsList = () => {const [newOAuthApp, setNewOAuthApp] = useState<OAuthClient | undefined>(undefined)const [showRegenerateDialog, setShowRegenerateDialog] = useState(false)const [selectedApp, setSelectedApp] = useState<OAuthClient>()- const [filteredAppTypes, setFilteredAppTypes] = useState<string[]>([])- const [filteredAppScopes, setFilteredAppScopes] = useState<string[]>([])+ const [filteredRegistrationTypes, setFilteredRegistrationTypes] = useState<string[]>([])+ const [filteredClientTypes, setFilteredClientTypes] = useState<string[]>([])const deletingOAuthAppIdRef = useRef<string | null>(null)const { data: supabaseClientData } = useSupabaseClientQuery({ projectRef })-const { data, isLoading, isError, error } = useOAuthServerAppsQuery({projectRef,@@ -87,6 +80,15 @@ export const OAuthAppsList = () => {parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true }))+ const { setValue: setSelectedAppToEdit, value: appToEdit } = useQueryStateWithSelect({+ urlKey: 'edit',+ select: (client_id: string) =>+ client_id ? oAuthApps?.find((app) => app.client_id === client_id) : undefined,+ enabled: !!oAuthApps?.length,+ onError: (_error, selectedId) =>+ handleErrorOnDelete(deletingOAuthAppIdRef, selectedId, `OAuth App not found`),+ })+const { setValue: setSelectedAppToDelete, value: appToDelete } = useQueryStateWithSelect({urlKey: 'delete',select: (client_id: string) =>@@ -106,12 +108,29 @@ export const OAuthAppsList = () => {},})- const handleDeleteClick = (app: OAuthClient) => {- setSelectedAppToDelete(app.client_id)- }+ const handleEditClick = (app: OAuthClient) => setSelectedAppToEdit(app.client_id)+ const handleDeleteClick = (app: OAuthClient) => setSelectedAppToDelete(app.client_id)const [filterString, setFilterString] = useState<string>('')+ const filteredOAuthApps = filterOAuthApps({+ apps: oAuthApps,+ searchString: filterString,+ registrationTypes: filteredRegistrationTypes,+ clientTypes: filteredClientTypes,+ })++ const hasActiveFilters =+ filterString.length > 0 ||+ filteredRegistrationTypes.length > 0 ||+ filteredClientTypes.length > 0++ const handleResetFilters = () => {+ setFilterString('')+ setFilteredRegistrationTypes([])+ setFilteredClientTypes([])+ }+if (isAuthConfigLoading || (isOAuthServerEnabled && isLoading)) {return <GenericSkeletonLoader />}@@ -123,7 +142,7 @@ export const OAuthAppsList = () => {return (<><div className="space-y-4">- {newOAuthApp && (+ {newOAuthApp?.client_secret && (<NewOAuthAppBanner oauthApp={newOAuthApp} onClose={() => setNewOAuthApp(undefined)} />)}{!isOAuthServerEnabled && (@@ -157,29 +176,38 @@ export const OAuthAppsList = () => {onChange={(e) => setFilterString(e.target.value)}/><FilterPopover- name="Type"- options={OAUTH_APP_TYPE_OPTIONS}+ name="Registration Type"+ options={OAUTH_APP_REGISTRATION_TYPE_OPTIONS}labelKey="name"valueKey="value"iconKey="icon"- activeOptions={filteredAppTypes}+ activeOptions={filteredRegistrationTypes}labelClass="text-xs text-foreground-light"maxHeightClass="h-[190px]"className="w-52"- onSaveFilters={setFilteredAppTypes}+ onSaveFilters={setFilteredRegistrationTypes}/><FilterPopover- name="Scope"- options={OAUTH_APP_SCOPE_OPTIONS}+ name="Client Type"+ options={OAUTH_APP_CLIENT_TYPE_OPTIONS}labelKey="name"valueKey="value"iconKey="icon"- activeOptions={filteredAppScopes}+ activeOptions={filteredClientTypes}labelClass="text-xs text-foreground-light"maxHeightClass="h-[190px]"className="w-52"- onSaveFilters={setFilteredAppScopes}+ onSaveFilters={setFilteredClientTypes}/>+ {hasActiveFilters && (+ <Button+ type="default"+ size="tiny"+ className="px-1"+ icon={<X />}+ onClick={handleResetFilters}+ />+ )}</div><div className="flex items-center gap-x-2"><ButtonTooltip@@ -202,70 +230,86 @@ export const OAuthAppsList = () => {</div><div className="w-full overflow-hidden overflow-x-auto">- <Card>- <Table>+ <Card className="@container">+ <Table containerProps={{ stickyLastColumn: true }}><TableHeader><TableRow><TableHead>Name</TableHead><TableHead>Client ID</TableHead>- <TableHead>Type</TableHead>- <TableHead>Scope</TableHead>+ <TableHead>Client Type</TableHead>+ <TableHead>Registration Type</TableHead><TableHead>Created</TableHead>- <TableHead className="w-8"></TableHead>+ <TableHead className="w-8 px-0">+ <div className="!bg-200 px-4 w-full h-full flex items-center border-l @[944px]:border-l-0" />+ </TableHead></TableRow></TableHeader><TableBody>- {oAuthApps.length === 0 && (+ {filteredOAuthApps.length === 0 && (<TableRow><TableCell colSpan={6}><p className="text-foreground-lighter">No OAuth apps found</p></TableCell></TableRow>)}- {oAuthApps.length > 0 &&- oAuthApps.map((app) => (+ {filteredOAuthApps.length > 0 &&+ filteredOAuthApps.map((app) => (<TableRow key={app.client_id} className="w-full">- <TableCell className="w-100 max-w-64 truncate" title={app.client_name}>- {app.client_name}+ <TableCell className="w-48 max-w-48 flex" title={app.client_name}>+ <Button+ type="text"+ className="text-link-table-cell text-sm p-0 hover:bg-transparent title [&>span]:!w-full"+ onClick={() => handleEditClick(app)}+ title={app.client_name}+ >+ {app.client_name}+ </Button></TableCell>- <TableCell className="max-w-40" title={app.client_id}>+ <TableCell title={app.client_id}><Badge className="font-mono">{app.client_id}</Badge></TableCell>- <TableCell className="max-w-40">- {app.client_type === 'public' ? 'Public' : 'Private'}+ <TableCell className="text-xs text-foreground-light max-w-28 capitalize">+ {app.client_type}</TableCell>- <TableCell className="max-w-40">- {app.scope ? (- <Badge>{app.scope}</Badge>- ) : (- <span className="text-xs text-foreground-light">N/A</span>- )}+ <TableCell className="text-xs text-foreground-light max-w-28 capitalize">+ {app.registration_type}</TableCell>- <TableCell className="text-xs text-foreground-light w-1/6">+ <TableCell className="text-xs text-foreground-light min-w-28 max-w-40 w-1/6"><TimestampInfo utcTimestamp={app.created_at} labelFormat="D MMM, YYYY" /></TableCell>- <TableCell>- <div className="flex justify-end items-center">+ <TableCell className="max-w-20 bg-surface-100 @[944px]:hover:bg-surface-200 px-6">+ <div className="absolute top-0 right-0 left-0 bottom-0 flex items-center justify-center border-l @[944px]:border-l-0"><DropdownMenu><DropdownMenuTrigger asChild><Button type="default" className="px-1" icon={<MoreVertical />} /></DropdownMenuTrigger>- <DropdownMenuContent side="bottom" align="end" className="w-52">+ <DropdownMenuContent side="bottom" align="end" className="w-48"><DropdownMenuItemclassName="space-x-2"onClick={() => {- setSelectedApp(app)- setShowRegenerateDialog(true)+ handleEditClick(app)}}>- <RotateCw size={14} />- <p>Regenerate client secret</p>+ <Edit size={12} />+ <p>Update</p></DropdownMenuItem>+ {app.client_type === 'confidential' && (+ <DropdownMenuItem+ className="space-x-2"+ onClick={() => {+ setSelectedApp(app)+ setShowRegenerateDialog(true)+ }}+ >+ <RotateCw size={12} />+ <p>Regenerate client secret</p>+ </DropdownMenuItem>+ )}<DropdownMenuItemclassName="space-x-2"onClick={() => handleDeleteClick(app)}>- <Trash size={14} />+ <Trash size={12} /><p>Delete</p></DropdownMenuItem></DropdownMenuContent>@@ -280,15 +324,22 @@ export const OAuthAppsList = () => {</div></div>- <CreateOAuthAppSheet- visible={showCreateSheet}+ <CreateOrUpdateOAuthAppSheet+ visible={showCreateSheet || !!appToEdit}+ appToEdit={appToEdit}onSuccess={(app) => {+ const isCreating = !appToEditsetShowCreateSheet(false)+ setSelectedAppToEdit(null)setSelectedApp(undefined)- setNewOAuthApp(app)+ // Only show banner for new apps or regenerated secrets, not for simple edits+ if (isCreating || app.client_secret) {+ setNewOAuthApp(app)+ }}}onCancel={() => {setShowCreateSheet(false)+ setSelectedAppToEdit(null)setSelectedApp(undefined)}}/>diff --git a/apps/studio/components/interfaces/Auth/OAuthApps/oauthApps.utils.ts b/apps/studio/components/interfaces/Auth/OAuthApps/oauthApps.utils.tsnew file mode 100644index 00000000000..f1f6ad52c6e--- /dev/null+++ b/apps/studio/components/interfaces/Auth/OAuthApps/oauthApps.utils.ts@@ -0,0 +1,53 @@+import type { OAuthClient } from '@supabase/supabase-js'++export const OAUTH_APP_REGISTRATION_TYPE_OPTIONS = [+ { name: 'Manual', value: 'manual' },+ { name: 'Dynamic', value: 'dynamic' },+]++export const OAUTH_APP_CLIENT_TYPE_OPTIONS = [+ { name: 'Public', value: 'public' },+ { name: 'Confidential', value: 'confidential' },+]++interface FilterOAuthAppsParams {+ apps: OAuthClient[]+ searchString?: string+ registrationTypes?: string[]+ clientTypes?: string[]+}++export function filterOAuthApps({+ apps,+ searchString,+ registrationTypes = [],+ clientTypes = [],+}: FilterOAuthAppsParams): OAuthClient[] {+ return apps.filter((app) => {+ // Filter by search string+ if (searchString) {+ const searchLower = searchString.toLowerCase()+ const matchesName = app.client_name.toLowerCase().includes(searchLower)+ const matchesClientId = app.client_id.toLowerCase().includes(searchLower)+ if (!matchesName && !matchesClientId) {+ return false+ }+ }++ // Filter by registration type+ if (registrationTypes.length > 0) {+ if (!registrationTypes.includes(app.registration_type)) {+ return false+ }+ }++ // Filter by client type+ if (clientTypes.length > 0) {+ if (!clientTypes.includes(app.client_type)) {+ return false+ }+ }++ return true+ })+}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.tsnew file mode 100644index 00000000000..e3d6b7bd41e--- /dev/null+++ b/apps/studio/data/oauth-server-apps/oauth-server-app-update-mutation.ts@@ -0,0 +1,60 @@+import { UpdateOAuthClientParams, SupabaseClient } from '@supabase/supabase-js'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { handleError } from 'data/fetchers'+import type { ResponseError, UseCustomMutationOptions } from 'types'+import { oauthServerAppKeys } from './keys'++export type OAuthServerAppUpdateVariables = UpdateOAuthClientParams & {+ clientId: string+ projectRef?: string+ supabaseClient?: SupabaseClient<any>+}++export async function updateOAuthServerApp({+ clientId,+ projectRef,+ supabaseClient,+ ...params+}: OAuthServerAppUpdateVariables) {+ if (!projectRef) throw new Error('Project reference is required')+ if (!supabaseClient) throw new Error('Supabase client is required')++ const { data, error } = await supabaseClient.auth.admin.oauth.updateClient(clientId, params)++ if (error) return handleError(error)+ return data+}++type OAuthAppUpdateData = Awaited<ReturnType<typeof updateOAuthServerApp>>++export const useOAuthServerAppUpdateMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseCustomMutationOptions<OAuthAppUpdateData, ResponseError, OAuthServerAppUpdateVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()++ return useMutation<OAuthAppUpdateData, ResponseError, OAuthServerAppUpdateVariables>({+ mutationFn: (vars) => updateOAuthServerApp(vars),+ onSuccess: async (data, variables, context) => {+ const { projectRef } = variables+ await queryClient.invalidateQueries({+ queryKey: oauthServerAppKeys.list(projectRef),+ })+ await onSuccess?.(data, variables, context)+ },+ onError: async (data, variables, context) => {+ if (onError === undefined) {+ toast.error(`Failed to update OAuth Server application: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/pages/project/[ref]/auth/oauth-apps.tsx b/apps/studio/pages/project/[ref]/auth/oauth-apps.tsxindex 9bef1ba0308..837250177bd 100644--- a/apps/studio/pages/project/[ref]/auth/oauth-apps.tsx+++ b/apps/studio/pages/project/[ref]/auth/oauth-apps.tsx@@ -3,16 +3,14 @@ import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'import DefaultLayout from 'components/layouts/DefaultLayout'import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'import { FormHeader } from 'components/ui/Forms/FormHeader'+import { DOCS_URL } from 'lib/constants'import type { NextPageWithLayout } from 'types'const OAuthApps: NextPageWithLayout = () => (<ScaffoldContainer><ScaffoldSection><div className="col-span-12">- <FormHeader- title="OAuth Apps"- docsUrl="https://supabase.com/docs/guides/auth/oauth-server"- />+ <FormHeader title="OAuth Apps" docsUrl={`${DOCS_URL}/guides/auth/oauth-server`} /><OAuthAppsList /></div></ScaffoldSection>diff --git a/apps/studio/pages/project/[ref]/auth/oauth-server.tsx b/apps/studio/pages/project/[ref]/auth/oauth-server.tsxindex 4f70f8e00f2..d98b2c4fc5d 100644--- a/apps/studio/pages/project/[ref]/auth/oauth-server.tsx+++ b/apps/studio/pages/project/[ref]/auth/oauth-server.tsx@@ -2,7 +2,9 @@ import { OAuthServerSettingsForm } from 'components/interfaces/Auth/OAuthApps/OAimport AuthLayout from 'components/layouts/AuthLayout/AuthLayout'import DefaultLayout from 'components/layouts/DefaultLayout'import { PageLayout } from 'components/layouts/PageLayout/PageLayout'+import { DocsButton } from 'components/ui/DocsButton'import { ScaffoldContainer } from 'components/layouts/Scaffold'+import { DOCS_URL } from 'lib/constants'import type { NextPageWithLayout } from 'types'const ProvidersPage: NextPageWithLayout = () => {@@ -13,12 +15,15 @@ const ProvidersPage: NextPageWithLayout = () => {)}+const secondaryActions = [<DocsButton key="docs" href={`${DOCS_URL}/guides/auth/oauth-server`} />]+ProvidersPage.getLayout = (page) => (<DefaultLayout><AuthLayout><PageLayouttitle="OAuth Server"subtitle="Configure your project to act as an identity provider for third-party applications"+ secondaryActions={secondaryActions}>{page}</PageLayout>