Skip to content

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

feat: add UI For Auth HTTP Hooks (#22495)

Joel Lee35645efc6f8a
diff --git a/apps/studio/components/interfaces/Auth/Hooks/BasicHooksConfig.tsx b/apps/studio/components/interfaces/Auth/Hooks/BasicHooksConfig.tsx
deleted file mode 100644
index b089b4dc6f4..00000000000
--- a/apps/studio/components/interfaces/Auth/Hooks/BasicHooksConfig.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useParams } from 'common'
-import { useEffect } from 'react'
-import toast from 'react-hot-toast'
-import {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
- Form,
- IconAlertCircle,
- Toggle,
-} from 'ui'
-import { boolean, object, string } from 'yup'
-
-import {
- FormActions,
- FormHeader,
- FormPanel,
- FormSection,
- FormSectionContent,
- FormSectionLabel,
-} from 'components/ui/Forms'
-import { useAuthConfigQuery } from 'data/auth/auth-config-query'
-import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
-import { useCheckPermissions } from 'hooks'
-import SchemaFunctionSelector from './SchemaFunctionSelector'
-
-const schema = object({
- HOOKS_CUSTOM_ACCESS_TOKEN_ENABLED: boolean(),
- HOOKS_CUSTOM_ACCESS_TOKEN_URI: string(),
-})
-
-const formId = 'auth-basic-hooks-form'
-
-const BasicHooksConfig = () => {
- const { ref: projectRef } = useParams()
- const {
- data: authConfig,
- error: authConfigError,
- isLoading,
- isError,
- isSuccess,
- } = useAuthConfigQuery({ projectRef })
- const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()
- const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
-
- // TODO: Remove as any once these properties are defined in Auth Config types
- const INITIAL_VALUES = {
- HOOK_CUSTOM_ACCESS_TOKEN_ENABLED: authConfig?.HOOK_CUSTOM_ACCESS_TOKEN_ENABLED || false,
- HOOK_CUSTOM_ACCESS_TOKEN_URI: authConfig?.HOOK_CUSTOM_ACCESS_TOKEN_URI || '',
- }
-
- const onSubmit = (values: any, { resetForm }: any) => {
- const payload = { ...values }
-
- if (payload.HOOK_CUSTOM_ACCESS_TOKEN_URI === '') {
- payload.HOOK_CUSTOM_ACCESS_TOKEN_URI = null
- }
-
- updateAuthConfig(
- { projectRef: projectRef!, config: payload },
- {
- onError: () => toast.error(`Failed to update settings`),
- onSuccess: () => {
- toast.success(`Successfully updated settings`)
- resetForm({ values: values, initialValues: values })
- },
- }
- )
- }
-
- if (isError) {
- return (
- <Alert_Shadcn_ variant="destructive">
- <IconAlertCircle strokeWidth={2} />
- <AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )
- }
-
- return (
- <Form id={formId} initialValues={INITIAL_VALUES} onSubmit={onSubmit} validationSchema={schema}>
- {({ handleReset, resetForm, values, initialValues, setFieldValue }: any) => {
- const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
-
- // Form is reset once remote data is loaded in store
- // eslint-disable-next-line react-hooks/rules-of-hooks
- useEffect(() => {
- if (isSuccess) {
- resetForm({ values: INITIAL_VALUES, initialValues: INITIAL_VALUES })
- }
- }, [isSuccess])
-
- return (
- <>
- <FormHeader
- title="Auth Hooks (Beta)"
- description="Use PostgreSQL functions to customize the behavior of Supabase Auth to meet your needs."
- />
- <FormPanel
- disabled={true}
- footer={
- <div className="flex py-4 px-8">
- <FormActions
- form={formId}
- isSubmitting={isUpdatingConfig}
- hasChanges={hasChanges}
- handleReset={handleReset}
- disabled={!canUpdateConfig}
- helper={
- !canUpdateConfig
- ? 'You need additional permissions to update authentication settings'
- : undefined
- }
- />
- </div>
- }
- >
- <FormSection
- header={<FormSectionLabel>Customize Access Token (JWT) Claims</FormSectionLabel>}
- >
- <FormSectionContent loading={isLoading}>
- <SchemaFunctionSelector
- id="HOOK_CUSTOM_ACCESS_TOKEN_URI"
- descriptionText="Select the function to be called by Supabase Auth each time a new JWT is created. It should return the claims you wish to be present in the JWT."
- values={values}
- setFieldValue={setFieldValue}
- disabled={!canUpdateConfig}
- />
- {values.HOOK_CUSTOM_ACCESS_TOKEN_URI && (
- <Toggle
- id="HOOK_CUSTOM_ACCESS_TOKEN_ENABLED"
- size="medium"
- label="Enable hook"
- layout="flex"
- disabled={!canUpdateConfig}
- />
- )}
- </FormSectionContent>
- </FormSection>
- <div className="border-t border-muted"></div>
- </FormPanel>
- </>
- )
- }}
- </Form>
- )
-}
-
-export default BasicHooksConfig
diff --git a/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
new file mode 100644
index 00000000000..3752b485925
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Hooks/CreateHookSheet.tsx
@@ -0,0 +1,427 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import randomBytes from 'randombytes'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import toast from 'react-hot-toast'
+import * as z from 'zod'
+
+import { useParams } from 'common'
+import SchemaSelector from 'components/ui/SchemaSelector'
+import { AuthConfigResponse } from 'data/auth/auth-config-query'
+import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
+import { useFlag } from 'hooks'
+import { X } from 'lucide-react'
+import { useEffect, useMemo } from 'react'
+import ReactMarkdown from 'react-markdown'
+import {
+ Button,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Form_Shadcn_,
+ Input_Shadcn_,
+ RadioGroupStacked,
+ RadioGroupStackedItem,
+ Separator,
+ Sheet,
+ SheetClose,
+ SheetContent,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+ Switch,
+ cn,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import FunctionSelector from './FunctionSelector'
+import { HOOKS_DEFINITIONS, HOOK_DEFINITION_TITLE, Hook } from './hooks.constants'
+import { extractMethod, isValidHook } from './hooks.utils'
+
+interface CreateHookSheetProps {
+ visible: boolean
+ onClose: () => void
+ onDelete: () => void
+ title: HOOK_DEFINITION_TITLE | null
+ authConfig: AuthConfigResponse
+}
+
+export function generateAuthHookSecret() {
+ const secretByteLength = 60
+ const buffer = randomBytes(secretByteLength)
+ const base64String = buffer.toString('base64')
+ return `v1,whsec_${base64String}`
+}
+
+const FORM_ID = 'create-edit-auth-hook'
+
+const FormSchema = z
+ .object({
+ hookType: z.string(),
+ enabled: z.boolean(),
+ selectedType: z.union([z.literal('https'), z.literal('postgres')]),
+ httpsValues: z.object({
+ url: z.string(),
+ secret: z.string(),
+ }),
+ postgresValues: z.object({
+ schema: z.string(),
+ functionName: z.string(),
+ }),
+ })
+ .superRefine((data, ctx) => {
+ if (data.selectedType === 'https') {
+ if (!data.httpsValues.url.startsWith('https://')) {
+ ctx.addIssue({
+ path: ['httpsValues', 'url'],
+ code: z.ZodIssueCode.custom,
+ message: 'The URL must start with https://',
+ })
+ }
+ if (!data.httpsValues.secret) {
+ ctx.addIssue({
+ path: ['httpsValues', 'secret'],
+ code: z.ZodIssueCode.custom,
+ message: 'Missing secret value',
+ })
+ }
+ }
+ if (data.selectedType === 'postgres') {
+ if (!data.postgresValues.schema) {
+ ctx.addIssue({
+ path: ['postgresValues', 'schema'],
+ code: z.ZodIssueCode.custom,
+ message: 'You must select a schema',
+ })
+ }
+ if (!data.postgresValues.functionName) {
+ ctx.addIssue({
+ path: ['postgresValues', 'functionName'],
+ code: z.ZodIssueCode.custom,
+ message: 'You must select a Postgres function',
+ })
+ }
+ }
+ return true
+ })
+
+export const CreateHookSheet = ({
+ visible,
+ onClose,
+ onDelete,
+ title,
+ authConfig,
+}: CreateHookSheetProps) => {
+ const { ref: projectRef } = useParams()
+ const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()
+ const httpsAuthHooksEnabled = useFlag('httpsAuthHooksEnabled')
+
+ const definition = useMemo(
+ () => HOOKS_DEFINITIONS.find((d) => d.title === title) || HOOKS_DEFINITIONS[0],
+ [title]
+ )
+
+ const hook: Hook = {
+ ...definition,
+ enabled: authConfig?.[definition.enabledKey] || false,
+ method: extractMethod(
+ authConfig?.[definition.uriKey] || '',
+ authConfig?.[definition.secretsKey] || ''
+ ),
+ }
+
+ // if the hook has all parameters, then it is not being created.
+ const isCreating = !isValidHook(hook)
+
+ const form = useForm<z.infer<typeof FormSchema>>({
+ resolver: zodResolver(FormSchema),
+ defaultValues: {
+ hookType: title || '',
+ enabled: true,
+ selectedType: 'postgres',
+ httpsValues: {
+ url: '',
+ secret: '',
+ },
+ postgresValues: {
+ schema: 'public',
+ functionName: '',
+ },
+ },
+ })
+
+ useEffect(() => {
+ if (visible) {
+ if (definition) {
+ const values = extractMethod(
+ authConfig?.[definition.uriKey] || '',
+ authConfig?.[definition.secretsKey] || ''
+ )
+
+ form.reset({
+ hookType: definition.title,
+ enabled: authConfig?.[definition.enabledKey] || false,
+ selectedType: values.type,
+ httpsValues: {
+ url: (values.type === 'https' && values.url) || '',
+ secret: (values.type === 'https' && values.secret) || '',
+ },
+ postgresValues: {
+ schema: (values.type === 'postgres' && values.schema) || 'public',
+ functionName: (values.type === 'postgres' && values.functionName) || '',
+ },
+ })
+ } else {
+ form.reset({
+ hookType: title || '',
+ enabled: true,
+ selectedType: 'postgres',
+ httpsValues: {
+ url: '',
+ secret: '',
+ },
+ postgresValues: {
+ schema: 'public',
+ functionName: '',
+ },
+ })
+ }
+ }
+ }, [authConfig, title, visible])
+
+ const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (values) => {
+ const definition = HOOKS_DEFINITIONS.find((d) => values.hookType === d.title)
+
+ if (!definition) {
+ return
+ }
+
+ const enabledLabel = definition.enabledKey
+ const uriLabel = definition.uriKey
+ const secretsLabel = definition.secretsKey
+
+ let url = ''
+ if (values.selectedType === 'postgres') {
+ url = `pg-functions://postgres/${values.postgresValues.schema}/${values.postgresValues.functionName}`
+ } else {
+ url = values.httpsValues.url
+ }
+
+ const payload = {
+ [enabledLabel]: values.enabled,
+ [uriLabel]: url,
+ [secretsLabel]: values.selectedType === 'https' ? values.httpsValues.secret : null,
+ }
+
+ updateAuthConfig(
+ { projectRef: projectRef!, config: payload },
+ {
+ onSuccess: () => {
+ toast.success(`Successfully created ${values.hookType}.`)
+ onClose()
+ },
+ }
+ )
+ }
+
+ const values = form.getValues()
+
+ return (
+ <Sheet open={visible} onOpenChange={() => onClose()}>
+ <SheetContent showClose={false} className="flex flex-col gap-0">
+ <SheetHeader className="py-3 flex flex-row justify-between items-center border-b-0">
+ <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">
+ {isCreating ? `Add ${title}` : `Update ${title}`}
+ </SheetTitle>
+ </div>
+ </SheetHeader>
+ <Separator />
+ <Form_Shadcn_ {...form}>
+ <form
+ id={FORM_ID}
+ className="space-y-6 w-full py-8 flex-1"
+ onSubmit={form.handleSubmit(onSubmit)}
+ >
+ <FormField_Shadcn_
+ key="enabled"
+ control={form.control}
+ name="enabled"
+ render={({ field }) => (
+ <FormItemLayout className="px-8" label={`Enable ${values.hookType}`} layout="flex">
+ <FormControl_Shadcn_>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ disabled={field.disabled}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ <Separator />
+ {httpsAuthHooksEnabled && (
+ <FormField_Shadcn_
+ control={form.control}
+ name="selectedType"
+ render={({ field }) => (
+ <FormItemLayout label="Hook type" className="px-8">
+ <FormControl_Shadcn_>
+ <RadioGroupStacked
+ value={values.selectedType}
+ onValueChange={(value) => field.onChange(value)}
+ >
+ <RadioGroupStackedItem
+ value="postgres"
+ id="postgres"
+ key="postgres"
+ label="Postgres"
+ description="Used to call a Postgres function."
+ />
+ <RadioGroupStackedItem
+ value="https"
+ id="https"
+ key="https"
+ label="HTTPS"
+ description="Used to call any HTTPS endpoint."
+ />
+ </RadioGroupStacked>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ )}
+ {values.selectedType === 'postgres' ? (
+ <div className="grid grid-cols-2 gap-8 px-8">
+ <FormField_Shadcn_
+ key="postgresValues.schema"
+ control={form.control}
+ name="postgresValues.schema"
+ render={({ field }) => (
+ <FormItemLayout
+ label="Postgres Schema"
+ description="Postgres schema where the function is defined."
+ >
+ <FormControl_Shadcn_>
+ <SchemaSelector
+ size="small"
+ showError={false}
+ selectedSchemaName={field.value}
+ onSelectSchema={(name) => {
+ field.onChange(name)
+ }}
+ disabled={field.disabled}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ <FormField_Shadcn_
+ key="postgresValues.functionName"
+ control={form.control}
+ name="postgresValues.functionName"
+ render={({ field }) => (
+ <FormItemLayout
+ label="Function name"
+ description="Postgres function which will be called by Supabase Auth each time the hook is triggered."
+ >
+ <FormControl_Shadcn_>
+ <FunctionSelector
+ size="small"
+ schema={values.postgresValues.schema}
+ value={field.value}
+ onChange={field.onChange}
+ disabled={field.disabled}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </div>
+ ) : (
+ <div className="flex flex-col px-8 gap-4">
+ <FormField_Shadcn_
+ key="httpsValues.url"
+ control={form.control}
+ name="httpsValues.url"
+ render={({ field }) => (
+ <FormItemLayout
+ label="URL"
+ description="Supabase Auth will send a HTTPS POST request to this URL each time the hook is triggered."
+ >
+ <FormControl_Shadcn_>
+ <Input_Shadcn_ {...field} />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ <FormField_Shadcn_
+ key="httpsValues.secret"
+ control={form.control}
+ name="httpsValues.secret"
+ render={({ field }) => (
+ <FormItemLayout
+ label="Secret"
+ description={
+ <ReactMarkdown>
+ It should be a base64 encoded hook secret with a prefix `v1,whsec_`. `v1`
+ denotes the signature version, and `whsec_` signifies a symmetric secret.
+ </ReactMarkdown>
+ }
+ >
+ <FormControl_Shadcn_>
+ <div className="flex flex-row">
+ <Input_Shadcn_ {...field} className="rounded-r-none border-r-0" />
+ <Button
+ type="default"
+ size="small"
+ className="rounded-l-none h-[38px]"
+ onClick={() => {
+ const authHookSecret = generateAuthHookSecret()
+ form.setValue('httpsValues.secret', authHookSecret)
+ }}
+ >
+ Generate secret
+ </Button>
+ </div>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </div>
+ )}
+ </form>
+ </Form_Shadcn_>
+ <SheetFooter>
+ {!isCreating && (
+ <div className="flex-1">
+ <Button type="danger" onClick={() => onDelete()}>
+ Delete hook
+ </Button>
+ </div>
+ )}
+
+ <Button disabled={isUpdatingConfig} type="default" onClick={() => onClose()}>
+ Cancel
+ </Button>
+ <Button
+ form={FORM_ID}
+ htmlType="submit"
+ disabled={isUpdatingConfig}
+ loading={isUpdatingConfig}
+ >
+ {isCreating ? 'Create' : 'Update'}
+ </Button>
+ </SheetFooter>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Hooks/EnterpriseHooksConfig.tsx b/apps/studio/components/interfaces/Auth/Hooks/EnterpriseHooksConfig.tsx
deleted file mode 100644
index 7c63d093e00..00000000000
--- a/apps/studio/components/interfaces/Auth/Hooks/EnterpriseHooksConfig.tsx
+++ /dev/null
@@ -1,204 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useParams } from 'common'
-import { useEffect } from 'react'
-import toast from 'react-hot-toast'
-import {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
- Form,
- IconAlertCircle,
- Toggle,
-} from 'ui'
-import { boolean, object, string } from 'yup'
-
-import {
- FormActions,
- FormHeader,
- FormPanel,
- FormSection,
- FormSectionContent,
- FormSectionLabel,
-} from 'components/ui/Forms'
-import UpgradeToPro from 'components/ui/UpgradeToPro'
-import { useAuthConfigQuery } from 'data/auth/auth-config-query'
-import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
-import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions, useSelectedOrganization } from 'hooks'
-import SchemaFunctionSelector from './SchemaFunctionSelector'
-
-const schema = object({
- HOOKS_MFA_VERIFICATION_ATTEMPT_ENABLED: boolean(),
- HOOKS_MFA_VERIFICATION_ATTEMPT_URI: string(),
- HOOKS_PASSWORD_VERIFICATION_ATTEMPT_ENABLED: boolean(),
- HOOKS_PASSWORD_VERIFICATION_ATTEMPT_URI: string(),
-})
-
-const FORM_ID = 'enterprise-hooks-config'
-
-const EnterpriseHooksConfig = () => {
- const { ref: projectRef } = useParams()
- const {
- data: authConfig,
- error: authConfigError,
- isLoading,
- isError,
- isSuccess,
- } = useAuthConfigQuery({ projectRef })
- const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()
- const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
-
- const organization = useSelectedOrganization()
- const { data: subscription, isSuccess: isSuccessSubscription } = useOrgSubscriptionQuery({
- orgSlug: organization?.slug,
- })
-
- const isTeamsEnterprisePlan =
- isSuccessSubscription && subscription?.plan?.id !== 'free' && subscription?.plan?.id !== 'pro'
-
- const INITIAL_VALUES = {
- HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED:
- authConfig?.HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED || false,
- HOOK_MFA_VERIFICATION_ATTEMPT_URI: authConfig?.HOOK_MFA_VERIFICATION_ATTEMPT_URI || '',
- // remove as any when the types are merged in
- HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED:
- (authConfig as any)?.HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED || false,
- HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI:
- (authConfig as any)?.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI || '',
- }
-
- const onSubmit = (values: any, { resetForm }: any) => {
- const payload = { ...values }
- if (payload.HOOK_MFA_VERIFICATION_ATTEMPT_URI === '') {
- payload.HOOK_MFA_VERIFICATION_ATTEMPT_URI = null
- }
- if (payload.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI === '') {
- payload.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI = null
- }
- updateAuthConfig(
- { projectRef: projectRef!, config: payload },
- {
- onError: () => {
- toast.error(`Failed to update settings`)
- },
- onSuccess: () => {
- toast.success(`Successfully updated settings`)
- resetForm({ values: values, initialValues: values })
- },
- }
- )
- }
-
- if (isError) {
- return (
- <Alert_Shadcn_ variant="destructive">
- <IconAlertCircle strokeWidth={2} />
- <AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- )
- }
-
- return (
- <Form id={FORM_ID} initialValues={INITIAL_VALUES} onSubmit={onSubmit} validationSchema={schema}>
- {({ handleReset, resetForm, values, initialValues, setFieldValue }: any) => {
- const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
-
- // Form is reset once remote data is loaded in store
- // eslint-disable-next-line react-hooks/rules-of-hooks
- useEffect(() => {
- if (isSuccess) {
- resetForm({ values: INITIAL_VALUES, initialValues: INITIAL_VALUES })
- }
- }, [isSuccess])
-
- return (
- <>
- <FormHeader
- title="Enterprise Hooks"
- description="Advanced Auth hooks are available to Teams and Enterprise plan customers."
- />
- <FormPanel
- disabled={true}
- footer={
- <div className="flex py-4 px-8">
- <FormActions
- form={FORM_ID}
- isSubmitting={isUpdatingConfig}
- hasChanges={hasChanges}
- handleReset={handleReset}
- disabled={!canUpdateConfig || !isTeamsEnterprisePlan}
- helper={
- !canUpdateConfig
- ? 'You need additional permissions to update authentication settings'
- : undefined
- }
- />
- </div>
- }
- >
- {!isTeamsEnterprisePlan && organization !== undefined && (
- <UpgradeToPro
- primaryText="Upgrade plan"
- secondaryText="Configuring Enterprise Hooks requires a Teams or Enterprise plan."
- projectRef={projectRef!}
- organizationSlug={organization.slug}
- buttonText="Upgrade"
- />
- )}
- <div className={isTeamsEnterprisePlan ? '' : 'opacity-50'}>
- <FormSection header={<FormSectionLabel>MFA Verification Attempt</FormSectionLabel>}>
- <FormSectionContent loading={isLoading}>
- <SchemaFunctionSelector
- id="HOOK_MFA_VERIFICATION_ATTEMPT_URI"
- descriptionText="Select the function to be called by Supabase Auth each time a user tries to verify an MFA factor. Return a decision on whether to reject the attempt and future ones, or to allow the user to keep trying."
- values={values}
- setFieldValue={setFieldValue}
- disabled={!canUpdateConfig || !isTeamsEnterprisePlan}
- />
- {values.HOOK_MFA_VERIFICATION_ATTEMPT_URI && (
- <Toggle
- id="HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED"
- size="small"
- label="Enable hook"
- layout="flex"
- disabled={!canUpdateConfig || !isTeamsEnterprisePlan}
- />
- )}
- </FormSectionContent>
- </FormSection>
- <div className="border-t border-muted"></div>
-
- <FormSection
- header={<FormSectionLabel>Password Verification Attempt</FormSectionLabel>}
- >
- <FormSectionContent loading={isLoading}>
- <SchemaFunctionSelector
- id="HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI"
- descriptionText="Select the function to be called by Supabase Auth each time a user tries to sign in with a password. Return a decision whether to allow the user to reject the attempt, or to allow the user to keep trying."
- values={values}
- setFieldValue={setFieldValue}
- disabled={!canUpdateConfig || !isTeamsEnterprisePlan}
- />
- {values.HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI && (
- <Toggle
- id="HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED"
- size="small"
- label="Enable hook"
- layout="flex"
- disabled={!canUpdateConfig || !isTeamsEnterprisePlan}
- />
- )}
- </FormSectionContent>
- </FormSection>
- </div>
- <div className="border-t border-muted"></div>
- </FormPanel>
- </>
- )
- }}
- </Form>
- )
-}
-
-export default EnterpriseHooksConfig
diff --git a/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx b/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx
index ebc2af7a0a5..e2db6e5bea3 100644
--- a/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx
+++ b/apps/studio/components/interfaces/Auth/Hooks/FunctionSelector.tsx
@@ -11,8 +11,6 @@ import {
CommandList_Shadcn_,
Command_Shadcn_,
IconCheck,
- IconCode,
- IconLoader,
PopoverContent_Shadcn_,
PopoverTrigger_Shadcn_,
Popover_Shadcn_,
@@ -22,14 +20,15 @@ import {
import { convertArgumentTypes } from 'components/interfaces/Database/Functions/Functions.utils'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { useDatabaseFunctionsQuery } from 'data/database-functions/database-functions-query'
+import { Code } from 'lucide-react'
interface FunctionSelectorProps {
className?: string
size?: 'tiny' | 'small'
showError?: boolean
schema?: string
- selectedFunctionName: string
- onSelectFunction: (name: string) => void
+ value: string
+ onChange: (value: string) => void
disabled?: boolean
}
@@ -39,8 +38,8 @@ const FunctionSelector = ({
showError = true,
disabled = false,
schema,
- selectedFunctionName,
- onSelectFunction,
+ value,
+ onChange,
}: FunctionSelectorProps) => {
const { project } = useProjectContext()
const [open, setOpen] = useState(false)
@@ -62,15 +61,8 @@ const FunctionSelector = ({
return (
<div className={className}>
{isLoading && (
- <Button
- type="outline"
- className="w-full [&>span]:w-full"
- icon={<IconLoader className="animate-spin" size={12} />}
- disabled={!!disabled}
- >
- <div className="w-full flex space-x-3 py-0.5">
- <p className="text-xs text-foreground-light">Loading functions...</p>
- </div>
+ <Button type="default" className="justify-start" block size={size} loading>
+ Loading functions...
</Button>
)}
@@ -93,22 +85,20 @@ const FunctionSelector = ({
<PopoverTrigger_Shadcn_ asChild>
<Button
size={size}
- type="outline"
+ type="default"
className={`w-full [&>span]:w-full ${size === 'small' ? 'py-1.5' : ''}`}
iconRight={
- <IconCode className="text-foreground-light rotate-90" strokeWidth={2} size={12} />
+ <Code className="text-foreground-light rotate-90" strokeWidth={2} size={12} />
}
disabled={!!disabled}
>
- <div className="w-full flex space-x-3 py-0.5">
- <p className="text-xs text-foreground-light">function</p>
- <p className="text-xs">
- {selectedFunctionName === '*' ? 'All functions' : selectedFunctionName}
- </p>
+ <div className="w-full flex gap-1">
+ <p className="text-foreground-lighter">function:</p>
+ <p className="text-foreground">{value}</p>
</div>
</Button>
</PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">
+ <PopoverContent_Shadcn_ className="p-0" side="bottom" align="start" sameWidthAsTrigger>
<Command_Shadcn_>
<CommandInput_Shadcn_ placeholder="Search functions..." />
<CommandList_Shadcn_>
@@ -134,16 +124,16 @@ const FunctionSelector = ({
value={func.name.replaceAll('"', '')}
className="cursor-pointer flex items-center justify-between space-x-2 w-full"
onSelect={() => {
- onSelectFunction(func.name)
+ onChange(func.name)
setOpen(false)
}}
onClick={() => {
- onSelectFunction(func.name)
+ onChange(func.name)
setOpen(false)
}}
>
<span>{func.name}</span>
- {selectedFunctionName === func.name && (
+ {value === func.name && (
<IconCheck className="text-brand" strokeWidth={2} />
)}
</CommandItem_Shadcn_>
diff --git a/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx b/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx
new file mode 100644
index 00000000000..e5fdbe8fe51
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Hooks/HookCard.tsx
@@ -0,0 +1,108 @@
+import { Check, Webhook } from 'lucide-react'
+import { Badge, Button, Input } from 'ui'
+import { Hook } from './hooks.constants'
+
+interface HookCardProps {
+ hook: Hook
+ canUpdateConfig: boolean
+ onToggle: (enabled: boolean) => void
+ onSelect: () => void
+}
+
+export const HookCard = ({ hook, canUpdateConfig, onToggle, onSelect }: HookCardProps) => {
+ return (
+ <div className="bg-surface-100 border-default overflow-hidden border shadow px-5 py-4 flex flex-row first:rounded-t-md last:rounded-b-md space-x-4">
+ <div className="">
+ <Webhook size={21} strokeWidth="1" />
+ </div>
+ <div className="flex flex-col flex-0 overflow-y-auto w-full">
+ <span className="text-sm text-foreground">{hook.title}</span>
+ <span className="text-sm text-foreground-lighter">{hook.subtitle}</span>
+ <div className="text-sm flex flex-row space-x-5 py-4">
+ {hook.method.type === 'postgres' ? (
+ <div className="flex flex-col w-full space-y-2">
+ <div className="flex flex-row items-center">
+ <span className="text-foreground-light w-20">type</span>
+ <span className="text-foreground">Postgres function</span>
+ </div>
+ <div className="flex flex-row items-center">
+ <span className="text-foreground-light w-20">schema</span>
+ <Input
+ title={hook.method.schema}
+ copy
+ readOnly
+ disabled
+ className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
+ value={hook.method.schema}
+ onCopy={() => {}}
+ />
+ </div>
+ <div className="flex flex-row items-center">
+ <span className="text-foreground-light w-20">function</span>
+ <Input
+ title={hook.method.functionName}
+ copy
+ readOnly
+ disabled
+ className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
+ value={hook.method.functionName}
+ onCopy={() => {}}
+ />
+ </div>
+ </div>
+ ) : (
+ <div className="flex flex-col w-full space-y-2">
+ <div className="flex flex-row items-center">
+ <span className="text-foreground-light w-20">type</span>
+ <span className="text-foreground">HTTPS endpoint</span>
+ </div>
+ <div className="flex flex-row items-center">
+ <span className="text-foreground-light w-20">endpoint</span>
+ <Input
+ title={hook.method.url}
+ copy
+ readOnly
+ disabled
+ className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
+ value={hook.method.url}
+ onCopy={() => {}}
+ />
+ </div>
+ <div className="flex flex-row items-center">
+ <span className="text-foreground-light w-20">secret</span>
+ <Input
+ copy
+ title={hook.method.secret}
+ reveal={true}
+ readOnly
+ disabled
+ className="input-mono [&>div>div>div>input]:text-xs [&>div>div>div>input]:opacity-100 flex-1"
+ value={hook.method.secret}
+ />
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="flex flex-row gap-2">
+ <Button type="default" disabled={!canUpdateConfig} onClick={() => onSelect()}>
+ Configure hook
+ </Button>
+ </div>
+ </div>
+ <div className="flex-1">
+ {hook.enabled ? (
+ <Badge className="space-x-1" size="large" variant="brand">
+ <div className="h-3.5 w-3.5 bg-brand rounded-full flex justify-center items-center">
+ <Check className="h-2 w-2 text-background-overlay " strokeWidth={6} />
+ </div>
+ <span>Enabled</span>
+ </Badge>
+ ) : (
+ <Badge variant="warning" size="large">
+ <span>Disabled</span>
+ </Badge>
+ )}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx b/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
new file mode 100644
index 00000000000..94ee3b7b4db
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Hooks/HooksListing.tsx
@@ -0,0 +1,191 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { IS_PLATFORM, useParams } from 'common'
+import { useState } from 'react'
+import toast from 'react-hot-toast'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from 'ui'
+
+import { FormHeader } from 'components/ui/Forms'
+import { useAuthConfigQuery } from 'data/auth/auth-config-query'
+import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useCheckPermissions, useSelectedOrganization } from 'hooks'
+import { AlertCircle, ChevronDown } from 'lucide-react'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { CreateHookSheet } from './CreateHookSheet'
+import { HookCard } from './HookCard'
+import { HOOKS_DEFINITIONS, HOOK_DEFINITION_TITLE, Hook } from './hooks.constants'
+import { extractMethod, isValidHook } from './hooks.utils'
+
+export const HooksListing = () => {
+ const { ref: projectRef } = useParams()
+ const { data: authConfig, error: authConfigError, isError } = useAuthConfigQuery({ projectRef })
+ const organization = useSelectedOrganization()
+ const { data: subscription } = useOrgSubscriptionQuery(
+ { orgSlug: organization?.slug },
+ { enabled: IS_PLATFORM }
+ )
+
+ const [selectedHook, setSelectedHook] = useState<HOOK_DEFINITION_TITLE | null>(null)
+ const [selectedHookForDeletion, setSelectedHookForDeletion] = useState<Hook | null>(null)
+
+ const { mutateAsync: updateAuthConfig } = useAuthConfigUpdateMutation()
+ const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')
+
+ if (isError) {
+ return (
+ <Alert_Shadcn_ variant="destructive">
+ <AlertCircle strokeWidth={2} />
+ <AlertTitle_Shadcn_>Failed to retrieve auth configuration</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>{authConfigError.message}</AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )
+ }
+
+ // configuration for all auth hooks.
+ const hooks: Hook[] = HOOKS_DEFINITIONS.map((definition) => {
+ return {
+ ...definition,
+ enabled: authConfig?.[definition.enabledKey] || false,
+ method: extractMethod(
+ authConfig?.[definition.uriKey] || '',
+ authConfig?.[definition.secretsKey] || ''
+ ),
+ }
+ })
+
+ const nonEnterpriseHookOptions = hooks.filter((h) => !isValidHook(h) && !h.enterprise)
+ const enterpriseHookOptions = hooks.filter((h) => !isValidHook(h) && h.enterprise)
+
+ return (
+ <>
+ <FormHeader
+ title="Auth Hooks"
+ description="Use Postgres functions or HTTP endpoints to customize the behavior of Supabase Auth to meet your needs."
+ actions={
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="default"
+ iconRight={<ChevronDown className="w-4 h-4" strokeWidth={1} />}
+ >
+ Add hook
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-76 p-0" align="end">
+ <div className="p-1">
+ {nonEnterpriseHookOptions.map((h) => (
+ <DropdownMenuItem key={h.title} onClick={() => setSelectedHook(h.title)}>
+ {h.title}
+ </DropdownMenuItem>
+ ))}
+ </div>
+ {nonEnterpriseHookOptions.length > 0 && <DropdownMenuSeparator />}
+
+ <div className="bg-surface-200 p-1 -mt-2">
+ {subscription?.plan.id !== 'enterprise' && (
+ <DropdownMenuLabel className="grid gap-1 bg-surface-200">
+ <p className="text-foreground-light">Enterprise plan required</p>
+ <p className="text-foreground-lighter text-xs">
+ The following hooks are not available on{' '}
+ <a
+ target="_href"
+ href="https://forms.supabase.com/enterprise"
+ className="underline"
+ >
+ your plan
+ </a>
+ .
+ </p>
+ </DropdownMenuLabel>
+ )}
+ {enterpriseHookOptions.map((h) => (
+ <DropdownMenuItem
+ key={h.title}
+ disabled={true}
+ className="cursor-not-allowed"
+ onClick={() => setSelectedHook(h.title)}
+ >
+ {h.title}
+ </DropdownMenuItem>
+ ))}
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ }
+ />
+ <div className="pb-2 -space-y-px">
+ {hooks
+ .filter((h) => isValidHook(h))
+ .map((hook) => {
+ return (
+ <HookCard
+ key={hook.enabledKey}
+ hook={hook}
+ canUpdateConfig={canUpdateConfig}
+ onToggle={(enabled) =>
+ updateAuthConfig({
+ projectRef: projectRef!,
+ config: { [hook.enabledKey]: enabled },
+ })
+ }
+ onSelect={() => {
+ setSelectedHook(hook.title)
+ }}
+ />
+ )
+ })}
+ </div>
+ <CreateHookSheet
+ title={selectedHook}
+ visible={!!selectedHook}
+ onDelete={() => {
+ const hook = hooks.find((h) => h.title === selectedHook)
+ if (hook) {
+ setSelectedHookForDeletion(hook)
+ }
+ }}
+ onClose={() => setSelectedHook(null)}
+ authConfig={authConfig!}
+ />
+ <ConfirmationModal
+ visible={!!selectedHookForDeletion}
+ variant="destructive"
+ title="Confirm to delete"
+ confirmLabel="Delete"
+ confirmLabelLoading="Deleting"
+ onCancel={() => setSelectedHookForDeletion(null)}
+ onConfirm={async () => {
+ if (!selectedHookForDeletion) {
+ return
+ }
+ await updateAuthConfig({
+ projectRef: projectRef!,
+ config: {
+ [selectedHookForDeletion.enabledKey]: false,
+ [selectedHookForDeletion.uriKey]: null,
+ [selectedHookForDeletion.secretsKey]: null,
+ },
+ })
+ toast.success(`${selectedHookForDeletion.title} has been deleted.`)
+ setSelectedHookForDeletion(null)
+ setSelectedHook(null)
+ }}
+ >
+ <p className="py-4 text-sm text-foreground-light">
+ {`Are you sure you want to delete the ${selectedHookForDeletion?.title}?`}
+ </p>
+ </ConfirmationModal>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Auth/Hooks/SchemaFunctionSelector.tsx b/apps/studio/components/interfaces/Auth/Hooks/SchemaFunctionSelector.tsx
deleted file mode 100644
index a15fa0701ce..00000000000
--- a/apps/studio/components/interfaces/Auth/Hooks/SchemaFunctionSelector.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { useState, useEffect } from 'react'
-
-import SchemaSelector from 'components/ui/SchemaSelector'
-import FunctionSelector from './FunctionSelector'
-
-interface SchemaFunctionSelectorProps {
- id: string
- values: any
- setFieldValue: (field: string, value: any) => void
- descriptionText?: string
- disabled?: boolean
-}
-
-const SchemaFunctionSelector = ({
- id,
- values,
- descriptionText,
- setFieldValue,
- disabled = false,
-}: SchemaFunctionSelectorProps) => {
- const [_proto, _x, _db, schema, func] = (values[id] || '').split('/')
- // select the public schema by default
- const [selectedSchema, setSelectedSchema] = useState(schema || 'public')
- const [selectedFunc, setSelectedFunc] = useState(func || '')
-
- useEffect(() => {
- if (schema) {
- setSelectedSchema(schema)
- }
- }, [schema])
-
- useEffect(() => {
- if (func) {
- setSelectedFunc(func)
- }
- }, [func])
-
- return (
- <div className="flex flex-col gap-2">
- <SchemaSelector
- size="tiny"
- showError={false}
- selectedSchemaName={selectedSchema}
- onSelectSchema={(name) => {
- setSelectedSchema(name)
- setSelectedFunc('')
- setFieldValue(id, '')
- }}
- disabled={!!disabled || !values}
- />
- <FunctionSelector
- size="tiny"
- schema={selectedSchema}
- selectedFunctionName={selectedFunc}
- onSelectFunction={(name) => {
- setSelectedFunc(name)
- setFieldValue(id, `pg-functions://postgres/${selectedSchema}/${name}`)
- }}
- disabled={!!disabled || !values}
- />
- {descriptionText && (
- <div className="mt-2 text-foreground-lighter leading-normal text-sm">{descriptionText}</div>
- )}
- </div>
- )
-}
-
-export default SchemaFunctionSelector
diff --git a/apps/studio/components/interfaces/Auth/Hooks/hooks.constants.ts b/apps/studio/components/interfaces/Auth/Hooks/hooks.constants.ts
new file mode 100644
index 00000000000..a120817513b
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Hooks/hooks.constants.ts
@@ -0,0 +1,60 @@
+export const HOOKS_DEFINITIONS = [
+ {
+ title: 'Send SMS hook',
+ subtitle: 'Will be called by Supabase Auth each time an SMS message needs to be sent.',
+ enabledKey: 'HOOK_SEND_SMS_ENABLED',
+ uriKey: 'HOOK_SEND_SMS_URI',
+ secretsKey: 'HOOK_SEND_SMS_SECRETS',
+ enterprise: false,
+ },
+ {
+ title: 'Send Email hook',
+ subtitle: 'Will be called by Supabase Auth each time an email message needs to be sent.',
+ enabledKey: 'HOOK_SEND_EMAIL_ENABLED',
+ uriKey: 'HOOK_SEND_EMAIL_URI',
+ secretsKey: 'HOOK_SEND_EMAIL_SECRETS',
+ enterprise: false,
+ },
+ {
+ title: 'Customize Access Token (JWT) Claims hook',
+ subtitle:
+ 'Will be called by Supabase Auth each time a new JWT is created. It should return the claims you wish to be present in the JWT.',
+ enabledKey: 'HOOK_CUSTOM_ACCESS_TOKEN_ENABLED',
+ uriKey: 'HOOK_CUSTOM_ACCESS_TOKEN_URI',
+ secretsKey: 'HOOK_CUSTOM_ACCESS_TOKEN_SECRETS',
+ enterprise: false,
+ },
+ {
+ title: 'MFA Verification Attempt hook',
+ subtitle:
+ 'Will be called by Supabase Auth each time a user tries to verify an MFA factor. Return a decision on whether to reject the attempt and future ones, or to allow the user to keep trying.',
+ enabledKey: 'HOOK_MFA_VERIFICATION_ATTEMPT_ENABLED',
+ uriKey: 'HOOK_MFA_VERIFICATION_ATTEMPT_URI',
+ secretsKey: 'HOOK_MFA_VERIFICATION_ATTEMPT_SECRETS',
+ enterprise: true,
+ },
+ {
+ title: 'Password Verification Attempt hook',
+ subtitle:
+ 'Will be called by Supabase Auth each time a user tries to sign in with a password. Return a decision whether to allow the user to reject the attempt, or to allow the user to keep trying.',
+ enabledKey: 'HOOK_PASSWORD_VERIFICATION_ATTEMPT_ENABLED',
+ uriKey: 'HOOK_PASSWORD_VERIFICATION_ATTEMPT_URI',
+ secretsKey: 'HOOK_PASSWORD_VERIFICATION_ATTEMPT_SECRETS',
+ enterprise: true,
+ },
+] as const
+
+export type HOOK_DEFINITION_TITLE = (typeof HOOKS_DEFINITIONS)[number]['title']
+
+export interface Hook {
+ title: HOOK_DEFINITION_TITLE
+ subtitle: string
+ enabled: boolean
+ enabledKey: string
+ uriKey: string
+ secretsKey: string
+ method:
+ | { type: 'postgres'; schema: string; functionName: string }
+ | { type: 'https'; url: string; secret: string }
+ enterprise: boolean
+}
diff --git a/apps/studio/components/interfaces/Auth/Hooks/hooks.utils.ts b/apps/studio/components/interfaces/Auth/Hooks/hooks.utils.ts
new file mode 100644
index 00000000000..7a801cca980
--- /dev/null
+++ b/apps/studio/components/interfaces/Auth/Hooks/hooks.utils.ts
@@ -0,0 +1,29 @@
+import { Hook } from './hooks.constants'
+
+export const extractMethod = (
+ uri: string,
+ secret?: string
+):
+ | { type: 'postgres'; schema: string; functionName: string }
+ | { type: 'https'; url: string; secret: string } => {
+ if (uri.startsWith('https')) {
+ return { type: 'https', url: uri, secret: secret || '' }
+ } else {
+ const [_proto, _x, _db, schema, functionName] = (uri || '').split('/')
+
+ return {
+ type: 'postgres',
+ schema: schema || '',
+ functionName: functionName || '',
+ }
+ }
+}
+
+export const isValidHook = (h: Hook) => {
+ return (
+ (h.method.type === 'postgres' &&
+ h.method.schema.length > 0 &&
+ h.method.functionName.length > 0) ||
+ (h.method.type === 'https' && h.method.url.startsWith('https') && h.method.secret.length > 0)
+ )
+}
diff --git a/apps/studio/package.json b/apps/studio/package.json
index 8f7bbcb431a..6d01eedea20 100644
--- a/apps/studio/package.json
+++ b/apps/studio/package.json
@@ -72,6 +72,7 @@
"path-to-regexp": "^6.2.0",
"pg-minify": "^1.6.3",
"prism-react-renderer": "^2.3.1",
+ "randombytes": "^2.1.0",
"react": "^18.2.0",
"react-beautiful-dnd": "^13.1.0",
"react-contexify": "^5.0.0",
@@ -122,6 +123,7 @@
"@types/lodash": "^4.14.172",
"@types/markdown-table": "^3.0.0",
"@types/papaparse": "^5.3.1",
+ "@types/randombytes": "^2.0.3",
"@types/react": "^18.2.24",
"@types/react-beautiful-dnd": "^13.1.2",
"@types/react-csv": "^1.1.2",
diff --git a/apps/studio/pages/project/[ref]/auth/hooks.tsx b/apps/studio/pages/project/[ref]/auth/hooks.tsx
index 7713c734dce..c6bd000e3df 100644
--- a/apps/studio/pages/project/[ref]/auth/hooks.tsx
+++ b/apps/studio/pages/project/[ref]/auth/hooks.tsx
@@ -1,9 +1,8 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import BasicHooksConfig from 'components/interfaces/Auth/Hooks/BasicHooksConfig'
-import EnterpriseHooksConfig from 'components/interfaces/Auth/Hooks/EnterpriseHooksConfig'
+import { HooksListing } from 'components/interfaces/Auth/Hooks/HooksListing'
import { AuthLayout } from 'components/layouts'
-import { FormsContainer } from 'components/ui/Forms'
+import { ScaffoldContainer } from 'components/layouts/Scaffold'
import NoPermission from 'components/ui/NoPermission'
import { useCheckPermissions, usePermissionsLoaded } from 'hooks'
import type { NextPageWithLayout } from 'types'
@@ -16,12 +15,9 @@ const Hooks: NextPageWithLayout = () => {
return <NoPermission isFullPage resourceText="access your project's auth hooks" />
} else {
return (
- <FormsContainer>
- <div className="flex flex-col gap-8">
- <BasicHooksConfig />
- <EnterpriseHooksConfig />
- </div>
- </FormsContainer>
+ <ScaffoldContainer className="pt-12 pb-20">
+ <HooksListing />
+ </ScaffoldContainer>
)
}
}
diff --git a/package-lock.json b/package-lock.json
index 2f4c0f13edd..7df8ef1b647 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -2640,6 +2640,7 @@
"path-to-regexp": "^6.2.0",
"pg-minify": "^1.6.3",
"prism-react-renderer": "^2.3.1",
+ "randombytes": "^2.1.0",
"react": "^18.2.0",
"react-beautiful-dnd": "^13.1.0",
"react-contexify": "^5.0.0",
@@ -2690,6 +2691,7 @@
"@types/lodash": "^4.14.172",
"@types/markdown-table": "^3.0.0",
"@types/papaparse": "^5.3.1",
+ "@types/randombytes": "^2.0.3",
"@types/react": "^18.2.24",
"@types/react-beautiful-dnd": "^13.1.2",
"@types/react-csv": "^1.1.2",
@@ -19990,6 +19992,15 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/randombytes": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/@types/randombytes/-/randombytes-2.0.3.tgz",
+ "integrity": "sha512-+NRgihTfuURllWCiIAhm1wsJqzsocnqXM77V/CalsdJIYSRGEHMnritxh+6EsBklshC+clo1KgnN14qgSGeQdw==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/range-parser": {
"version": "1.2.5",
"dev": true,
@@ -42052,7 +42063,8 @@
},
"node_modules/randombytes": {
"version": "2.1.0",
- "license": "MIT",
+ "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
+ "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
"dependencies": {
"safe-buffer": "^5.1.0"
}
diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.ts
index f4c190210a0..e3d447e8361 100644
--- a/packages/api-types/types/api.d.ts
+++ b/packages/api-types/types/api.d.ts
@@ -160,7 +160,7 @@ export interface paths {
}
'/platform/organizations/{slug}/roles': {
/** Gets the given organization's roles */
- get: operations['OrganizationRolesController_addMember']
+ get: operations['OrganizationRolesController_getAllRolesV2']
}
'/platform/organizations/{slug}/tax-ids': {
/** Gets the given organization's tax IDs */
@@ -199,27 +199,34 @@ export interface paths {
get: operations['OrgAuditLogsController_getAuditLogs']
}
'/platform/organizations/{slug}/members/invite': {
- /** Gets invited users */
+ /**
+ * Gets invited users
+ * @deprecated
+ */
get: operations['OrganizationInviteController_getInvitedUsers']
- /** Invites user */
+ /**
+ * Invites user
+ * @deprecated
+ */
post: operations['OrganizationInviteController_inviteUser']
- /** Delete invited user */
+ /**
+ * Delete invited user
+ * @deprecated
+ */
delete: operations['OrganizationInviteController_deleteInvitedUser']
}
'/platform/organizations/{slug}/members/join': {
- /** Gets invite */
+ /**
+ * Gets invite
+ * @deprecated
+ */
get: operations['JoinController_getInvite']
- /** Joins organization */
+ /**
+ * Joins organization
+ * @deprecated
+ */
post: operations['JoinController_joinOrganization']
}
- '/platform/organizations/{slug}/members/leave': {
- /** Leaves the given organization */
- post: operations['MembersDeprecatedController_leaveOrganization']
- }
- '/platform/organizations/{slug}/members/remove': {
- /** Leaves the given organization */
- delete: operations['MembersDeprecatedController_removeMember']
- }
'/platform/organizations/{slug}/members': {
/** Gets organization's members */
get: operations['MembersController_getMembers']
@@ -227,13 +234,33 @@ export interface paths {
'/platform/organizations/{slug}/members/{gotrue_id}': {
/** Removes organization member */
delete: operations['MembersController_deleteMember']
- /** Updates organization member */
- patch: operations['MembersController_updateMember']
+ /** Updates organization member role */
+ patch: operations['MembersController_updateMemberRoleV2']
+ }
+ '/platform/organizations/{slug}/members/{gotrue_id}/roles/{role_id}': {
+ /** Removes organization member */
+ delete: operations['MembersController_deleteMemberRole']
}
'/platform/organizations/{slug}/members/reached-free-project-limit': {
/** Gets organization members who have reached their free project limit */
get: operations['ReachedFreeProjectLimitController_getMembersWhoReachedFreeProjectLimit']
}
+ '/platform/organizations/{slug}/members/invitations': {
+ /** Gets organization invitations */
+ get: operations['InvitationsController_getAllInvitations']
+ /** Creates organization invitation */
+ post: operations['InvitationsController_createInvitation']
+ }
+ '/platform/organizations/{slug}/members/invitations/{token}': {
+ /** Gets organization invitation by token */
+ get: operations['InvitationsController_getInvitationByToken']
+ /** Accepts organization invitation by token */
+ post: operations['InvitationsController_acceptInvitationByToken']
+ }
+ '/platform/organizations/{slug}/members/invitations/{id}': {
+ /** Deletes organization invitation with given id */
+ delete: operations['InvitationsController_deleteInvitation']
+ }
'/platform/organizations/{slug}/payments': {
/** Gets Stripe payment methods for the given organization */
get: operations['PaymentsController_getPaymentMethods']
@@ -1172,20 +1199,35 @@ export interface paths {
}
'/v0/organizations/{slug}/roles': {
/** Gets the given organization's roles */
- get: operations['OrganizationRolesController_addMember']
+ get: operations['OrganizationRolesController_getAllRolesV2']
}
'/v0/organizations/{slug}/members/invite': {
- /** Gets invited users */
+ /**
+ * Gets invited users
+ * @deprecated
+ */
get: operations['OrganizationInviteController_getInvitedUsers']
- /** Invites user */
+ /**
+ * Invites user
+ * @deprecated
+ */
post: operations['OrganizationInviteController_inviteUser']
- /** Delete invited user */
+ /**
+ * Delete invited user
+ * @deprecated
+ */
delete: operations['OrganizationInviteController_deleteInvitedUser']
}
'/v0/organizations/{slug}/members/join': {
- /** Gets invite */
+ /**
+ * Gets invite
+ * @deprecated
+ */
get: operations['JoinController_getInvite']
- /** Joins organization */
+ /**
+ * Joins organization
+ * @deprecated
+ */
post: operations['JoinController_joinOrganization']
}
'/v0/organizations/{slug}/members': {
@@ -1195,8 +1237,12 @@ export interface paths {
'/v0/organizations/{slug}/members/{gotrue_id}': {
/** Removes organization member */
delete: operations['MembersController_deleteMember']
- /** Updates organization member */
- patch: operations['MembersController_updateMember']
+ /** Updates organization member role */
+ patch: operations['MembersController_updateMemberRoleV2']
+ }
+ '/v0/organizations/{slug}/members/{gotrue_id}/roles/{role_id}': {
+ /** Removes organization member */
+ delete: operations['MembersController_deleteMemberRole']
}
'/v0/pg-meta/{ref}/column-privileges': {
/** Retrieve column privileges */
@@ -2576,9 +2622,21 @@ export interface components {
stripeAccount?: string
}
}
- Role: {
+ OrganizationRole: {
id: number
name: string
+ description: string
+ }
+ OrganizationRoleV2: {
+ id: number
+ name: string
+ description: string
+ project_ids: number[]
+ base_role_id: number
+ }
+ OrganizationRoleResponseV2: {
+ org_scoped_roles: components['schemas']['OrganizationRoleV2'][]
+ project_scoped_roles: components['schemas']['OrganizationRoleV2'][]
}
TaxId: {
id: string
@@ -2738,9 +2796,6 @@ export interface components {
slug: string
stripe_customer_id: string
}
- RemoveMemberBody: {
- member_id: number
- }
Member: {
gotrue_id: string
primary_email: string | null
@@ -2751,11 +2806,37 @@ export interface components {
UpdateMemberBody: {
role_id: number
}
+ UpdateMemberRoleBodyV2: {
+ role_id: number
+ role_scoped_projects?: string[]
+ }
MemberWithFreeProjectLimit: {
free_project_limit: number
primary_email: string
username: string
}
+ Invitation: {
+ id: number
+ invited_at: string
+ invited_email: string
+ role_id: number
+ }
+ InvitationResponse: {
+ invitations: components['schemas']['Invitation'][]
+ }
+ InvitationByTokenResponse: {
+ organization_name: string
+ invite_id?: number
+ token_does_not_exist: boolean
+ email_match: boolean
+ authorized_user: boolean
+ expired_token: boolean
+ }
+ CreateInvitationBody: {
+ email: string
+ role_id: number
+ role_scoped_projects?: string[]
+ }
Payment: {
id: string
object: string
@@ -6931,7 +7012,7 @@ export interface operations {
}
}
/** Gets the given organization's roles */
- OrganizationRolesController_addMember: {
+ OrganizationRolesController_getAllRolesV2: {
parameters: {
path: {
/** @description Organization slug */
@@ -6941,7 +7022,7 @@ export interface operations {
responses: {
200: {
content: {
- 'application/json': components['schemas']['Role'][]
+ 'application/json': components['schemas']['OrganizationRoleResponseV2']
}
}
/** @description Failed to retrieve the organization's roles */
@@ -7200,7 +7281,10 @@ export interface operations {
}
}
}
- /** Gets invited users */
+ /**
+ * Gets invited users
+ * @deprecated
+ */
OrganizationInviteController_getInvitedUsers: {
parameters: {
path: {
@@ -7220,7 +7304,10 @@ export interface operations {
}
}
}
- /** Invites user */
+ /**
+ * Invites user
+ * @deprecated
+ */
OrganizationInviteController_inviteUser: {
parameters: {
path: {
@@ -7245,7 +7332,10 @@ export interface operations {
}
}
}
- /** Delete invited user */
+ /**
+ * Delete invited user
+ * @deprecated
+ */
OrganizationInviteController_deleteInvitedUser: {
parameters: {
query: {
@@ -7266,7 +7356,10 @@ export interface operations {
}
}
}
- /** Gets invite */
+ /**
+ * Gets invite
+ * @deprecated
+ */
JoinController_getInvite: {
parameters: {
query: {
@@ -7289,7 +7382,10 @@ export interface operations {
}
}
}
- /** Joins organization */
+ /**
+ * Joins organization
+ * @deprecated
+ */
JoinController_joinOrganization: {
parameters: {
query: {
@@ -7312,8 +7408,8 @@ export interface operations {
}
}
}
- /** Leaves the given organization */
- MembersDeprecatedController_leaveOrganization: {
+ /** Gets organization's members */
+ MembersController_getMembers: {
parameters: {
path: {
/** @description Organization slug */
@@ -7321,44 +7417,82 @@ export interface operations {
}
}
responses: {
- 201: {
+ 200: {
content: {
- 'application/json': Record<string, never>
+ 'application/json': components['schemas']['Member'][]
}
}
- /** @description Failed to leave organization */
+ /** @description Failed to retrieve organization's members */
500: {
content: never
}
}
}
- /** Leaves the given organization */
- MembersDeprecatedController_removeMember: {
+ /** Removes organization member */
+ MembersController_deleteMember: {
parameters: {
path: {
/** @description Organization slug */
slug: string
+ gotrue_id: string
+ }
+ }
+ responses: {
+ 200: {
+ content: never
+ }
+ /** @description Failed to remove organization member */
+ 500: {
+ content: never
+ }
+ }
+ }
+ /** Updates organization member role */
+ MembersController_updateMemberRoleV2: {
+ parameters: {
+ path: {
+ /** @description Organization slug */
+ slug: string
+ gotrue_id: string
}
}
requestBody: {
content: {
- 'application/json': components['schemas']['RemoveMemberBody']
+ 'application/json': components['schemas']['UpdateMemberRoleBodyV2']
}
}
responses: {
200: {
- content: {
- 'application/json': Record<string, never>
- }
+ content: never
}
- /** @description Failed to leave organization */
+ /** @description Failed to update organization member role */
500: {
content: never
}
}
}
- /** Gets organization's members */
- MembersController_getMembers: {
+ /** Removes organization member */
+ MembersController_deleteMemberRole: {
+ parameters: {
+ path: {
+ /** @description Organization slug */
+ slug: string
+ gotrue_id: string
+ role_id: string
+ }
+ }
+ responses: {
+ 200: {
+ content: never
+ }
+ /** @description Failed to remove organization member */
+ 500: {
+ content: never
+ }
+ }
+ }
+ /** Gets organization members who have reached their free project limit */
+ ReachedFreeProjectLimitController_getMembersWhoReachedFreeProjectLimit: {
parameters: {
path: {
/** @description Organization slug */
@@ -7368,73 +7502,112 @@ export interface operations {
responses: {
200: {
content: {
- 'application/json': components['schemas']['Member'][]
+ 'application/json': components['schemas']['MemberWithFreeProjectLimit'][]
}
}
- /** @description Failed to retrieve organization's members */
+ /** @description Failed to retrieve organization members who have reached their free project limit */
500: {
content: never
}
}
}
- /** Removes organization member */
- MembersController_deleteMember: {
+ /** Gets organization invitations */
+ InvitationsController_getAllInvitations: {
parameters: {
path: {
/** @description Organization slug */
slug: string
- gotrue_id: string
}
}
responses: {
200: {
- content: never
+ content: {
+ 'application/json': components['schemas']['InvitationResponse']
+ }
}
- /** @description Failed to remove organization member */
+ /** @description Failed to get organization invitations */
500: {
content: never
}
}
}
- /** Updates organization member */
- MembersController_updateMember: {
+ /** Creates organization invitation */
+ InvitationsController_createInvitation: {
parameters: {
path: {
/** @description Organization slug */
slug: string
- gotrue_id: string
}
}
requestBody: {
content: {
- 'application/json': components['schemas']['UpdateMemberBody']
+ 'application/json': components['schemas']['CreateInvitationBody']
}
}
responses: {
- 200: {
+ 201: {
content: never
}
- /** @description Failed to update organization member */
+ /** @description Failed to create organization invitation */
500: {
content: never
}
}
}
- /** Gets organization members who have reached their free project limit */
- ReachedFreeProjectLimitController_getMembersWhoReachedFreeProjectLimit: {
+ /** Gets organization invitation by token */
+ InvitationsController_getInvitationByToken: {
parameters: {
path: {
/** @description Organization slug */
slug: string
+ token: string
}
}
responses: {
200: {
content: {
- 'application/json': components['schemas']['MemberWithFreeProjectLimit'][]
+ 'application/json': components['schemas']['InvitationByTokenResponse']
}
}
- /** @description Failed to retrieve organization members who have reached their free project limit */
+ /** @description Failed to get organization invitation by token */
+ 500: {
+ content: never
+ }
+ }
+ }
+ /** Accepts organization invitation by token */
+ InvitationsController_acceptInvitationByToken: {
+ parameters: {
+ path: {
+ /** @description Organization slug */
+ slug: string
+ token: string
+ }
+ }
+ responses: {
+ 201: {
+ content: never
+ }
+ /** @description Failed to accept organization invitation by token */
+ 500: {
+ content: never
+ }
+ }
+ }
+ /** Deletes organization invitation with given id */
+ InvitationsController_deleteInvitation: {
+ parameters: {
+ path: {
+ /** @description Organization slug */
+ slug: string
+ id: number
+ }
+ }
+ responses: {
+ 200: {
+ content: never
+ }
+ /** @description Failed to delete organization invitation with given id */
500: {
content: never
}